1 //! Markdown formatting for rustdoc.
3 //! This module implements markdown formatting through the pulldown-cmark library.
6 //! #![feature(rustc_private)]
8 //! extern crate rustc_span;
10 //! use rustc_span::edition::Edition;
11 //! use rustdoc::html::markdown::{HeadingOffset, IdMap, Markdown, ErrorCodes};
13 //! let s = "My *markdown* _text_";
14 //! let mut id_map = IdMap::new();
15 //! let md = Markdown {
19 //! error_codes: ErrorCodes::Yes,
20 //! edition: Edition::Edition2015,
21 //! playground: &None,
22 //! heading_offset: HeadingOffset::H2,
24 //! let html = md.into_string();
25 //! // ... something using html
28 use rustc_data_structures::fx::FxHashMap;
29 use rustc_hir::def_id::DefId;
31 use rustc_middle::ty::TyCtxt;
32 use rustc_span::edition::Edition;
36 use std::cell::RefCell;
37 use std::collections::VecDeque;
38 use std::default::Default;
40 use std::ops::{ControlFlow, Range};
43 use crate::clean::RenderedLink;
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;
52 html, BrokenLink, CodeBlockKind, CowStr, Event, LinkType, Options, Parser, Tag,
58 const MAX_HEADER_LEVEL: u32 = 6;
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
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
78 #[derive(Debug, Clone, Copy)]
79 pub enum HeadingOffset {
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> {
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`).
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,
105 /// A tuple struct like `Markdown` that renders the markdown with a table of contents.
106 crate struct MarkdownWithToc<'a>(
111 crate &'a Option<Playground>,
113 /// A tuple struct like `Markdown` that renders the markdown escaping HTML tags.
114 crate struct MarkdownHtml<'a>(
119 crate &'a Option<Playground>,
121 /// A tuple struct like `Markdown` that renders only the first paragraph.
122 crate struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [RenderedLink]);
124 #[derive(Copy, Clone, PartialEq, Debug)]
125 pub enum ErrorCodes {
131 crate fn from(b: bool) -> Self {
133 true => ErrorCodes::Yes,
134 false => ErrorCodes::No,
138 crate fn as_bool(self) -> bool {
140 ErrorCodes::Yes => true,
141 ErrorCodes::No => false,
146 /// Controls whether a line will be hidden or shown in HTML output.
148 /// All lines are used in documentation tests.
155 fn for_html(self) -> Option<Cow<'a, str>> {
157 Line::Shown(l) => Some(l),
158 Line::Hidden(_) => None,
162 fn for_code(self) -> Cow<'a, str> {
165 Line::Hidden(l) => Cow::Borrowed(l),
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("# ") {
181 Line::Hidden(&stripped)
182 } else if trimmed == "#" {
183 // We cannot handle '#text' because it could be #[attr].
186 Line::Shown(Cow::Borrowed(s))
190 /// Convert chars from a title for an id.
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() {
203 #[derive(Clone, Debug)]
204 pub struct Playground {
205 pub crate_name: Option<String>,
209 /// Adds syntax highlighting and playground Run buttons to Rust code blocks.
210 struct CodeBlocks<'p, 'a, I: Iterator<Item = Event<'a>>> {
212 check_error_codes: ErrorCodes,
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>,
219 impl<'p, 'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'p, 'a, I> {
222 error_codes: ErrorCodes,
224 playground: &'p Option<Playground>,
226 CodeBlocks { inner: iter, check_error_codes: error_codes, edition, playground }
230 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
231 type Item = Event<'a>;
233 fn next(&mut self) -> Option<Self::Item> {
234 let event = self.inner.next();
239 let kind = if let Some(Event::Start(Tag::CodeBlock(kind))) = event {
245 let mut origtext = String::new();
246 for event in &mut self.inner {
248 Event::End(Tag::CodeBlock(..)) => break,
249 Event::Text(ref s) => {
250 origtext.push_str(s);
255 let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
256 let text = lines.collect::<Vec<Cow<'_, str>>>().join("\n");
258 let parse_result = match kind {
259 CodeBlockKind::Fenced(ref lang) => {
261 LangString::parse_without_check(&lang, self.check_error_codes, false);
262 if !parse_result.rust {
263 return Some(Event::Html(
265 "<div class=\"example-wrap\">\
266 <pre class=\"language-{}\"><code>{}</code></pre>\
276 CodeBlockKind::Indented => Default::default(),
279 compile_fail = parse_result.compile_fail;
280 should_panic = parse_result.should_panic;
281 ignore = parse_result.ignore;
282 edition = parse_result.edition;
284 let explicit_edition = edition.is_some();
285 let edition = edition.unwrap_or(self.edition);
287 let playground_button = self.playground.as_ref().and_then(|playground| {
288 let krate = &playground.crate_name;
289 let url = &playground.url;
295 .map(|l| map_line(l).for_code())
296 .collect::<Vec<Cow<'_, str>>>()
298 let krate = krate.as_ref().map(|s| &**s);
300 doctest::make_test(&test, krate, false, &Default::default(), edition, None);
301 let channel = if test.contains("#![feature(") { "&version=nightly" } else { "" };
303 let edition_string = format!("&edition={}", edition);
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')
321 let mut test_escaped = String::new();
322 for b in test.bytes() {
324 test_escaped.push(char::from(b));
326 write!(test_escaped, "%{:02X}", b).unwrap();
330 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}{}">Run</a>"#,
331 url, test_escaped, channel, edition_string
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"))
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();
351 highlight::render_with_highlighting(
355 "rust-example-rendered{}",
356 if let Some((_, class)) = tooltip { format!(" {}", class) } else { String::new() }
358 playground_button.as_deref(),
364 Some(Event::Html(s.into_inner().into()))
368 /// Make headings links with anchor IDs and build up TOC.
369 struct LinkReplacer<'a, I: Iterator<Item = Event<'a>>> {
371 links: &'a [RenderedLink],
372 shortcut_link: Option<&'a RenderedLink>,
375 impl<'a, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, I> {
376 fn new(iter: I, links: &'a [RenderedLink]) -> Self {
377 LinkReplacer { inner: iter, links, shortcut_link: None }
381 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
382 type Item = Event<'a>;
384 fn next(&mut self) -> Option<Self::Item> {
385 let mut event = self.inner.next();
387 // Replace intra-doc links and remove disambiguators from shortcut links (`[fn@f]`).
389 // This is a shortcut link that was resolved by the broken_link_callback: `[fn@f]`
390 // Remove any disambiguator.
391 Some(Event::Start(Tag::Link(
392 // [fn@f] or [fn@f][]
393 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
397 debug!("saw start of shortcut link to {} with title {}", dest, title);
398 // If this is a shortcut link, it was resolved by the broken_link_callback.
399 // So the URL will already be updated properly.
400 let link = self.links.iter().find(|&link| *link.href == **dest);
401 // Since this is an external iterator, we can't replace the inner text just yet.
402 // Store that we saw a link so we know to replace it later.
403 if let Some(link) = link {
404 trace!("it matched");
405 assert!(self.shortcut_link.is_none(), "shortcut links cannot be nested");
406 self.shortcut_link = Some(link);
409 // Now that we're done with the shortcut link, don't replace any more text.
410 Some(Event::End(Tag::Link(
411 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
415 debug!("saw end of shortcut link to {}", dest);
416 if self.links.iter().any(|link| *link.href == **dest) {
417 assert!(self.shortcut_link.is_some(), "saw closing link without opening tag");
418 self.shortcut_link = None;
421 // Handle backticks in inline code blocks, but only if we're in the middle of a shortcut link.
423 Some(Event::Code(text)) => {
424 trace!("saw code {}", text);
425 if let Some(link) = self.shortcut_link {
426 trace!("original text was {}", link.original_text);
427 // NOTE: this only replaces if the code block is the *entire* text.
428 // If only part of the link has code highlighting, the disambiguator will not be removed.
430 // This is a limitation from `collect_intra_doc_links`: it passes a full link,
431 // and does not distinguish at all between code blocks.
432 // So we could never be sure we weren't replacing too much:
433 // [fn@my_`f`unc] is treated the same as [my_func()] in that pass.
435 // NOTE: &[1..len() - 1] is to strip the backticks
436 if **text == link.original_text[1..link.original_text.len() - 1] {
437 debug!("replacing {} with {}", text, link.new_text);
438 *text = CowStr::Borrowed(&link.new_text);
442 // Replace plain text in links, but only in the middle of a shortcut link.
444 Some(Event::Text(text)) => {
445 trace!("saw text {}", text);
446 if let Some(link) = self.shortcut_link {
447 trace!("original text was {}", link.original_text);
448 // NOTE: same limitations as `Event::Code`
449 if **text == *link.original_text {
450 debug!("replacing {} with {}", text, link.new_text);
451 *text = CowStr::Borrowed(&link.new_text);
455 // If this is a link, but not a shortcut link,
456 // replace the URL, since the broken_link_callback was not called.
457 Some(Event::Start(Tag::Link(_, dest, _))) => {
458 if let Some(link) = self.links.iter().find(|&link| *link.original_text == **dest) {
459 *dest = CowStr::Borrowed(link.href.as_ref());
462 // Anything else couldn't have been a valid Rust path, so no need to replace the text.
466 // Yield the modified event
471 /// Wrap HTML tables into `<div>` to prevent having the doc blocks width being too big.
472 struct TableWrapper<'a, I: Iterator<Item = Event<'a>>> {
474 stored_events: VecDeque<Event<'a>>,
477 impl<'a, I: Iterator<Item = Event<'a>>> TableWrapper<'a, I> {
478 fn new(iter: I) -> Self {
479 Self { inner: iter, stored_events: VecDeque::new() }
483 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for TableWrapper<'a, I> {
484 type Item = Event<'a>;
486 fn next(&mut self) -> Option<Self::Item> {
487 if let Some(first) = self.stored_events.pop_front() {
491 let event = self.inner.next()?;
494 Event::Start(Tag::Table(t)) => {
495 self.stored_events.push_back(Event::Start(Tag::Table(t)));
496 Event::Html(CowStr::Borrowed("<div>"))
498 Event::End(Tag::Table(t)) => {
499 self.stored_events.push_back(Event::Html(CowStr::Borrowed("</div>")));
500 Event::End(Tag::Table(t))
507 type SpannedEvent<'a> = (Event<'a>, Range<usize>);
509 /// Make headings links with anchor IDs and build up TOC.
510 struct HeadingLinks<'a, 'b, 'ids, I> {
512 toc: Option<&'b mut TocBuilder>,
513 buf: VecDeque<SpannedEvent<'a>>,
514 id_map: &'ids mut IdMap,
515 heading_offset: HeadingOffset,
518 impl<'a, 'b, 'ids, I> HeadingLinks<'a, 'b, 'ids, I> {
521 toc: Option<&'b mut TocBuilder>,
522 ids: &'ids mut IdMap,
523 heading_offset: HeadingOffset,
525 HeadingLinks { inner: iter, toc, buf: VecDeque::new(), id_map: ids, heading_offset }
529 impl<'a, 'b, 'ids, I: Iterator<Item = SpannedEvent<'a>>> Iterator
530 for HeadingLinks<'a, 'b, 'ids, I>
532 type Item = SpannedEvent<'a>;
534 fn next(&mut self) -> Option<Self::Item> {
535 if let Some(e) = self.buf.pop_front() {
539 let event = self.inner.next();
540 if let Some((Event::Start(Tag::Heading(level)), _)) = event {
541 let mut id = String::new();
542 for event in &mut self.inner {
544 Event::End(Tag::Heading(..)) => break,
545 Event::Start(Tag::Link(_, _, _)) | Event::End(Tag::Link(..)) => {}
546 Event::Text(text) | Event::Code(text) => {
547 id.extend(text.chars().filter_map(slugify));
548 self.buf.push_back(event);
550 _ => self.buf.push_back(event),
553 let id = self.id_map.derive(id);
555 if let Some(ref mut builder) = self.toc {
556 let mut html_header = String::new();
557 html::push_html(&mut html_header, self.buf.iter().map(|(ev, _)| ev.clone()));
558 let sec = builder.push(level as u32, html_header, id.clone());
559 self.buf.push_front((Event::Html(format!("{} ", sec).into()), 0..0));
562 let level = std::cmp::min(level + (self.heading_offset as u32), MAX_HEADER_LEVEL);
563 self.buf.push_back((Event::Html(format!("</a></h{}>", level).into()), 0..0));
565 let start_tags = format!(
566 "<h{level} id=\"{id}\" class=\"section-header\">\
571 return Some((Event::Html(start_tags.into()), 0..0));
577 /// Extracts just the first paragraph.
578 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
584 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
585 fn new(iter: I) -> Self {
586 SummaryLine { inner: iter, started: false, depth: 0 }
590 fn check_if_allowed_tag(t: &Tag<'_>) -> bool {
593 Tag::Paragraph | Tag::Item | Tag::Emphasis | Tag::Strong | Tag::Link(..) | Tag::BlockQuote
597 fn is_forbidden_tag(t: &Tag<'_>) -> bool {
598 matches!(t, Tag::CodeBlock(_) | Tag::Table(_) | Tag::TableHead | Tag::TableRow | Tag::TableCell)
601 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
602 type Item = Event<'a>;
604 fn next(&mut self) -> Option<Self::Item> {
605 if self.started && self.depth == 0 {
611 if let Some(event) = self.inner.next() {
612 let mut is_start = true;
613 let is_allowed_tag = match event {
614 Event::Start(ref c) => {
615 if is_forbidden_tag(c) {
619 check_if_allowed_tag(c)
621 Event::End(ref c) => {
622 if is_forbidden_tag(c) {
627 check_if_allowed_tag(c)
631 return if !is_allowed_tag {
633 Some(Event::Start(Tag::Paragraph))
635 Some(Event::End(Tag::Paragraph))
645 /// Moves all footnote definitions to the end and add back links to the
647 struct Footnotes<'a, I> {
649 footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
652 impl<'a, I> Footnotes<'a, I> {
653 fn new(iter: I) -> Self {
654 Footnotes { inner: iter, footnotes: FxHashMap::default() }
657 fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
658 let new_id = self.footnotes.keys().count() + 1;
659 let key = key.to_owned();
660 self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
664 impl<'a, I: Iterator<Item = SpannedEvent<'a>>> Iterator for Footnotes<'a, I> {
665 type Item = SpannedEvent<'a>;
667 fn next(&mut self) -> Option<Self::Item> {
669 match self.inner.next() {
670 Some((Event::FootnoteReference(ref reference), range)) => {
671 let entry = self.get_entry(&reference);
672 let reference = format!(
673 "<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}</a></sup>",
676 return Some((Event::Html(reference.into()), range));
678 Some((Event::Start(Tag::FootnoteDefinition(def)), _)) => {
679 let mut content = Vec::new();
680 for (event, _) in &mut self.inner {
681 if let Event::End(Tag::FootnoteDefinition(..)) = event {
686 let entry = self.get_entry(&def);
687 (*entry).0 = content;
689 Some(e) => return Some(e),
691 if !self.footnotes.is_empty() {
692 let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
693 v.sort_by(|a, b| a.1.cmp(&b.1));
694 let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
695 for (mut content, id) in v {
696 write!(ret, "<li id=\"fn{}\">", id).unwrap();
697 let mut is_paragraph = false;
698 if let Some(&Event::End(Tag::Paragraph)) = content.last() {
702 html::push_html(&mut ret, content.into_iter());
703 write!(ret, " <a href=\"#fnref{}\">↩</a>", id).unwrap();
705 ret.push_str("</p>");
707 ret.push_str("</li>");
709 ret.push_str("</ol></div>");
710 return Some((Event::Html(ret.into()), 0..0));
720 crate fn find_testable_code<T: doctest::Tester>(
723 error_codes: ErrorCodes,
724 enable_per_target_ignores: bool,
725 extra_info: Option<&ExtraInfo<'_>>,
727 let mut parser = Parser::new(doc).into_offset_iter();
728 let mut prev_offset = 0;
729 let mut nb_lines = 0;
730 let mut register_header = None;
731 while let Some((event, offset)) = parser.next() {
733 Event::Start(Tag::CodeBlock(kind)) => {
734 let block_info = match kind {
735 CodeBlockKind::Fenced(ref lang) => {
742 enable_per_target_ignores,
747 CodeBlockKind::Indented => Default::default(),
749 if !block_info.rust {
753 let mut test_s = String::new();
755 while let Some((Event::Text(s), _)) = parser.next() {
760 .map(|l| map_line(l).for_code())
761 .collect::<Vec<Cow<'_, str>>>()
764 nb_lines += doc[prev_offset..offset.start].lines().count();
765 // If there are characters between the preceding line ending and
766 // this code block, `str::lines` will return an additional line,
767 // which we subtract here.
768 if nb_lines != 0 && !&doc[prev_offset..offset.start].ends_with('\n') {
771 let line = tests.get_line() + nb_lines + 1;
772 tests.add_test(text, block_info, line);
773 prev_offset = offset.start;
775 Event::Start(Tag::Heading(level)) => {
776 register_header = Some(level as u32);
778 Event::Text(ref s) if register_header.is_some() => {
779 let level = register_header.unwrap();
781 tests.register_header("", level);
783 tests.register_header(s, level);
785 register_header = None;
792 crate struct ExtraInfo<'tcx> {
803 impl<'tcx> ExtraInfo<'tcx> {
804 crate fn new(tcx: TyCtxt<'tcx>, hir_id: HirId, sp: Span) -> ExtraInfo<'tcx> {
805 ExtraInfo { id: ExtraInfoId::Hir(hir_id), sp, tcx }
808 crate fn new_did(tcx: TyCtxt<'tcx>, did: DefId, sp: Span) -> ExtraInfo<'tcx> {
809 ExtraInfo { id: ExtraInfoId::Def(did), sp, tcx }
812 fn error_invalid_codeblock_attr(&self, msg: &str, help: &str) {
813 let hir_id = match self.id {
814 ExtraInfoId::Hir(hir_id) => hir_id,
815 ExtraInfoId::Def(item_did) => {
816 match item_did.as_local() {
817 Some(item_did) => self.tcx.hir().local_def_id_to_hir_id(item_did),
819 // If non-local, no need to check anything.
825 self.tcx.struct_span_lint_hir(
826 crate::lint::INVALID_CODEBLOCK_ATTRIBUTES,
830 let mut diag = lint.build(msg);
838 #[derive(Eq, PartialEq, Clone, Debug)]
839 crate struct LangString {
841 crate should_panic: bool,
843 crate ignore: Ignore,
845 crate test_harness: bool,
846 crate compile_fail: bool,
847 crate error_codes: Vec<String>,
848 crate allow_fail: bool,
849 crate edition: Option<Edition>,
852 #[derive(Eq, PartialEq, Clone, Debug)]
859 impl Default for LangString {
860 fn default() -> Self {
862 original: String::new(),
865 ignore: Ignore::None,
869 error_codes: Vec::new(),
877 fn parse_without_check(
879 allow_error_code_check: ErrorCodes,
880 enable_per_target_ignores: bool,
882 Self::parse(string, allow_error_code_check, enable_per_target_ignores, None)
885 fn tokens(string: &str) -> impl Iterator<Item = &str> {
886 // Pandoc, which Rust once used for generating documentation,
887 // expects lang strings to be surrounded by `{}` and for each token
888 // to be proceeded by a `.`. Since some of these lang strings are still
889 // loose in the wild, we strip a pair of surrounding `{}` from the lang
890 // string and a leading `.` from each token.
892 let string = string.trim();
894 let first = string.chars().next();
895 let last = string.chars().last();
897 let string = if first == Some('{') && last == Some('}') {
898 &string[1..string.len() - 1]
904 .split(|c| c == ',' || c == ' ' || c == '\t')
906 .map(|token| if token.chars().next() == Some('.') { &token[1..] } else { token })
907 .filter(|token| !token.is_empty())
912 allow_error_code_check: ErrorCodes,
913 enable_per_target_ignores: bool,
914 extra: Option<&ExtraInfo<'_>>,
916 let allow_error_code_check = allow_error_code_check.as_bool();
917 let mut seen_rust_tags = false;
918 let mut seen_other_tags = false;
919 let mut data = LangString::default();
920 let mut ignores = vec![];
922 data.original = string.to_owned();
924 let tokens = Self::tokens(string).collect::<Vec<&str>>();
926 for token in tokens {
929 data.should_panic = true;
930 seen_rust_tags = !seen_other_tags;
934 seen_rust_tags = !seen_other_tags;
937 data.ignore = Ignore::All;
938 seen_rust_tags = !seen_other_tags;
940 x if x.starts_with("ignore-") => {
941 if enable_per_target_ignores {
942 ignores.push(x.trim_start_matches("ignore-").to_owned());
943 seen_rust_tags = !seen_other_tags;
947 data.allow_fail = true;
948 seen_rust_tags = !seen_other_tags;
952 seen_rust_tags = true;
955 data.test_harness = true;
956 seen_rust_tags = !seen_other_tags || seen_rust_tags;
959 data.compile_fail = true;
960 seen_rust_tags = !seen_other_tags || seen_rust_tags;
963 x if x.starts_with("edition") => {
964 data.edition = x[7..].parse::<Edition>().ok();
966 x if allow_error_code_check && x.starts_with('E') && x.len() == 5 => {
967 if x[1..].parse::<u32>().is_ok() {
968 data.error_codes.push(x.to_owned());
969 seen_rust_tags = !seen_other_tags || seen_rust_tags;
971 seen_other_tags = true;
974 x if extra.is_some() => {
975 let s = x.to_lowercase();
976 match if s == "compile-fail" || s == "compile_fail" || s == "compilefail" {
979 "the code block will either not be tested if not marked as a rust one \
980 or won't fail if it compiles successfully",
982 } else if s == "should-panic" || s == "should_panic" || s == "shouldpanic" {
985 "the code block will either not be tested if not marked as a rust one \
986 or won't fail if it doesn't panic when running",
988 } else if s == "no-run" || s == "no_run" || s == "norun" {
991 "the code block will either not be tested if not marked as a rust one \
992 or will be run (which you might not want)",
994 } else if s == "allow-fail" || s == "allow_fail" || s == "allowfail" {
997 "the code block will either not be tested if not marked as a rust one \
998 or will be run (which you might not want)",
1000 } else if s == "test-harness" || s == "test_harness" || s == "testharness" {
1003 "the code block will either not be tested if not marked as a rust one \
1004 or the code will be wrapped inside a main function",
1009 Some((flag, help)) => {
1010 if let Some(ref extra) = extra {
1011 extra.error_invalid_codeblock_attr(
1012 &format!("unknown attribute `{}`. Did you mean `{}`?", x, flag),
1019 seen_other_tags = true;
1021 _ => seen_other_tags = true,
1025 // ignore-foo overrides ignore
1026 if !ignores.is_empty() {
1027 data.ignore = Ignore::Some(ignores);
1030 data.rust &= !seen_other_tags || seen_rust_tags;
1037 pub fn into_string(self) -> String {
1048 // This is actually common enough to special-case
1050 return String::new();
1052 let mut replacer = |broken_link: BrokenLink<'_>| {
1054 links.iter().find(|link| &*link.original_text == broken_link.reference)
1056 Some((link.href.as_str().into(), link.new_text.as_str().into()))
1062 let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(&mut replacer));
1063 let p = p.into_offset_iter();
1065 let mut s = String::with_capacity(md.len() * 3 / 2);
1067 let p = HeadingLinks::new(p, None, &mut ids, heading_offset);
1068 let p = Footnotes::new(p);
1069 let p = LinkReplacer::new(p.map(|(ev, _)| ev), links);
1070 let p = TableWrapper::new(p);
1071 let p = CodeBlocks::new(p, codes, edition, playground);
1072 html::push_html(&mut s, p);
1078 impl MarkdownWithToc<'_> {
1079 crate fn into_string(self) -> String {
1080 let MarkdownWithToc(md, mut ids, codes, edition, playground) = self;
1082 let p = Parser::new_ext(md, main_body_opts()).into_offset_iter();
1084 let mut s = String::with_capacity(md.len() * 3 / 2);
1086 let mut toc = TocBuilder::new();
1089 let p = HeadingLinks::new(p, Some(&mut toc), &mut ids, HeadingOffset::H1);
1090 let p = Footnotes::new(p);
1091 let p = TableWrapper::new(p.map(|(ev, _)| ev));
1092 let p = CodeBlocks::new(p, codes, edition, playground);
1093 html::push_html(&mut s, p);
1096 format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s)
1100 impl MarkdownHtml<'_> {
1101 crate fn into_string(self) -> String {
1102 let MarkdownHtml(md, mut ids, codes, edition, playground) = self;
1104 // This is actually common enough to special-case
1106 return String::new();
1108 let p = Parser::new_ext(md, main_body_opts()).into_offset_iter();
1110 // Treat inline HTML as plain text.
1111 let p = p.map(|event| match event.0 {
1112 Event::Html(text) => (Event::Text(text), event.1),
1116 let mut s = String::with_capacity(md.len() * 3 / 2);
1118 let p = HeadingLinks::new(p, None, &mut ids, HeadingOffset::H1);
1119 let p = Footnotes::new(p);
1120 let p = TableWrapper::new(p.map(|(ev, _)| ev));
1121 let p = CodeBlocks::new(p, codes, edition, playground);
1122 html::push_html(&mut s, p);
1128 impl MarkdownSummaryLine<'_> {
1129 crate fn into_string(self) -> String {
1130 let MarkdownSummaryLine(md, links) = self;
1131 // This is actually common enough to special-case
1133 return String::new();
1136 let mut replacer = |broken_link: BrokenLink<'_>| {
1138 links.iter().find(|link| &*link.original_text == broken_link.reference)
1140 Some((link.href.as_str().into(), link.new_text.as_str().into()))
1146 let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1148 let mut s = String::new();
1150 html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
1156 /// Renders a subset of Markdown in the first paragraph of the provided Markdown.
1158 /// - *Italics*, **bold**, and `inline code` styles **are** rendered.
1159 /// - Headings and links are stripped (though the text *is* rendered).
1160 /// - HTML, code blocks, and everything else are ignored.
1162 /// Returns a tuple of the rendered HTML string and whether the output was shortened
1163 /// due to the provided `length_limit`.
1164 fn markdown_summary_with_limit(
1166 link_names: &[RenderedLink],
1167 length_limit: usize,
1168 ) -> (String, bool) {
1170 return (String::new(), false);
1173 let mut replacer = |broken_link: BrokenLink<'_>| {
1175 link_names.iter().find(|link| &*link.original_text == broken_link.reference)
1177 Some((link.href.as_str().into(), link.new_text.as_str().into()))
1183 let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1184 let mut p = LinkReplacer::new(p, link_names);
1186 let mut buf = HtmlWithLimit::new(length_limit);
1187 let mut stopped_early = false;
1188 p.try_for_each(|event| {
1190 Event::Text(text) => {
1192 text.split_inclusive(char::is_whitespace).try_for_each(|word| buf.push(word));
1194 stopped_early = true;
1198 Event::Code(code) => {
1199 buf.open_tag("code");
1200 let r = buf.push(code);
1202 stopped_early = true;
1208 Event::Start(tag) => match tag {
1209 Tag::Emphasis => buf.open_tag("em"),
1210 Tag::Strong => buf.open_tag("strong"),
1211 Tag::CodeBlock(..) => return ControlFlow::BREAK,
1214 Event::End(tag) => match tag {
1215 Tag::Emphasis | Tag::Strong => buf.close_tag(),
1216 Tag::Paragraph | Tag::Heading(..) => return ControlFlow::BREAK,
1219 Event::HardBreak | Event::SoftBreak => buf.push(" ")?,
1222 ControlFlow::CONTINUE
1225 (buf.finish(), stopped_early)
1228 /// Renders a shortened first paragraph of the given Markdown as a subset of Markdown,
1229 /// making it suitable for contexts like the search index.
1231 /// Will shorten to 59 or 60 characters, including an ellipsis (…) if it was shortened.
1233 /// See [`markdown_summary_with_limit`] for details about what is rendered and what is not.
1234 crate fn short_markdown_summary(markdown: &str, link_names: &[RenderedLink]) -> String {
1235 let (mut s, was_shortened) = markdown_summary_with_limit(markdown, link_names, 59);
1244 /// Renders the first paragraph of the provided markdown as plain text.
1245 /// Useful for alt-text.
1247 /// - Headings, links, and formatting are stripped.
1248 /// - Inline code is rendered as-is, surrounded by backticks.
1249 /// - HTML and code blocks are ignored.
1250 crate fn plain_text_summary(md: &str) -> String {
1252 return String::new();
1255 let mut s = String::with_capacity(md.len() * 3 / 2);
1257 for event in Parser::new_ext(md, summary_opts()) {
1259 Event::Text(text) => s.push_str(text),
1260 Event::Code(code) => {
1265 Event::HardBreak | Event::SoftBreak => s.push(' '),
1266 Event::Start(Tag::CodeBlock(..)) => break,
1267 Event::End(Tag::Paragraph) => break,
1268 Event::End(Tag::Heading(..)) => break,
1277 crate struct MarkdownLink {
1280 pub range: Range<usize>,
1283 crate fn markdown_links(md: &str) -> Vec<MarkdownLink> {
1288 let links = RefCell::new(vec![]);
1290 // FIXME: remove this function once pulldown_cmark can provide spans for link definitions.
1291 let locate = |s: &str, fallback: Range<usize>| unsafe {
1292 let s_start = s.as_ptr();
1293 let s_end = s_start.add(s.len());
1294 let md_start = md.as_ptr();
1295 let md_end = md_start.add(md.len());
1296 if md_start <= s_start && s_end <= md_end {
1297 let start = s_start.offset_from(md_start) as usize;
1298 let end = s_end.offset_from(md_start) as usize;
1305 let span_for_link = |link: &CowStr<'_>, span: Range<usize>| {
1306 // For diagnostics, we want to underline the link's definition but `span` will point at
1307 // where the link is used. This is a problem for reference-style links, where the definition
1308 // is separate from the usage.
1310 // `Borrowed` variant means the string (the link's destination) may come directly from
1311 // the markdown text and we can locate the original link destination.
1312 // NOTE: LinkReplacer also provides `Borrowed` but possibly from other sources,
1313 // so `locate()` can fall back to use `span`.
1314 CowStr::Borrowed(s) => locate(s, span),
1316 // For anything else, we can only use the provided range.
1317 CowStr::Boxed(_) | CowStr::Inlined(_) => span,
1321 let mut push = |link: BrokenLink<'_>| {
1322 let span = span_for_link(&CowStr::Borrowed(link.reference), link.span);
1323 links.borrow_mut().push(MarkdownLink {
1324 kind: LinkType::ShortcutUnknown,
1325 link: link.reference.to_owned(),
1330 let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(&mut push))
1331 .into_offset_iter();
1333 // There's no need to thread an IdMap through to here because
1334 // the IDs generated aren't going to be emitted anywhere.
1335 let mut ids = IdMap::new();
1336 let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids, HeadingOffset::H1));
1339 if let Event::Start(Tag::Link(kind, dest, _)) = ev.0 {
1340 debug!("found link: {}", dest);
1341 let span = span_for_link(&dest, ev.1);
1342 links.borrow_mut().push(MarkdownLink { kind, link: dest.into_string(), range: span });
1350 crate struct RustCodeBlock {
1351 /// The range in the markdown that the code block occupies. Note that this includes the fences
1352 /// for fenced code blocks.
1353 crate range: Range<usize>,
1354 /// The range in the markdown that the code within the code block occupies.
1355 crate code: Range<usize>,
1356 crate is_fenced: bool,
1357 crate lang_string: LangString,
1360 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
1361 /// untagged (and assumed to be rust).
1362 crate fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_>) -> Vec<RustCodeBlock> {
1363 let mut code_blocks = vec![];
1369 let mut p = Parser::new_ext(md, main_body_opts()).into_offset_iter();
1371 while let Some((event, offset)) = p.next() {
1372 if let Event::Start(Tag::CodeBlock(syntax)) = event {
1373 let (lang_string, code_start, code_end, range, is_fenced) = match syntax {
1374 CodeBlockKind::Fenced(syntax) => {
1375 let syntax = syntax.as_ref();
1376 let lang_string = if syntax.is_empty() {
1379 LangString::parse(&*syntax, ErrorCodes::Yes, false, Some(extra_info))
1381 if !lang_string.rust {
1384 let (code_start, mut code_end) = match p.next() {
1385 Some((Event::Text(_), offset)) => (offset.start, offset.end),
1386 Some((_, sub_offset)) => {
1387 let code = Range { start: sub_offset.start, end: sub_offset.start };
1388 code_blocks.push(RustCodeBlock {
1397 let code = Range { start: offset.end, end: offset.end };
1398 code_blocks.push(RustCodeBlock {
1407 while let Some((Event::Text(_), offset)) = p.next() {
1408 code_end = offset.end;
1410 (lang_string, code_start, code_end, offset, true)
1412 CodeBlockKind::Indented => {
1413 // The ending of the offset goes too far sometime so we reduce it by one in
1415 if offset.end > offset.start && md.get(offset.end..=offset.end) == Some(&"\n") {
1417 LangString::default(),
1420 Range { start: offset.start, end: offset.end - 1 },
1424 (LangString::default(), offset.start, offset.end, offset, false)
1429 code_blocks.push(RustCodeBlock {
1432 code: Range { start: code_start, end: code_end },
1441 #[derive(Clone, Default, Debug)]
1443 map: FxHashMap<String, usize>,
1446 fn init_id_map() -> FxHashMap<String, usize> {
1447 let mut map = FxHashMap::default();
1448 // This is the list of IDs used in Javascript.
1449 map.insert("help".to_owned(), 1);
1450 // This is the list of IDs used in HTML generated in Rust (including the ones
1451 // used in tera template files).
1452 map.insert("mainThemeStyle".to_owned(), 1);
1453 map.insert("themeStyle".to_owned(), 1);
1454 map.insert("theme-picker".to_owned(), 1);
1455 map.insert("theme-choices".to_owned(), 1);
1456 map.insert("settings-menu".to_owned(), 1);
1457 map.insert("help-button".to_owned(), 1);
1458 map.insert("main".to_owned(), 1);
1459 map.insert("search".to_owned(), 1);
1460 map.insert("crate-search".to_owned(), 1);
1461 map.insert("render-detail".to_owned(), 1);
1462 map.insert("toggle-all-docs".to_owned(), 1);
1463 map.insert("all-types".to_owned(), 1);
1464 map.insert("default-settings".to_owned(), 1);
1465 map.insert("rustdoc-vars".to_owned(), 1);
1466 map.insert("sidebar-vars".to_owned(), 1);
1467 map.insert("copy-path".to_owned(), 1);
1468 map.insert("TOC".to_owned(), 1);
1469 // This is the list of IDs used by rustdoc sections (but still generated by
1471 map.insert("fields".to_owned(), 1);
1472 map.insert("variants".to_owned(), 1);
1473 map.insert("implementors-list".to_owned(), 1);
1474 map.insert("synthetic-implementors-list".to_owned(), 1);
1475 map.insert("foreign-impls".to_owned(), 1);
1476 map.insert("implementations".to_owned(), 1);
1477 map.insert("trait-implementations".to_owned(), 1);
1478 map.insert("synthetic-implementations".to_owned(), 1);
1479 map.insert("blanket-implementations".to_owned(), 1);
1480 map.insert("associated-types".to_owned(), 1);
1481 map.insert("associated-const".to_owned(), 1);
1482 map.insert("required-methods".to_owned(), 1);
1483 map.insert("provided-methods".to_owned(), 1);
1484 map.insert("implementors".to_owned(), 1);
1485 map.insert("synthetic-implementors".to_owned(), 1);
1486 map.insert("trait-implementations-list".to_owned(), 1);
1487 map.insert("synthetic-implementations-list".to_owned(), 1);
1488 map.insert("blanket-implementations-list".to_owned(), 1);
1489 map.insert("deref-methods".to_owned(), 1);
1494 pub fn new() -> Self {
1495 IdMap { map: init_id_map() }
1498 crate fn derive<S: AsRef<str> + ToString>(&mut self, candidate: S) -> String {
1499 let id = match self.map.get_mut(candidate.as_ref()) {
1500 None => candidate.to_string(),
1502 let id = format!("{}-{}", candidate.as_ref(), *a);
1508 self.map.insert(id.clone(), 1);