Skip to main content

rustdoc/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 mut html = String::new();
25//! md.write_into(&mut html).unwrap();
26//! // ... something using html
27//! ```
28
29use std::borrow::Cow;
30use std::collections::VecDeque;
31use std::fmt::{self, Write};
32use std::iter::Peekable;
33use std::ops::{ControlFlow, Range};
34use std::path::PathBuf;
35use std::str::{self, CharIndices};
36use std::sync::atomic::AtomicUsize;
37use std::sync::{Arc, Weak};
38
39use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
40use rustc_errors::{Diag, DiagMessage};
41use rustc_hir::def_id::LocalDefId;
42use rustc_middle::ty::TyCtxt;
43pub(crate) use rustc_resolve::rustdoc::main_body_opts;
44use rustc_resolve::rustdoc::may_be_doc_link;
45use rustc_resolve::rustdoc::pulldown_cmark::{
46    self, BrokenLink, CodeBlockKind, CowStr, Event, LinkType, Options, Parser, Tag, TagEnd, html,
47};
48use rustc_span::edition::Edition;
49use rustc_span::{Span, Symbol};
50use tracing::{debug, trace};
51
52use crate::clean::RenderedLink;
53use crate::doctest;
54use crate::doctest::GlobalTestOptions;
55use crate::html::escape::{Escape, EscapeBodyText};
56use crate::html::highlight;
57use crate::html::length_limit::HtmlWithLimit;
58use crate::html::render::small_url_encode;
59use crate::html::toc::{Toc, TocBuilder};
60
61mod footnotes;
62#[cfg(test)]
63mod tests;
64
65const MAX_HEADER_LEVEL: u32 = 6;
66
67/// Options for rendering Markdown in summaries (e.g., in search results).
68pub(crate) fn summary_opts() -> Options {
69    Options::ENABLE_TABLES
70        | Options::ENABLE_FOOTNOTES
71        | Options::ENABLE_STRIKETHROUGH
72        | Options::ENABLE_TASKLISTS
73        | Options::ENABLE_SMART_PUNCTUATION
74}
75
76#[derive(Debug, Clone, Copy)]
77pub enum HeadingOffset {
78    H1 = 0,
79    H2,
80    H3,
81    H4,
82    H5,
83    H6,
84}
85
86/// When `to_string` is called, this struct will emit the HTML corresponding to
87/// the rendered version of the contained markdown string.
88pub struct Markdown<'a> {
89    pub content: &'a str,
90    /// A list of link replacements.
91    pub links: &'a [RenderedLink],
92    /// The current list of used header IDs.
93    pub ids: &'a mut IdMap,
94    /// Whether to allow the use of explicit error codes in doctest lang strings.
95    pub error_codes: ErrorCodes,
96    /// Default edition to use when parsing doctests (to add a `fn main`).
97    pub edition: Edition,
98    pub playground: &'a Option<Playground>,
99    /// Offset at which we render headings.
100    /// E.g. if `heading_offset: HeadingOffset::H2`, then `# something` renders an `<h2>`.
101    pub heading_offset: HeadingOffset,
102}
103/// A struct like `Markdown` that renders the markdown with a table of contents.
104pub(crate) struct MarkdownWithToc<'a> {
105    pub(crate) content: &'a str,
106    pub(crate) links: &'a [RenderedLink],
107    pub(crate) ids: &'a mut IdMap,
108    pub(crate) error_codes: ErrorCodes,
109    pub(crate) edition: Edition,
110    pub(crate) playground: &'a Option<Playground>,
111}
112
113/// A struct like `Markdown` that renders the markdown escaping HTML tags
114/// and includes no paragraph tags.
115pub(crate) struct MarkdownItemInfo<'a> {
116    pub(crate) content: &'a str,
117    pub(crate) links: &'a [RenderedLink],
118    pub(crate) ids: &'a mut IdMap,
119}
120
121/// A tuple struct like `Markdown` that renders only the first paragraph.
122pub(crate) struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [RenderedLink]);
123
124#[derive(Copy, Clone, PartialEq, Debug)]
125pub enum ErrorCodes {
126    Yes,
127    No,
128}
129
130impl ErrorCodes {
131    pub(crate) fn from(b: bool) -> Self {
132        match b {
133            true => ErrorCodes::Yes,
134            false => ErrorCodes::No,
135        }
136    }
137
138    pub(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.
149pub(crate) enum Line<'a> {
150    Hidden(&'a str),
151    Shown(Cow<'a, str>),
152}
153
154impl<'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    pub(crate) 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/// This function is used to handle the "hidden lines" (ie starting with `#`) in
171/// doctests. It also transforms `##` back into `#`.
172// FIXME: There is a minor inconsistency here. For lines that start with ##, we
173// have no easy way of removing a potential single space after the hashes, which
174// is done in the single # case. This inconsistency seems okay, if non-ideal. In
175// order to fix it we'd have to iterate to find the first non-# character, and
176// then reallocate to remove it; which would make us return a String.
177pub(crate) fn map_line(s: &str) -> Line<'_> {
178    let trimmed = s.trim();
179    if trimmed.starts_with("##") {
180        Line::Shown(Cow::Owned(s.replacen("##", "#", 1)))
181    } else if let Some(stripped) = trimmed.strip_prefix("# ") {
182        // # text
183        Line::Hidden(stripped)
184    } else if trimmed == "#" {
185        // We cannot handle '#text' because it could be #[attr].
186        Line::Hidden("")
187    } else {
188        Line::Shown(Cow::Borrowed(s))
189    }
190}
191
192/// Convert chars from a title for an id.
193///
194/// "Hello, world!" -> "hello-world"
195fn slugify(c: char) -> Option<char> {
196    if c.is_alphanumeric() || c == '-' || c == '_' {
197        if c.is_ascii() { Some(c.to_ascii_lowercase()) } else { Some(c) }
198    } else if c.is_whitespace() && c.is_ascii() {
199        Some('-')
200    } else {
201        None
202    }
203}
204
205#[derive(Debug)]
206pub struct Playground {
207    pub crate_name: Option<Symbol>,
208    pub url: String,
209}
210
211/// Adds syntax highlighting and playground Run buttons to Rust code blocks.
212struct CodeBlocks<'p, 'a, I: Iterator<Item = Event<'a>>> {
213    inner: I,
214    check_error_codes: ErrorCodes,
215    edition: Edition,
216    // Information about the playground if a URL has been specified, containing an
217    // optional crate name and the URL.
218    playground: &'p Option<Playground>,
219}
220
221impl<'p, 'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'p, 'a, I> {
222    fn new(
223        iter: I,
224        error_codes: ErrorCodes,
225        edition: Edition,
226        playground: &'p Option<Playground>,
227    ) -> Self {
228        CodeBlocks { inner: iter, check_error_codes: error_codes, edition, playground }
229    }
230}
231
232impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
233    type Item = Event<'a>;
234
235    fn next(&mut self) -> Option<Self::Item> {
236        let event = self.inner.next();
237        let Some(Event::Start(Tag::CodeBlock(kind))) = event else {
238            return event;
239        };
240
241        let mut original_text = String::new();
242        for event in &mut self.inner {
243            match event {
244                Event::End(TagEnd::CodeBlock) => break,
245                Event::Text(ref s) => {
246                    original_text.push_str(s);
247                }
248                _ => {}
249            }
250        }
251
252        let LangString { added_classes, compile_fail, should_panic, ignore, edition, .. } =
253            match kind {
254                CodeBlockKind::Fenced(ref lang) => {
255                    let parse_result =
256                        LangString::parse_without_check(lang, self.check_error_codes);
257                    if !parse_result.rust {
258                        let added_classes = parse_result.added_classes;
259                        let lang_string = if let Some(lang) = parse_result.unknown.first() {
260                            format!("language-{lang}")
261                        } else {
262                            String::new()
263                        };
264                        let whitespace = if added_classes.is_empty() { "" } else { " " };
265                        return Some(Event::Html(
266                            format!(
267                                "<div class=\"example-wrap\">\
268                                 <pre class=\"{lang_string}{whitespace}{added_classes}\">\
269                                     <code>{text}</code>\
270                                 </pre>\
271                             </div>",
272                                added_classes = added_classes.join(" "),
273                                text = Escape(original_text.trim_suffix('\n')),
274                            )
275                            .into(),
276                        ));
277                    }
278                    parse_result
279                }
280                CodeBlockKind::Indented => Default::default(),
281            };
282
283        let lines = original_text.lines().filter_map(|l| map_line(l).for_html());
284        let text = lines.intersperse("\n".into()).collect::<String>();
285
286        let explicit_edition = edition.is_some();
287        let edition = edition.unwrap_or(self.edition);
288
289        let playground_button = self.playground.as_ref().and_then(|playground| {
290            let krate = &playground.crate_name;
291            let url = &playground.url;
292            if url.is_empty() {
293                return None;
294            }
295            let test = original_text
296                .lines()
297                .map(|l| map_line(l).for_code())
298                .intersperse("\n".into())
299                .collect::<String>();
300            let krate = krate.as_ref().map(|s| s.as_str());
301
302            // FIXME: separate out the code to make a code block into runnable code
303            //        from the complicated doctest logic
304            let opts = GlobalTestOptions {
305                crate_name: krate.map(String::from).unwrap_or_default(),
306                no_crate_inject: false,
307                insert_indent_space: true,
308                args_file: PathBuf::new(),
309            };
310            let mut builder = doctest::BuildDocTestBuilder::new(&test).edition(edition);
311            if let Some(krate) = krate {
312                builder = builder.crate_name(krate);
313            }
314            let doctest = builder.build(None);
315            let (wrapped, _) = doctest.generate_unique_doctest(&test, false, &opts, krate);
316            let test = wrapped.to_string();
317            let channel = if test.contains("#![feature(") { "&amp;version=nightly" } else { "" };
318
319            let test_escaped = small_url_encode(test);
320            Some(format!(
321                "<a class=\"test-arrow\" \
322                    target=\"_blank\" \
323                    title=\"Run code\" \
324                    href=\"{url}?code={test_escaped}{channel}&amp;edition={edition}\"></a>",
325            ))
326        });
327
328        let tooltip = {
329            use highlight::Tooltip::*;
330
331            if ignore == Ignore::All {
332                Some(IgnoreAll)
333            } else if let Ignore::Some(platforms) = ignore {
334                Some(IgnoreSome(platforms))
335            } else if compile_fail {
336                Some(CompileFail)
337            } else if should_panic {
338                Some(ShouldPanic)
339            } else if explicit_edition {
340                Some(Edition(edition))
341            } else {
342                None
343            }
344        };
345
346        // insert newline to clearly separate it from the
347        // previous block so we can shorten the html output
348        let s = format!(
349            "\n{}",
350            highlight::render_example_with_highlighting(
351                &text,
352                tooltip.as_ref(),
353                playground_button.as_deref(),
354                &added_classes,
355            )
356        );
357        Some(Event::Html(s.into()))
358    }
359}
360
361/// Make headings links with anchor IDs and build up TOC.
362struct LinkReplacerInner<'a> {
363    links: &'a [RenderedLink],
364    shortcut_link: Option<&'a RenderedLink>,
365}
366
367struct LinkReplacer<'a, I: Iterator<Item = Event<'a>>> {
368    iter: I,
369    inner: LinkReplacerInner<'a>,
370}
371
372impl<'a, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, I> {
373    fn new(iter: I, links: &'a [RenderedLink]) -> Self {
374        LinkReplacer { iter, inner: { LinkReplacerInner { links, shortcut_link: None } } }
375    }
376}
377
378// FIXME: Once we have specialized trait impl (for `Iterator` impl on `LinkReplacer`),
379// we can remove this type and move back `LinkReplacerInner` fields into `LinkReplacer`.
380struct SpannedLinkReplacer<'a, I: Iterator<Item = SpannedEvent<'a>>> {
381    iter: I,
382    inner: LinkReplacerInner<'a>,
383}
384
385impl<'a, I: Iterator<Item = SpannedEvent<'a>>> SpannedLinkReplacer<'a, I> {
386    fn new(iter: I, links: &'a [RenderedLink]) -> Self {
387        SpannedLinkReplacer { iter, inner: { LinkReplacerInner { links, shortcut_link: None } } }
388    }
389}
390
391impl<'a> LinkReplacerInner<'a> {
392    fn handle_event(&mut self, event: &mut Event<'a>) {
393        // Replace intra-doc links and remove disambiguators from shortcut links (`[fn@f]`).
394        match event {
395            // This is a shortcut link that was resolved by the broken_link_callback: `[fn@f]`
396            // Remove any disambiguator.
397            Event::Start(Tag::Link {
398                // [fn@f] or [fn@f][]
399                link_type: LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
400                dest_url,
401                title,
402                ..
403            }) => {
404                debug!("saw start of shortcut link to {dest_url} with title {title}");
405                // If this is a shortcut link, it was resolved by the broken_link_callback.
406                // So the URL will already be updated properly.
407                let link = self.links.iter().find(|&link| *link.href == **dest_url);
408                // Since this is an external iterator, we can't replace the inner text just yet.
409                // Store that we saw a link so we know to replace it later.
410                if let Some(link) = link {
411                    trace!("it matched");
412                    assert!(self.shortcut_link.is_none(), "shortcut links cannot be nested");
413                    self.shortcut_link = Some(link);
414                    if title.is_empty() && !link.tooltip.is_empty() {
415                        *title = CowStr::Borrowed(link.tooltip.as_ref());
416                    }
417                }
418            }
419            // Now that we're done with the shortcut link, don't replace any more text.
420            Event::End(TagEnd::Link) if self.shortcut_link.is_some() => {
421                debug!("saw end of shortcut link");
422                self.shortcut_link = None;
423            }
424            // Handle backticks in inline code blocks, but only if we're in the middle of a shortcut link.
425            // [`fn@f`]
426            Event::Code(text) => {
427                trace!("saw code {text}");
428                if let Some(link) = self.shortcut_link {
429                    // NOTE: this only replaces if the code block is the *entire* text.
430                    // If only part of the link has code highlighting, the disambiguator will not be removed.
431                    // e.g. [fn@`f`]
432                    // This is a limitation from `collect_intra_doc_links`: it passes a full link,
433                    // and does not distinguish at all between code blocks.
434                    // So we could never be sure we weren't replacing too much:
435                    // [fn@my_`f`unc] is treated the same as [my_func()] in that pass.
436                    //
437                    // NOTE: .get(1..len() - 1) is to strip the backticks
438                    if let Some(link) = self.links.iter().find(|l| {
439                        l.href == link.href
440                            && Some(&**text) == l.original_text.get(1..l.original_text.len() - 1)
441                    }) {
442                        debug!("replacing {text} with {new_text}", new_text = link.new_text);
443                        *text = CowStr::Borrowed(&link.new_text);
444                    }
445                }
446            }
447            // Replace plain text in links, but only in the middle of a shortcut link.
448            // [fn@f]
449            Event::Text(text) => {
450                trace!("saw text {text}");
451                if let Some(link) = self.shortcut_link {
452                    // NOTE: same limitations as `Event::Code`
453                    if let Some(link) = self
454                        .links
455                        .iter()
456                        .find(|l| l.href == link.href && **text == *l.original_text)
457                    {
458                        debug!("replacing {text} with {new_text}", new_text = link.new_text);
459                        *text = CowStr::Borrowed(&link.new_text);
460                    }
461                }
462            }
463            // If this is a link, but not a shortcut link,
464            // replace the URL, since the broken_link_callback was not called.
465            Event::Start(Tag::Link { dest_url, title, .. }) => {
466                if let Some(link) =
467                    self.links.iter().find(|&link| *link.original_text == **dest_url)
468                {
469                    *dest_url = CowStr::Borrowed(link.href.as_ref());
470                    if title.is_empty() && !link.tooltip.is_empty() {
471                        *title = CowStr::Borrowed(link.tooltip.as_ref());
472                    }
473                }
474            }
475            // Anything else couldn't have been a valid Rust path, so no need to replace the text.
476            _ => {}
477        }
478    }
479}
480
481impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
482    type Item = Event<'a>;
483
484    fn next(&mut self) -> Option<Self::Item> {
485        let mut event = self.iter.next();
486        if let Some(ref mut event) = event {
487            self.inner.handle_event(event);
488        }
489        // Yield the modified event
490        event
491    }
492}
493
494impl<'a, I: Iterator<Item = SpannedEvent<'a>>> Iterator for SpannedLinkReplacer<'a, I> {
495    type Item = SpannedEvent<'a>;
496
497    fn next(&mut self) -> Option<Self::Item> {
498        let (mut event, range) = self.iter.next()?;
499        self.inner.handle_event(&mut event);
500        // Yield the modified event
501        Some((event, range))
502    }
503}
504
505/// Wrap HTML tables into `<div>` to prevent having the doc blocks width being too big.
506struct TableWrapper<'a, I: Iterator<Item = Event<'a>>> {
507    inner: I,
508    stored_events: VecDeque<Event<'a>>,
509}
510
511impl<'a, I: Iterator<Item = Event<'a>>> TableWrapper<'a, I> {
512    fn new(iter: I) -> Self {
513        Self { inner: iter, stored_events: VecDeque::new() }
514    }
515}
516
517impl<'a, I: Iterator<Item = Event<'a>>> Iterator for TableWrapper<'a, I> {
518    type Item = Event<'a>;
519
520    fn next(&mut self) -> Option<Self::Item> {
521        if let Some(first) = self.stored_events.pop_front() {
522            return Some(first);
523        }
524
525        let event = self.inner.next()?;
526
527        Some(match event {
528            Event::Start(Tag::Table(t)) => {
529                self.stored_events.push_back(Event::Start(Tag::Table(t)));
530                Event::Html(CowStr::Borrowed("<div>"))
531            }
532            Event::End(TagEnd::Table) => {
533                self.stored_events.push_back(Event::Html(CowStr::Borrowed("</div>")));
534                Event::End(TagEnd::Table)
535            }
536            e => e,
537        })
538    }
539}
540
541type SpannedEvent<'a> = (Event<'a>, Range<usize>);
542
543/// Make headings links with anchor IDs and build up TOC.
544struct HeadingLinks<'a, 'b, 'ids, I> {
545    inner: I,
546    toc: Option<&'b mut TocBuilder>,
547    buf: VecDeque<SpannedEvent<'a>>,
548    id_map: &'ids mut IdMap,
549    heading_offset: HeadingOffset,
550}
551
552impl<'b, 'ids, I> HeadingLinks<'_, 'b, 'ids, I> {
553    fn new(
554        iter: I,
555        toc: Option<&'b mut TocBuilder>,
556        ids: &'ids mut IdMap,
557        heading_offset: HeadingOffset,
558    ) -> Self {
559        HeadingLinks { inner: iter, toc, buf: VecDeque::new(), id_map: ids, heading_offset }
560    }
561}
562
563impl<'a, I: Iterator<Item = SpannedEvent<'a>>> Iterator for HeadingLinks<'a, '_, '_, I> {
564    type Item = SpannedEvent<'a>;
565
566    fn next(&mut self) -> Option<Self::Item> {
567        if let Some(e) = self.buf.pop_front() {
568            return Some(e);
569        }
570
571        let event = self.inner.next();
572        if let Some((Event::Start(Tag::Heading { level, .. }), _)) = event {
573            let mut id = String::new();
574            for event in &mut self.inner {
575                match &event.0 {
576                    Event::End(TagEnd::Heading(_)) => break,
577                    Event::Text(text) | Event::Code(text) => {
578                        id.extend(text.chars().filter_map(slugify));
579                        self.buf.push_back(event);
580                    }
581                    _ => self.buf.push_back(event),
582                }
583            }
584            let id = self.id_map.derive(id);
585            let percent_encoded_id = small_url_encode(id.clone());
586
587            if let Some(ref mut builder) = self.toc {
588                let mut text_header = String::new();
589                plain_text_from_events(self.buf.iter().map(|(ev, _)| ev.clone()), &mut text_header);
590                let mut html_header = String::new();
591                html_text_from_events(self.buf.iter().map(|(ev, _)| ev.clone()), &mut html_header);
592                let sec = builder.push(level as u32, text_header, html_header, id.clone());
593                self.buf.push_front((Event::Html(format!("{sec} ").into()), 0..0));
594            }
595
596            let level =
597                std::cmp::min(level as u32 + (self.heading_offset as u32), MAX_HEADER_LEVEL);
598            self.buf.push_back((Event::Html(format!("</h{level}>").into()), 0..0));
599
600            let start_tags = format!(
601                "<h{level} id=\"{id}\"><a class=\"doc-anchor\" href=\"#{percent_encoded_id}\">§</a>"
602            );
603            return Some((Event::Html(start_tags.into()), 0..0));
604        }
605        event
606    }
607}
608
609/// Extracts just the first paragraph.
610struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
611    inner: I,
612    started: bool,
613    depth: u32,
614    skipped_tags: u32,
615}
616
617impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
618    fn new(iter: I) -> Self {
619        SummaryLine { inner: iter, started: false, depth: 0, skipped_tags: 0 }
620    }
621}
622
623fn check_if_allowed_tag(t: &TagEnd) -> bool {
624    matches!(
625        t,
626        TagEnd::Paragraph
627            | TagEnd::Emphasis
628            | TagEnd::Strong
629            | TagEnd::Strikethrough
630            | TagEnd::Link
631            | TagEnd::BlockQuote
632    )
633}
634
635fn is_forbidden_tag(t: &TagEnd) -> bool {
636    matches!(
637        t,
638        TagEnd::CodeBlock
639            | TagEnd::Table
640            | TagEnd::TableHead
641            | TagEnd::TableRow
642            | TagEnd::TableCell
643            | TagEnd::FootnoteDefinition
644    )
645}
646
647impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
648    type Item = Event<'a>;
649
650    fn next(&mut self) -> Option<Self::Item> {
651        if self.started && self.depth == 0 {
652            return None;
653        }
654        if !self.started {
655            self.started = true;
656        }
657        if let Some(event) = self.inner.next() {
658            let mut is_start = true;
659            let is_allowed_tag = match event {
660                Event::Start(ref c) => {
661                    if is_forbidden_tag(&c.to_end()) {
662                        self.skipped_tags += 1;
663                        return None;
664                    }
665                    self.depth += 1;
666                    check_if_allowed_tag(&c.to_end())
667                }
668                Event::End(ref c) => {
669                    if is_forbidden_tag(c) {
670                        self.skipped_tags += 1;
671                        return None;
672                    }
673                    self.depth -= 1;
674                    is_start = false;
675                    check_if_allowed_tag(c)
676                }
677                Event::FootnoteReference(_) => {
678                    self.skipped_tags += 1;
679                    false
680                }
681                _ => true,
682            };
683            if !is_allowed_tag {
684                self.skipped_tags += 1;
685            }
686            return if !is_allowed_tag {
687                if is_start {
688                    Some(Event::Start(Tag::Paragraph))
689                } else {
690                    Some(Event::End(TagEnd::Paragraph))
691                }
692            } else {
693                Some(event)
694            };
695        }
696        None
697    }
698}
699
700/// A newtype that represents a relative line number in Markdown.
701///
702/// In other words, this represents an offset from the first line of Markdown
703/// in a doc comment or other source. If the first Markdown line appears on line 32,
704/// and the `MdRelLine` is 3, then the absolute line for this one is 35. I.e., it's
705/// a zero-based offset.
706pub(crate) struct MdRelLine {
707    offset: usize,
708}
709
710impl MdRelLine {
711    /// See struct docs.
712    pub(crate) const fn new(offset: usize) -> Self {
713        Self { offset }
714    }
715
716    /// See struct docs.
717    pub(crate) const fn offset(self) -> usize {
718        self.offset
719    }
720}
721
722pub(crate) fn find_testable_code<T: doctest::DocTestVisitor>(
723    doc: &str,
724    tests: &mut T,
725    error_codes: ErrorCodes,
726    extra_info: Option<&ExtraInfo<'_>>,
727) {
728    find_codes(doc, tests, error_codes, extra_info, false)
729}
730
731pub(crate) fn find_codes<T: doctest::DocTestVisitor>(
732    doc: &str,
733    tests: &mut T,
734    error_codes: ErrorCodes,
735    extra_info: Option<&ExtraInfo<'_>>,
736    include_non_rust: bool,
737) {
738    let mut parser = Parser::new_ext(doc, main_body_opts()).into_offset_iter();
739    let mut prev_offset = 0;
740    let mut nb_lines = 0;
741    let mut register_header = None;
742    while let Some((event, offset)) = parser.next() {
743        match event {
744            Event::Start(Tag::CodeBlock(kind)) => {
745                let block_info = match kind {
746                    CodeBlockKind::Fenced(ref lang) => {
747                        if lang.is_empty() {
748                            Default::default()
749                        } else {
750                            LangString::parse(lang, error_codes, extra_info)
751                        }
752                    }
753                    CodeBlockKind::Indented => Default::default(),
754                };
755                if !include_non_rust && !block_info.rust {
756                    continue;
757                }
758
759                let mut test_s = String::new();
760
761                while let Some((Event::Text(s), _)) = parser.next() {
762                    test_s.push_str(&s);
763                }
764                let text = test_s
765                    .lines()
766                    .map(|l| map_line(l).for_code())
767                    .collect::<Vec<Cow<'_, str>>>()
768                    .join("\n");
769
770                nb_lines += doc[prev_offset..offset.start].lines().count();
771                // If there are characters between the preceding line ending and
772                // this code block, `str::lines` will return an additional line,
773                // which we subtract here.
774                if nb_lines != 0 && !&doc[prev_offset..offset.start].ends_with('\n') {
775                    nb_lines -= 1;
776                }
777                let line = MdRelLine::new(nb_lines);
778                tests.visit_test(text, block_info, line);
779                prev_offset = offset.start;
780            }
781            Event::Start(Tag::Heading { level, .. }) => {
782                register_header = Some(level as u32);
783            }
784            Event::Text(ref s) if register_header.is_some() => {
785                let level = register_header.unwrap();
786                tests.visit_header(s, level);
787                register_header = None;
788            }
789            _ => {}
790        }
791    }
792}
793
794pub(crate) struct ExtraInfo<'tcx> {
795    def_id: LocalDefId,
796    sp: Span,
797    tcx: TyCtxt<'tcx>,
798}
799
800impl<'tcx> ExtraInfo<'tcx> {
801    pub(crate) fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId, sp: Span) -> ExtraInfo<'tcx> {
802        ExtraInfo { def_id, sp, tcx }
803    }
804
805    fn error_invalid_codeblock_attr(&self, msg: impl Into<DiagMessage>) {
806        self.error_invalid_codeblock_attr_with_help(msg, |_| {});
807    }
808
809    fn error_invalid_codeblock_attr_with_help(
810        &self,
811        msg: impl Into<DiagMessage>,
812        f: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
813    ) {
814        self.tcx.emit_node_span_lint(
815            crate::lint::INVALID_CODEBLOCK_ATTRIBUTES,
816            self.tcx.local_def_id_to_hir_id(self.def_id),
817            self.sp,
818            rustc_errors::DiagDecorator(|lint| {
819                lint.primary_message(msg);
820                f(lint);
821            }),
822        );
823    }
824}
825
826#[derive(Eq, PartialEq, Clone, Debug)]
827pub(crate) struct LangString {
828    pub(crate) original: String,
829    pub(crate) should_panic: bool,
830    pub(crate) no_run: bool,
831    pub(crate) ignore: Ignore,
832    pub(crate) rust: bool,
833    pub(crate) test_harness: bool,
834    pub(crate) compile_fail: bool,
835    pub(crate) standalone_crate: bool,
836    pub(crate) error_codes: Vec<String>,
837    pub(crate) edition: Option<Edition>,
838    pub(crate) added_classes: Vec<String>,
839    pub(crate) unknown: Vec<String>,
840}
841
842#[derive(Eq, PartialEq, Clone, Debug)]
843pub(crate) enum Ignore {
844    All,
845    None,
846    Some(Vec<String>),
847}
848
849/// This is the parser for fenced codeblocks attributes.
850///
851/// It implements the following grammar as expressed in ABNF:
852///
853/// ```ABNF
854/// lang-string = *(token-list / delimited-attribute-list / comment)
855/// bareword = LEADINGCHAR *(CHAR)
856/// bareword-without-leading-char = CHAR *(CHAR)
857/// quoted-string = QUOTE *(NONQUOTE) QUOTE
858/// token = bareword / quoted-string
859/// token-without-leading-char = bareword-without-leading-char / quoted-string
860/// sep = COMMA/WS *(COMMA/WS)
861/// attribute = (DOT token)/(token EQUAL token-without-leading-char)
862/// attribute-list = [sep] attribute *(sep attribute) [sep]
863/// delimited-attribute-list = OPEN-CURLY-BRACKET attribute-list CLOSE-CURLY-BRACKET
864/// token-list = [sep] token *(sep token) [sep]
865/// comment = OPEN_PAREN *<all characters except closing parentheses> CLOSE_PAREN
866///
867/// OPEN_PAREN = "("
868/// CLOSE_PARENT = ")"
869/// OPEN-CURLY-BRACKET = "{"
870/// CLOSE-CURLY-BRACKET = "}"
871/// LEADINGCHAR = ALPHA | DIGIT | "_" | "-" | ":"
872/// ; All ASCII punctuation except comma, quote, equals, backslash, grave (backquote) and braces.
873/// ; Comma is used to separate language tokens, so it can't be used in one.
874/// ; Quote is used to allow otherwise-disallowed characters in language tokens.
875/// ; Equals is used to make key=value pairs in attribute blocks.
876/// ; Backslash and grave are special Markdown characters.
877/// ; Braces are used to start an attribute block.
878/// CHAR = ALPHA | DIGIT | "_" | "-" | ":" | "." | "!" | "#" | "$" | "%" | "&" | "*" | "+" | "/" |
879///        ";" | "<" | ">" | "?" | "@" | "^" | "|" | "~"
880/// NONQUOTE = %x09 / %x20 / %x21 / %x23-7E ; TAB / SPACE / all printable characters except `"`
881/// COMMA = ","
882/// DOT = "."
883/// EQUAL = "="
884///
885/// ALPHA = %x41-5A / %x61-7A ; A-Z / a-z
886/// DIGIT = %x30-39
887/// WS = %x09 / " "
888/// ```
889pub(crate) struct TagIterator<'a, 'tcx> {
890    inner: Peekable<CharIndices<'a>>,
891    data: &'a str,
892    is_in_attribute_block: bool,
893    extra: Option<&'a ExtraInfo<'tcx>>,
894    is_error: bool,
895}
896
897#[derive(Clone, Debug, Eq, PartialEq)]
898pub(crate) enum LangStringToken<'a> {
899    LangToken(&'a str),
900    ClassAttribute(&'a str),
901    KeyValueAttribute(&'a str, &'a str),
902}
903
904fn is_leading_char(c: char) -> bool {
905    c == '_' || c == '-' || c == ':' || c.is_ascii_alphabetic() || c.is_ascii_digit()
906}
907fn is_bareword_char(c: char) -> bool {
908    is_leading_char(c) || ".!#$%&*+/;<>?@^|~".contains(c)
909}
910fn is_separator(c: char) -> bool {
911    c == ' ' || c == ',' || c == '\t'
912}
913
914struct Indices {
915    start: usize,
916    end: usize,
917}
918
919impl<'a, 'tcx> TagIterator<'a, 'tcx> {
920    pub(crate) fn new(data: &'a str, extra: Option<&'a ExtraInfo<'tcx>>) -> Self {
921        Self {
922            inner: data.char_indices().peekable(),
923            data,
924            is_in_attribute_block: false,
925            extra,
926            is_error: false,
927        }
928    }
929
930    fn emit_error(&mut self, err: impl Into<DiagMessage>) {
931        if let Some(extra) = self.extra {
932            extra.error_invalid_codeblock_attr(err);
933        }
934        self.is_error = true;
935    }
936
937    fn skip_separators(&mut self) -> Option<usize> {
938        while let Some((pos, c)) = self.inner.peek() {
939            if !is_separator(*c) {
940                return Some(*pos);
941            }
942            self.inner.next();
943        }
944        None
945    }
946
947    fn parse_string(&mut self, start: usize) -> Option<Indices> {
948        for (pos, c) in self.inner.by_ref() {
949            if c == '"' {
950                return Some(Indices { start: start + 1, end: pos });
951            }
952        }
953        self.emit_error("unclosed quote string `\"`");
954        None
955    }
956
957    fn parse_class(&mut self, start: usize) -> Option<LangStringToken<'a>> {
958        while let Some((pos, c)) = self.inner.peek().copied() {
959            if is_bareword_char(c) {
960                self.inner.next();
961            } else {
962                let class = &self.data[start + 1..pos];
963                if class.is_empty() {
964                    self.emit_error(format!("unexpected `{c}` character after `.`"));
965                    return None;
966                } else if self.check_after_token() {
967                    return Some(LangStringToken::ClassAttribute(class));
968                } else {
969                    return None;
970                }
971            }
972        }
973        let class = &self.data[start + 1..];
974        if class.is_empty() {
975            self.emit_error("missing character after `.`");
976            None
977        } else if self.check_after_token() {
978            Some(LangStringToken::ClassAttribute(class))
979        } else {
980            None
981        }
982    }
983
984    fn parse_token(&mut self, start: usize) -> Option<Indices> {
985        while let Some((pos, c)) = self.inner.peek() {
986            if !is_bareword_char(*c) {
987                return Some(Indices { start, end: *pos });
988            }
989            self.inner.next();
990        }
991        self.emit_error("unexpected end");
992        None
993    }
994
995    fn parse_key_value(&mut self, c: char, start: usize) -> Option<LangStringToken<'a>> {
996        let key_indices =
997            if c == '"' { self.parse_string(start)? } else { self.parse_token(start)? };
998        if key_indices.start == key_indices.end {
999            self.emit_error("unexpected empty string as key");
1000            return None;
1001        }
1002
1003        if let Some((_, c)) = self.inner.next() {
1004            if c != '=' {
1005                self.emit_error(format!("expected `=`, found `{c}`"));
1006                return None;
1007            }
1008        } else {
1009            self.emit_error("unexpected end");
1010            return None;
1011        }
1012        let value_indices = match self.inner.next() {
1013            Some((pos, '"')) => self.parse_string(pos)?,
1014            Some((pos, c)) if is_bareword_char(c) => self.parse_token(pos)?,
1015            Some((_, c)) => {
1016                self.emit_error(format!("unexpected `{c}` character after `=`"));
1017                return None;
1018            }
1019            None => {
1020                self.emit_error("expected value after `=`");
1021                return None;
1022            }
1023        };
1024        if value_indices.start == value_indices.end {
1025            self.emit_error("unexpected empty string as value");
1026            None
1027        } else if self.check_after_token() {
1028            Some(LangStringToken::KeyValueAttribute(
1029                &self.data[key_indices.start..key_indices.end],
1030                &self.data[value_indices.start..value_indices.end],
1031            ))
1032        } else {
1033            None
1034        }
1035    }
1036
1037    /// Returns `false` if an error was emitted.
1038    fn check_after_token(&mut self) -> bool {
1039        if let Some((_, c)) = self.inner.peek().copied() {
1040            if c == '}' || is_separator(c) || c == '(' {
1041                true
1042            } else {
1043                self.emit_error(format!("unexpected `{c}` character"));
1044                false
1045            }
1046        } else {
1047            // The error will be caught on the next iteration.
1048            true
1049        }
1050    }
1051
1052    fn parse_in_attribute_block(&mut self) -> Option<LangStringToken<'a>> {
1053        if let Some((pos, c)) = self.inner.next() {
1054            if c == '}' {
1055                self.is_in_attribute_block = false;
1056                return self.next();
1057            } else if c == '.' {
1058                return self.parse_class(pos);
1059            } else if c == '"' || is_leading_char(c) {
1060                return self.parse_key_value(c, pos);
1061            } else {
1062                self.emit_error(format!("unexpected character `{c}`"));
1063                return None;
1064            }
1065        }
1066        self.emit_error("unclosed attribute block (`{}`): missing `}` at the end");
1067        None
1068    }
1069
1070    /// Returns `false` if an error was emitted.
1071    fn skip_paren_block(&mut self) -> bool {
1072        for (_, c) in self.inner.by_ref() {
1073            if c == ')' {
1074                return true;
1075            }
1076        }
1077        self.emit_error("unclosed comment: missing `)` at the end");
1078        false
1079    }
1080
1081    fn parse_outside_attribute_block(&mut self, start: usize) -> Option<LangStringToken<'a>> {
1082        while let Some((pos, c)) = self.inner.next() {
1083            if c == '"' {
1084                if pos != start {
1085                    self.emit_error("expected ` `, `{` or `,` found `\"`");
1086                    return None;
1087                }
1088                let indices = self.parse_string(pos)?;
1089                if let Some((_, c)) = self.inner.peek().copied()
1090                    && c != '{'
1091                    && !is_separator(c)
1092                    && c != '('
1093                {
1094                    self.emit_error(format!("expected ` `, `{{` or `,` after `\"`, found `{c}`"));
1095                    return None;
1096                }
1097                return Some(LangStringToken::LangToken(&self.data[indices.start..indices.end]));
1098            } else if c == '{' {
1099                self.is_in_attribute_block = true;
1100                return self.next();
1101            } else if is_separator(c) {
1102                if pos != start {
1103                    return Some(LangStringToken::LangToken(&self.data[start..pos]));
1104                }
1105                return self.next();
1106            } else if c == '(' {
1107                if !self.skip_paren_block() {
1108                    return None;
1109                }
1110                if pos != start {
1111                    return Some(LangStringToken::LangToken(&self.data[start..pos]));
1112                }
1113                return self.next();
1114            } else if (pos == start && is_leading_char(c)) || (pos != start && is_bareword_char(c))
1115            {
1116                continue;
1117            } else {
1118                self.emit_error(format!("unexpected character `{c}`"));
1119                return None;
1120            }
1121        }
1122        let token = &self.data[start..];
1123        if token.is_empty() { None } else { Some(LangStringToken::LangToken(&self.data[start..])) }
1124    }
1125}
1126
1127impl<'a> Iterator for TagIterator<'a, '_> {
1128    type Item = LangStringToken<'a>;
1129
1130    fn next(&mut self) -> Option<Self::Item> {
1131        if self.is_error {
1132            return None;
1133        }
1134        let Some(start) = self.skip_separators() else {
1135            if self.is_in_attribute_block {
1136                self.emit_error("unclosed attribute block (`{}`): missing `}` at the end");
1137            }
1138            return None;
1139        };
1140        if self.is_in_attribute_block {
1141            self.parse_in_attribute_block()
1142        } else {
1143            self.parse_outside_attribute_block(start)
1144        }
1145    }
1146}
1147
1148impl Default for LangString {
1149    fn default() -> Self {
1150        Self {
1151            original: String::new(),
1152            should_panic: false,
1153            no_run: false,
1154            ignore: Ignore::None,
1155            rust: true,
1156            test_harness: false,
1157            compile_fail: false,
1158            standalone_crate: false,
1159            error_codes: Vec::new(),
1160            edition: None,
1161            added_classes: Vec::new(),
1162            unknown: Vec::new(),
1163        }
1164    }
1165}
1166
1167impl LangString {
1168    fn parse_without_check(string: &str, allow_error_code_check: ErrorCodes) -> Self {
1169        Self::parse(string, allow_error_code_check, None)
1170    }
1171
1172    fn parse(
1173        string: &str,
1174        allow_error_code_check: ErrorCodes,
1175        extra: Option<&ExtraInfo<'_>>,
1176    ) -> Self {
1177        let allow_error_code_check = allow_error_code_check.as_bool();
1178        let mut seen_rust_tags = false;
1179        let mut seen_other_tags = false;
1180        let mut seen_custom_tag = false;
1181        let mut data = LangString::default();
1182        let mut ignores = vec![];
1183
1184        data.original = string.to_owned();
1185
1186        let mut call = |tokens: &mut dyn Iterator<Item = LangStringToken<'_>>| {
1187            for token in tokens {
1188                match token {
1189                    LangStringToken::LangToken("should_panic") => {
1190                        data.should_panic = true;
1191                        seen_rust_tags = !seen_other_tags;
1192                    }
1193                    LangStringToken::LangToken("no_run") => {
1194                        data.no_run = true;
1195                        seen_rust_tags = !seen_other_tags;
1196                    }
1197                    LangStringToken::LangToken("ignore") => {
1198                        data.ignore = Ignore::All;
1199                        seen_rust_tags = !seen_other_tags;
1200                    }
1201                    LangStringToken::LangToken(x)
1202                        if let Some(ignore) = x.strip_prefix("ignore-") =>
1203                    {
1204                        ignores.push(ignore.to_owned());
1205                        seen_rust_tags = !seen_other_tags;
1206                    }
1207                    LangStringToken::LangToken("rust") => {
1208                        data.rust = true;
1209                        seen_rust_tags = true;
1210                    }
1211                    LangStringToken::LangToken("custom") => {
1212                        seen_custom_tag = true;
1213                    }
1214                    LangStringToken::LangToken("test_harness") => {
1215                        data.test_harness = true;
1216                        seen_rust_tags = !seen_other_tags || seen_rust_tags;
1217                    }
1218                    LangStringToken::LangToken("compile_fail") => {
1219                        data.compile_fail = true;
1220                        seen_rust_tags = !seen_other_tags || seen_rust_tags;
1221                        data.no_run = true;
1222                    }
1223                    LangStringToken::LangToken("standalone_crate") => {
1224                        data.standalone_crate = true;
1225                        seen_rust_tags = !seen_other_tags || seen_rust_tags;
1226                    }
1227                    LangStringToken::LangToken(x)
1228                        if let Some(edition) = x.strip_prefix("edition") =>
1229                    {
1230                        data.edition = edition.parse::<Edition>().ok();
1231                    }
1232                    LangStringToken::LangToken(x)
1233                        if let Some(edition) = x.strip_prefix("rust")
1234                            && edition.parse::<Edition>().is_ok()
1235                            && let Some(extra) = extra =>
1236                    {
1237                        extra.error_invalid_codeblock_attr_with_help(
1238                            format!("unknown attribute `{x}`"),
1239                            |lint| {
1240                                lint.help(format!(
1241                                    "there is an attribute with a similar name: `edition{edition}`"
1242                                ));
1243                            },
1244                        );
1245                    }
1246                    LangStringToken::LangToken(x)
1247                        if allow_error_code_check
1248                            && let Some(error_code) = x.strip_prefix('E')
1249                            && error_code.len() == 4 =>
1250                    {
1251                        if error_code.parse::<u32>().is_ok() {
1252                            data.error_codes.push(x.to_owned());
1253                            seen_rust_tags = !seen_other_tags || seen_rust_tags;
1254                        } else {
1255                            seen_other_tags = true;
1256                        }
1257                    }
1258                    LangStringToken::LangToken(x) if let Some(extra) = extra => {
1259                        if let Some(help) = match x.to_lowercase().as_str() {
1260                            "compile-fail" | "compile_fail" | "compilefail" => Some(
1261                                "use `compile_fail` to invert the results of this test, so that it \
1262                                passes if it cannot be compiled and fails if it can",
1263                            ),
1264                            "should-panic" | "should_panic" | "shouldpanic" => Some(
1265                                "use `should_panic` to invert the results of this test, so that if \
1266                                passes if it panics and fails if it does not",
1267                            ),
1268                            "no-run" | "no_run" | "norun" => Some(
1269                                "use `no_run` to compile, but not run, the code sample during \
1270                                testing",
1271                            ),
1272                            "test-harness" | "test_harness" | "testharness" => Some(
1273                                "use `test_harness` to run functions marked `#[test]` instead of a \
1274                                potentially-implicit `main` function",
1275                            ),
1276                            "standalone" | "standalone_crate" | "standalone-crate"
1277                                if extra.sp.at_least_rust_2024() =>
1278                            {
1279                                Some(
1280                                    "use `standalone_crate` to compile this code block \
1281                                        separately",
1282                                )
1283                            }
1284                            _ => None,
1285                        } {
1286                            extra.error_invalid_codeblock_attr_with_help(
1287                                format!("unknown attribute `{x}`"),
1288                                |lint| {
1289                                    lint.help(help).help(
1290                                        "this code block may be skipped during testing, \
1291                                            because unknown attributes are treated as markers for \
1292                                            code samples written in other programming languages, \
1293                                            unless it is also explicitly marked as `rust`",
1294                                    );
1295                                },
1296                            );
1297                        }
1298                        seen_other_tags = true;
1299                        data.unknown.push(x.to_owned());
1300                    }
1301                    LangStringToken::LangToken(x) => {
1302                        seen_other_tags = true;
1303                        data.unknown.push(x.to_owned());
1304                    }
1305                    LangStringToken::KeyValueAttribute("class", value) => {
1306                        data.added_classes.push(value.to_owned());
1307                    }
1308                    LangStringToken::KeyValueAttribute(key, ..) if let Some(extra) = extra => {
1309                        extra
1310                            .error_invalid_codeblock_attr(format!("unsupported attribute `{key}`"));
1311                    }
1312                    LangStringToken::ClassAttribute(class) => {
1313                        data.added_classes.push(class.to_owned());
1314                    }
1315                    _ => {}
1316                }
1317            }
1318        };
1319
1320        let mut tag_iter = TagIterator::new(string, extra);
1321        call(&mut tag_iter);
1322
1323        // ignore-foo overrides ignore
1324        if !ignores.is_empty() {
1325            data.ignore = Ignore::Some(ignores);
1326        }
1327
1328        data.rust &= !seen_custom_tag && (!seen_other_tags || seen_rust_tags) && !tag_iter.is_error;
1329
1330        data
1331    }
1332}
1333
1334impl<'a> Markdown<'a> {
1335    pub fn write_into(self, f: impl fmt::Write) -> fmt::Result {
1336        // This is actually common enough to special-case
1337        if self.content.is_empty() {
1338            return Ok(());
1339        }
1340
1341        html::write_html_fmt(f, self.into_iter())
1342    }
1343
1344    fn into_iter(self) -> CodeBlocks<'a, 'a, impl Iterator<Item = Event<'a>>> {
1345        let Markdown {
1346            content: md,
1347            links,
1348            ids,
1349            error_codes: codes,
1350            edition,
1351            playground,
1352            heading_offset,
1353        } = self;
1354
1355        let replacer = move |broken_link: BrokenLink<'_>| {
1356            links
1357                .iter()
1358                .find(|link| *link.original_text == *broken_link.reference)
1359                .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1360        };
1361
1362        let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(replacer));
1363        let p = p.into_offset_iter();
1364
1365        ids.handle_footnotes(|ids, existing_footnotes| {
1366            let p = HeadingLinks::new(p, None, ids, heading_offset);
1367            let p = SpannedLinkReplacer::new(p, links);
1368            let p = footnotes::Footnotes::new(p, existing_footnotes);
1369            let p = TableWrapper::new(p.map(|(ev, _)| ev));
1370            CodeBlocks::new(p, codes, edition, playground)
1371        })
1372    }
1373
1374    /// Convert markdown to (summary, remaining) HTML.
1375    ///
1376    /// - The summary is the first top-level Markdown element (usually a paragraph, but potentially
1377    ///   any block).
1378    /// - The remaining docs contain everything after the summary.
1379    pub(crate) fn split_summary_and_content(self) -> (Option<String>, Option<String>) {
1380        if self.content.is_empty() {
1381            return (None, None);
1382        }
1383        let mut p = self.into_iter();
1384
1385        let mut event_level = 0;
1386        let mut summary_events = Vec::new();
1387        let mut get_next_tag = false;
1388
1389        let mut end_of_summary = false;
1390        while let Some(event) = p.next() {
1391            match event {
1392                Event::Start(_) => event_level += 1,
1393                Event::End(kind) => {
1394                    event_level -= 1;
1395                    if event_level == 0 {
1396                        // We're back at the "top" so it means we're done with the summary.
1397                        end_of_summary = true;
1398                        // We surround tables with `<div>` HTML tags so this is a special case.
1399                        get_next_tag = kind == TagEnd::Table;
1400                    }
1401                }
1402                _ => {}
1403            }
1404            summary_events.push(event);
1405            if end_of_summary {
1406                if get_next_tag && let Some(event) = p.next() {
1407                    summary_events.push(event);
1408                }
1409                break;
1410            }
1411        }
1412        let mut summary = String::new();
1413        html::push_html(&mut summary, summary_events.into_iter());
1414        if summary.is_empty() {
1415            return (None, None);
1416        }
1417        let mut content = String::new();
1418        html::push_html(&mut content, p);
1419
1420        if content.is_empty() { (Some(summary), None) } else { (Some(summary), Some(content)) }
1421    }
1422}
1423
1424impl MarkdownWithToc<'_> {
1425    pub(crate) fn into_parts(self) -> (Toc, String) {
1426        let MarkdownWithToc { content: md, links, ids, error_codes: codes, edition, playground } =
1427            self;
1428
1429        // This is actually common enough to special-case
1430        if md.is_empty() {
1431            return (Toc { entries: Vec::new() }, String::new());
1432        }
1433        let mut replacer = |broken_link: BrokenLink<'_>| {
1434            links
1435                .iter()
1436                .find(|link| *link.original_text == *broken_link.reference)
1437                .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1438        };
1439
1440        let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(&mut replacer));
1441        let p = p.into_offset_iter();
1442
1443        let mut s = String::with_capacity(md.len() * 3 / 2);
1444
1445        let mut toc = TocBuilder::new();
1446
1447        ids.handle_footnotes(|ids, existing_footnotes| {
1448            let p = HeadingLinks::new(p, Some(&mut toc), ids, HeadingOffset::H1);
1449            let p = footnotes::Footnotes::new(p, existing_footnotes);
1450            let p = TableWrapper::new(p.map(|(ev, _)| ev));
1451            let p = CodeBlocks::new(p, codes, edition, playground);
1452            html::push_html(&mut s, p);
1453        });
1454
1455        (toc.into_toc(), s)
1456    }
1457
1458    pub(crate) fn write_into(self, mut f: impl fmt::Write) -> fmt::Result {
1459        let (toc, s) = self.into_parts();
1460        write!(f, "<nav id=\"rustdoc\">{toc}</nav>{s}", toc = toc.print())
1461    }
1462}
1463
1464impl<'a> MarkdownItemInfo<'a> {
1465    pub(crate) fn new(content: &'a str, links: &'a [RenderedLink], ids: &'a mut IdMap) -> Self {
1466        Self { content, links, ids }
1467    }
1468
1469    pub(crate) fn write_into(self, mut f: impl fmt::Write) -> fmt::Result {
1470        let MarkdownItemInfo { content: md, links, ids } = self;
1471
1472        // This is actually common enough to special-case
1473        if md.is_empty() {
1474            return Ok(());
1475        }
1476
1477        let replacer = move |broken_link: BrokenLink<'_>| {
1478            links
1479                .iter()
1480                .find(|link| *link.original_text == *broken_link.reference)
1481                .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1482        };
1483
1484        let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(replacer));
1485        let p = p.into_offset_iter();
1486
1487        // Treat inline HTML as plain text.
1488        let p = p.map(|event| match event.0 {
1489            Event::Html(text) | Event::InlineHtml(text) => (Event::Text(text), event.1),
1490            _ => event,
1491        });
1492
1493        ids.handle_footnotes(|ids, existing_footnotes| {
1494            let p = HeadingLinks::new(p, None, ids, HeadingOffset::H1);
1495            let p = SpannedLinkReplacer::new(p, links);
1496            let p = footnotes::Footnotes::new(p, existing_footnotes);
1497            let p = TableWrapper::new(p.map(|(ev, _)| ev));
1498            // in legacy wrap mode, strip <p> elements to avoid them inserting newlines
1499            html::write_html_fmt(&mut f, p)?;
1500
1501            Ok(())
1502        })
1503    }
1504}
1505
1506impl MarkdownSummaryLine<'_> {
1507    pub(crate) fn into_string_with_has_more_content(self) -> (String, bool) {
1508        let MarkdownSummaryLine(md, links) = self;
1509        // This is actually common enough to special-case
1510        if md.is_empty() {
1511            return (String::new(), false);
1512        }
1513
1514        let mut replacer = |broken_link: BrokenLink<'_>| {
1515            links
1516                .iter()
1517                .find(|link| *link.original_text == *broken_link.reference)
1518                .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1519        };
1520
1521        let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer))
1522            .peekable();
1523        let mut summary = SummaryLine::new(p);
1524
1525        let mut s = String::new();
1526
1527        let without_paragraphs = LinkReplacer::new(&mut summary, links).filter(|event| {
1528            !matches!(event, Event::Start(Tag::Paragraph) | Event::End(TagEnd::Paragraph))
1529        });
1530
1531        html::push_html(&mut s, without_paragraphs);
1532
1533        let has_more_content =
1534            matches!(summary.inner.peek(), Some(Event::Start(_))) || summary.skipped_tags > 0;
1535
1536        (s, has_more_content)
1537    }
1538
1539    pub(crate) fn into_string(self) -> String {
1540        self.into_string_with_has_more_content().0
1541    }
1542}
1543
1544/// Renders a subset of Markdown in the first paragraph of the provided Markdown.
1545///
1546/// - *Italics*, **bold**, and `inline code` styles **are** rendered.
1547/// - Headings and links are stripped (though the text *is* rendered).
1548/// - HTML, code blocks, and everything else are ignored.
1549///
1550/// Returns a tuple of the rendered HTML string and whether the output was shortened
1551/// due to the provided `length_limit`.
1552fn markdown_summary_with_limit(
1553    md: &str,
1554    link_names: &[RenderedLink],
1555    length_limit: usize,
1556) -> (String, bool) {
1557    if md.is_empty() {
1558        return (String::new(), false);
1559    }
1560
1561    let mut replacer = |broken_link: BrokenLink<'_>| {
1562        link_names
1563            .iter()
1564            .find(|link| *link.original_text == *broken_link.reference)
1565            .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1566    };
1567
1568    let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1569    let mut p = LinkReplacer::new(p, link_names);
1570
1571    let mut buf = HtmlWithLimit::new(length_limit);
1572    let mut stopped_early = false;
1573    let _ = p.try_for_each(|event| {
1574        match &event {
1575            Event::Text(text) => {
1576                let r =
1577                    text.split_inclusive(char::is_whitespace).try_for_each(|word| buf.push(word));
1578                if r.is_break() {
1579                    stopped_early = true;
1580                }
1581                return r;
1582            }
1583            Event::Code(code) => {
1584                buf.open_tag("code");
1585                let r = buf.push(code);
1586                if r.is_break() {
1587                    stopped_early = true;
1588                } else {
1589                    buf.close_tag();
1590                }
1591                return r;
1592            }
1593            Event::Start(tag) => match tag {
1594                Tag::Emphasis => buf.open_tag("em"),
1595                Tag::Strong => buf.open_tag("strong"),
1596                Tag::CodeBlock(..) => return ControlFlow::Break(()),
1597                _ => {}
1598            },
1599            Event::End(tag) => match tag {
1600                TagEnd::Emphasis | TagEnd::Strong => buf.close_tag(),
1601                TagEnd::Paragraph | TagEnd::Heading(_) => return ControlFlow::Break(()),
1602                _ => {}
1603            },
1604            Event::HardBreak | Event::SoftBreak => buf.push(" ")?,
1605            _ => {}
1606        };
1607        ControlFlow::Continue(())
1608    });
1609
1610    (buf.finish(), stopped_early)
1611}
1612
1613/// Renders a shortened first paragraph of the given Markdown as a subset of Markdown,
1614/// making it suitable for contexts like the search index.
1615///
1616/// Will shorten to 59 or 60 characters, including an ellipsis (…) if it was shortened.
1617///
1618/// See [`markdown_summary_with_limit`] for details about what is rendered and what is not.
1619pub(crate) fn short_markdown_summary(markdown: &str, link_names: &[RenderedLink]) -> String {
1620    let (mut s, was_shortened) = markdown_summary_with_limit(markdown, link_names, 59);
1621
1622    if was_shortened {
1623        s.push('…');
1624    }
1625
1626    s
1627}
1628
1629/// Renders the first paragraph of the provided markdown as plain text.
1630/// Useful for alt-text.
1631///
1632/// - Headings, links, and formatting are stripped.
1633/// - Inline code is rendered as-is, surrounded by backticks.
1634/// - HTML and code blocks are ignored.
1635pub(crate) fn plain_text_summary(md: &str, link_names: &[RenderedLink]) -> String {
1636    if md.is_empty() {
1637        return String::new();
1638    }
1639
1640    let mut s = String::with_capacity(md.len() * 3 / 2);
1641
1642    let mut replacer = |broken_link: BrokenLink<'_>| {
1643        link_names
1644            .iter()
1645            .find(|link| *link.original_text == *broken_link.reference)
1646            .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1647    };
1648
1649    let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1650
1651    plain_text_from_events(p, &mut s);
1652
1653    s
1654}
1655
1656pub(crate) fn plain_text_from_events<'a>(
1657    events: impl Iterator<Item = pulldown_cmark::Event<'a>>,
1658    s: &mut String,
1659) {
1660    for event in events {
1661        match &event {
1662            Event::Text(text) => s.push_str(text),
1663            Event::Code(code) => {
1664                s.push('`');
1665                s.push_str(code);
1666                s.push('`');
1667            }
1668            Event::HardBreak | Event::SoftBreak => s.push(' '),
1669            Event::Start(Tag::CodeBlock(..)) => break,
1670            Event::End(TagEnd::Paragraph) => break,
1671            Event::End(TagEnd::Heading(..)) => break,
1672            _ => (),
1673        }
1674    }
1675}
1676
1677pub(crate) fn html_text_from_events<'a>(
1678    events: impl Iterator<Item = pulldown_cmark::Event<'a>>,
1679    s: &mut String,
1680) {
1681    for event in events {
1682        match &event {
1683            Event::Text(text) => {
1684                write!(s, "{}", EscapeBodyText(text)).expect("string alloc infallible")
1685            }
1686            Event::Code(code) => {
1687                s.push_str("<code>");
1688                write!(s, "{}", EscapeBodyText(code)).expect("string alloc infallible");
1689                s.push_str("</code>");
1690            }
1691            Event::HardBreak | Event::SoftBreak => s.push(' '),
1692            Event::Start(Tag::CodeBlock(..)) => break,
1693            Event::End(TagEnd::Paragraph) => break,
1694            Event::End(TagEnd::Heading(..)) => break,
1695            _ => (),
1696        }
1697    }
1698}
1699
1700#[derive(Debug)]
1701pub(crate) struct MarkdownLink {
1702    pub kind: LinkType,
1703    pub link: String,
1704    pub range: MarkdownLinkRange,
1705}
1706
1707#[derive(Clone, Debug)]
1708pub(crate) enum MarkdownLinkRange {
1709    /// Normally, markdown link warnings point only at the destination.
1710    Destination(Range<usize>),
1711    /// In some cases, it's not possible to point at the destination.
1712    /// Usually, this happens because backslashes `\\` are used.
1713    /// When that happens, point at the whole link, and don't provide structured suggestions.
1714    WholeLink(Range<usize>),
1715}
1716
1717impl MarkdownLinkRange {
1718    /// Extracts the inner range.
1719    pub fn inner_range(&self) -> &Range<usize> {
1720        match self {
1721            MarkdownLinkRange::Destination(range) => range,
1722            MarkdownLinkRange::WholeLink(range) => range,
1723        }
1724    }
1725}
1726
1727pub(crate) fn markdown_links<'md, R>(
1728    md: &'md str,
1729    preprocess_link: impl Fn(MarkdownLink) -> Option<R>,
1730) -> Vec<R> {
1731    use itertools::Itertools;
1732    if md.is_empty() {
1733        return vec![];
1734    }
1735
1736    // FIXME: remove this function once pulldown_cmark can provide spans for link definitions.
1737    let locate = |s: &str, fallback: Range<usize>| unsafe {
1738        let s_start = s.as_ptr();
1739        let s_end = s_start.add(s.len());
1740        let md_start = md.as_ptr();
1741        let md_end = md_start.add(md.len());
1742        if md_start <= s_start && s_end <= md_end {
1743            let start = s_start.offset_from(md_start) as usize;
1744            let end = s_end.offset_from(md_start) as usize;
1745            MarkdownLinkRange::Destination(start..end)
1746        } else {
1747            MarkdownLinkRange::WholeLink(fallback)
1748        }
1749    };
1750
1751    let span_for_link = |link: &CowStr<'_>, span: Range<usize>| {
1752        // For diagnostics, we want to underline the link's definition but `span` will point at
1753        // where the link is used. This is a problem for reference-style links, where the definition
1754        // is separate from the usage.
1755
1756        match link {
1757            // `Borrowed` variant means the string (the link's destination) may come directly from
1758            // the markdown text and we can locate the original link destination.
1759            // NOTE: LinkReplacer also provides `Borrowed` but possibly from other sources,
1760            // so `locate()` can fall back to use `span`.
1761            CowStr::Borrowed(s) => locate(s, span),
1762
1763            // For anything else, we can only use the provided range.
1764            CowStr::Boxed(_) | CowStr::Inlined(_) => MarkdownLinkRange::WholeLink(span),
1765        }
1766    };
1767
1768    let span_for_refdef = |link: &CowStr<'_>, span: Range<usize>| {
1769        // We want to underline the link's definition, but `span` will point at the entire refdef.
1770        // Skip the label, then try to find the entire URL.
1771        let mut square_brace_count = 0;
1772        let mut iter = md.as_bytes()[span.start..span.end].iter().copied().enumerate();
1773        for (_i, c) in &mut iter {
1774            match c {
1775                b':' if square_brace_count == 0 => break,
1776                b'[' => square_brace_count += 1,
1777                b']' => square_brace_count -= 1,
1778                _ => {}
1779            }
1780        }
1781        while let Some((i, c)) = iter.next() {
1782            if c == b'<' {
1783                while let Some((j, c)) = iter.next() {
1784                    match c {
1785                        b'\\' => {
1786                            let _ = iter.next();
1787                        }
1788                        b'>' => {
1789                            return MarkdownLinkRange::Destination(
1790                                i + 1 + span.start..j + span.start,
1791                            );
1792                        }
1793                        _ => {}
1794                    }
1795                }
1796            } else if !c.is_ascii_whitespace() {
1797                for (j, c) in iter.by_ref() {
1798                    if c.is_ascii_whitespace() {
1799                        return MarkdownLinkRange::Destination(i + span.start..j + span.start);
1800                    }
1801                }
1802                return MarkdownLinkRange::Destination(i + span.start..span.end);
1803            }
1804        }
1805        span_for_link(link, span)
1806    };
1807
1808    let span_for_offset_backward = |span: Range<usize>, open: u8, close: u8| {
1809        let mut open_brace = !0;
1810        let mut close_brace = !0;
1811        for (i, b) in md.as_bytes()[span.clone()].iter().copied().enumerate().rev() {
1812            let i = i + span.start;
1813            if b == close {
1814                close_brace = i;
1815                break;
1816            }
1817        }
1818        if close_brace < span.start || close_brace >= span.end {
1819            return MarkdownLinkRange::WholeLink(span);
1820        }
1821        let mut nesting = 1;
1822        for (i, b) in md.as_bytes()[span.start..close_brace].iter().copied().enumerate().rev() {
1823            let i = i + span.start;
1824            if b == close {
1825                nesting += 1;
1826            }
1827            if b == open {
1828                nesting -= 1;
1829            }
1830            if nesting == 0 {
1831                open_brace = i;
1832                break;
1833            }
1834        }
1835        assert!(open_brace != close_brace);
1836        if open_brace < span.start || open_brace >= span.end {
1837            return MarkdownLinkRange::WholeLink(span);
1838        }
1839        // do not actually include braces in the span
1840        let range = (open_brace + 1)..close_brace;
1841        MarkdownLinkRange::Destination(range)
1842    };
1843
1844    let span_for_offset_forward = |span: Range<usize>, open: u8, close: u8| {
1845        let mut open_brace = !0;
1846        let mut close_brace = !0;
1847        for (i, b) in md.as_bytes()[span.clone()].iter().copied().enumerate() {
1848            let i = i + span.start;
1849            if b == open {
1850                open_brace = i;
1851                break;
1852            }
1853        }
1854        if open_brace < span.start || open_brace >= span.end {
1855            return MarkdownLinkRange::WholeLink(span);
1856        }
1857        let mut nesting = 0;
1858        for (i, b) in md.as_bytes()[open_brace..span.end].iter().copied().enumerate() {
1859            let i = i + open_brace;
1860            if b == close {
1861                nesting -= 1;
1862            }
1863            if b == open {
1864                nesting += 1;
1865            }
1866            if nesting == 0 {
1867                close_brace = i;
1868                break;
1869            }
1870        }
1871        assert!(open_brace != close_brace);
1872        if open_brace < span.start || open_brace >= span.end {
1873            return MarkdownLinkRange::WholeLink(span);
1874        }
1875        // do not actually include braces in the span
1876        let range = (open_brace + 1)..close_brace;
1877        MarkdownLinkRange::Destination(range)
1878    };
1879
1880    let mut broken_link_callback = |link: BrokenLink<'md>| Some((link.reference, "".into()));
1881    let event_iter = Parser::new_with_broken_link_callback(
1882        md,
1883        main_body_opts(),
1884        Some(&mut broken_link_callback),
1885    )
1886    .into_offset_iter();
1887    let mut links = Vec::new();
1888
1889    let mut refdefs = FxIndexMap::default();
1890    for (label, refdef) in event_iter.reference_definitions().iter().sorted_by_key(|x| x.0) {
1891        refdefs.insert(label.to_string(), (false, refdef.dest.to_string(), refdef.span.clone()));
1892    }
1893
1894    for (event, span) in event_iter {
1895        match event {
1896            Event::Start(Tag::Link { link_type, dest_url, id, .. })
1897                if may_be_doc_link(link_type) =>
1898            {
1899                let range = match link_type {
1900                    // Link is pulled from the link itself.
1901                    LinkType::ReferenceUnknown | LinkType::ShortcutUnknown => {
1902                        span_for_offset_backward(span, b'[', b']')
1903                    }
1904                    LinkType::CollapsedUnknown => span_for_offset_forward(span, b'[', b']'),
1905                    LinkType::Inline => span_for_offset_backward(span, b'(', b')'),
1906                    // Link is pulled from elsewhere in the document.
1907                    LinkType::Reference | LinkType::Collapsed | LinkType::Shortcut => {
1908                        if let Some((is_used, dest_url, span)) = refdefs.get_mut(&id[..]) {
1909                            *is_used = true;
1910                            span_for_refdef(&CowStr::from(&dest_url[..]), span.clone())
1911                        } else {
1912                            span_for_link(&dest_url, span)
1913                        }
1914                    }
1915                    LinkType::Autolink | LinkType::Email => unreachable!(),
1916                };
1917
1918                if let Some(link) = preprocess_link(MarkdownLink {
1919                    kind: link_type,
1920                    link: dest_url.into_string(),
1921                    range,
1922                }) {
1923                    links.push(link);
1924                }
1925            }
1926            _ => {}
1927        }
1928    }
1929
1930    for (_label, (is_used, dest_url, span)) in refdefs.into_iter() {
1931        if !is_used
1932            && let Some(link) = preprocess_link(MarkdownLink {
1933                kind: LinkType::Reference,
1934                range: span_for_refdef(&CowStr::from(&dest_url[..]), span),
1935                link: dest_url,
1936            })
1937        {
1938            links.push(link);
1939        }
1940    }
1941
1942    links
1943}
1944
1945#[derive(Debug)]
1946pub(crate) struct RustCodeBlock {
1947    /// The range in the markdown that the code block occupies. Note that this includes the fences
1948    /// for fenced code blocks.
1949    pub(crate) range: Range<usize>,
1950    /// The range in the markdown that the code within the code block occupies.
1951    pub(crate) code: Range<usize>,
1952    pub(crate) is_fenced: bool,
1953    pub(crate) lang_string: LangString,
1954}
1955
1956/// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
1957/// untagged (and assumed to be rust).
1958pub(crate) fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_>) -> Vec<RustCodeBlock> {
1959    let mut code_blocks = vec![];
1960
1961    if md.is_empty() {
1962        return code_blocks;
1963    }
1964
1965    let mut p = Parser::new_ext(md, main_body_opts()).into_offset_iter();
1966
1967    while let Some((event, offset)) = p.next() {
1968        if let Event::Start(Tag::CodeBlock(syntax)) = event {
1969            let (lang_string, code_start, code_end, range, is_fenced) = match syntax {
1970                CodeBlockKind::Fenced(syntax) => {
1971                    let syntax = syntax.as_ref();
1972                    let lang_string = if syntax.is_empty() {
1973                        Default::default()
1974                    } else {
1975                        LangString::parse(syntax, ErrorCodes::Yes, Some(extra_info))
1976                    };
1977                    if !lang_string.rust {
1978                        continue;
1979                    }
1980                    let (code_start, mut code_end) = match p.next() {
1981                        Some((Event::Text(_), offset)) => (offset.start, offset.end),
1982                        Some((_, sub_offset)) => {
1983                            let code = Range { start: sub_offset.start, end: sub_offset.start };
1984                            code_blocks.push(RustCodeBlock {
1985                                is_fenced: true,
1986                                range: offset,
1987                                code,
1988                                lang_string,
1989                            });
1990                            continue;
1991                        }
1992                        None => {
1993                            let code = Range { start: offset.end, end: offset.end };
1994                            code_blocks.push(RustCodeBlock {
1995                                is_fenced: true,
1996                                range: offset,
1997                                code,
1998                                lang_string,
1999                            });
2000                            continue;
2001                        }
2002                    };
2003                    while let Some((Event::Text(_), offset)) = p.next() {
2004                        code_end = offset.end;
2005                    }
2006                    (lang_string, code_start, code_end, offset, true)
2007                }
2008                CodeBlockKind::Indented => {
2009                    // The ending of the offset goes too far sometime so we reduce it by one in
2010                    // these cases.
2011                    if offset.end > offset.start && md.get(offset.end..=offset.end) == Some("\n") {
2012                        (
2013                            LangString::default(),
2014                            offset.start,
2015                            offset.end,
2016                            Range { start: offset.start, end: offset.end - 1 },
2017                            false,
2018                        )
2019                    } else {
2020                        (LangString::default(), offset.start, offset.end, offset, false)
2021                    }
2022                }
2023            };
2024
2025            code_blocks.push(RustCodeBlock {
2026                is_fenced,
2027                range,
2028                code: Range { start: code_start, end: code_end },
2029                lang_string,
2030            });
2031        }
2032    }
2033
2034    code_blocks
2035}
2036
2037#[derive(Clone, Default, Debug)]
2038pub struct IdMap {
2039    map: FxHashMap<String, usize>,
2040    existing_footnotes: Arc<AtomicUsize>,
2041}
2042
2043fn is_default_id(id: &str) -> bool {
2044    matches!(
2045        id,
2046        // This is the list of IDs used in JavaScript.
2047        "help"
2048        | "settings"
2049        | "not-displayed"
2050        | "alternative-display"
2051        | "search"
2052        | "crate-search"
2053        | "crate-search-div"
2054        // This is the list of IDs used in HTML generated in Rust (including the ones
2055        // used in askama template files).
2056        | "themeStyle"
2057        | "settings-menu"
2058        | "help-button"
2059        | "sidebar-button"
2060        | "main-content"
2061        | "toggle-all-docs"
2062        | "all-types"
2063        | "default-settings"
2064        | "sidebar-vars"
2065        | "copy-path"
2066        | "rustdoc-toc"
2067        | "rustdoc-modnav"
2068        // This is the list of IDs used by rustdoc sections (but still generated by
2069        // rustdoc).
2070        | "fields"
2071        | "variants"
2072        | "implementors-list"
2073        | "synthetic-implementors-list"
2074        | "foreign-impls"
2075        | "implementations"
2076        | "trait-implementations"
2077        | "synthetic-implementations"
2078        | "blanket-implementations"
2079        | "required-associated-types"
2080        | "provided-associated-types"
2081        | "provided-associated-consts"
2082        | "required-associated-consts"
2083        | "required-methods"
2084        | "provided-methods"
2085        | "dyn-compatibility"
2086        | "implementors"
2087        | "synthetic-implementors"
2088        | "implementations-list"
2089        | "trait-implementations-list"
2090        | "synthetic-implementations-list"
2091        | "blanket-implementations-list"
2092        | "deref-methods"
2093        | "layout"
2094        | "aliased-type",
2095    )
2096}
2097
2098impl IdMap {
2099    pub fn new() -> Self {
2100        IdMap { map: FxHashMap::default(), existing_footnotes: Arc::new(AtomicUsize::new(0)) }
2101    }
2102
2103    pub(crate) fn derive<S: AsRef<str> + ToString>(&mut self, candidate: S) -> String {
2104        let id = match self.map.get_mut(candidate.as_ref()) {
2105            None => {
2106                let candidate = candidate.to_string();
2107                if is_default_id(&candidate) {
2108                    let id = format!("{}-{}", candidate, 1);
2109                    self.map.insert(candidate, 2);
2110                    id
2111                } else {
2112                    candidate
2113                }
2114            }
2115            Some(a) => {
2116                let id = format!("{}-{}", candidate.as_ref(), *a);
2117                *a += 1;
2118                id
2119            }
2120        };
2121
2122        self.map.insert(id.clone(), 1);
2123        id
2124    }
2125
2126    /// Method to handle `existing_footnotes` increment automatically (to prevent forgetting
2127    /// about it).
2128    pub(crate) fn handle_footnotes<'a, T, F: FnOnce(&'a mut Self, Weak<AtomicUsize>) -> T>(
2129        &'a mut self,
2130        closure: F,
2131    ) -> T {
2132        let existing_footnotes = Arc::downgrade(&self.existing_footnotes);
2133
2134        closure(self, existing_footnotes)
2135    }
2136
2137    pub(crate) fn clear(&mut self) {
2138        self.map.clear();
2139        self.existing_footnotes = Arc::new(AtomicUsize::new(0));
2140    }
2141}