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::{IdMap, Markdown, ErrorCodes};
13 //! let s = "My *markdown* _text_";
14 //! let mut id_map = IdMap::new();
15 //! let md = Markdown(s, &[], &mut id_map, ErrorCodes::Yes, Edition::Edition2015, &None);
16 //! let html = md.into_string();
17 //! // ... something using html
20 use rustc_data_structures::fx::FxHashMap;
21 use rustc_hir::def_id::DefId;
23 use rustc_middle::ty::TyCtxt;
24 use rustc_span::edition::Edition;
28 use std::cell::RefCell;
29 use std::collections::VecDeque;
30 use std::default::Default;
32 use std::ops::{ControlFlow, Range};
35 use crate::clean::RenderedLink;
37 use crate::html::escape::Escape;
38 use crate::html::format::Buffer;
39 use crate::html::highlight;
40 use crate::html::length_limit::HtmlWithLimit;
41 use crate::html::toc::TocBuilder;
44 html, BrokenLink, CodeBlockKind, CowStr, Event, LinkType, Options, Parser, Tag,
50 /// Options for rendering Markdown in the main body of documentation.
51 pub(crate) fn main_body_opts() -> Options {
52 Options::ENABLE_TABLES
53 | Options::ENABLE_FOOTNOTES
54 | Options::ENABLE_STRIKETHROUGH
55 | Options::ENABLE_TASKLISTS
56 | Options::ENABLE_SMART_PUNCTUATION
59 /// Options for rendering Markdown in summaries (e.g., in search results).
60 pub(crate) fn summary_opts() -> Options {
61 Options::ENABLE_TABLES
62 | Options::ENABLE_FOOTNOTES
63 | Options::ENABLE_STRIKETHROUGH
64 | Options::ENABLE_TASKLISTS
65 | Options::ENABLE_SMART_PUNCTUATION
68 /// When `to_string` is called, this struct will emit the HTML corresponding to
69 /// the rendered version of the contained markdown string.
70 pub struct Markdown<'a>(
72 /// A list of link replacements.
73 pub &'a [RenderedLink],
74 /// The current list of used header IDs.
76 /// Whether to allow the use of explicit error codes in doctest lang strings.
78 /// Default edition to use when parsing doctests (to add a `fn main`).
80 pub &'a Option<Playground>,
82 /// A tuple struct like `Markdown` that renders the markdown with a table of contents.
83 crate struct MarkdownWithToc<'a>(
88 crate &'a Option<Playground>,
90 /// A tuple struct like `Markdown` that renders the markdown escaping HTML tags.
91 crate struct MarkdownHtml<'a>(
96 crate &'a Option<Playground>,
98 /// A tuple struct like `Markdown` that renders only the first paragraph.
99 crate struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [RenderedLink]);
101 #[derive(Copy, Clone, PartialEq, Debug)]
102 pub enum ErrorCodes {
108 crate fn from(b: bool) -> Self {
110 true => ErrorCodes::Yes,
111 false => ErrorCodes::No,
115 crate fn as_bool(self) -> bool {
117 ErrorCodes::Yes => true,
118 ErrorCodes::No => false,
123 /// Controls whether a line will be hidden or shown in HTML output.
125 /// All lines are used in documentation tests.
132 fn for_html(self) -> Option<Cow<'a, str>> {
134 Line::Shown(l) => Some(l),
135 Line::Hidden(_) => None,
139 fn for_code(self) -> Cow<'a, str> {
142 Line::Hidden(l) => Cow::Borrowed(l),
147 // FIXME: There is a minor inconsistency here. For lines that start with ##, we
148 // have no easy way of removing a potential single space after the hashes, which
149 // is done in the single # case. This inconsistency seems okay, if non-ideal. In
150 // order to fix it we'd have to iterate to find the first non-# character, and
151 // then reallocate to remove it; which would make us return a String.
152 fn map_line(s: &str) -> Line<'_> {
153 let trimmed = s.trim();
154 if trimmed.starts_with("##") {
155 Line::Shown(Cow::Owned(s.replacen("##", "#", 1)))
156 } else if let Some(stripped) = trimmed.strip_prefix("# ") {
158 Line::Hidden(&stripped)
159 } else if trimmed == "#" {
160 // We cannot handle '#text' because it could be #[attr].
163 Line::Shown(Cow::Borrowed(s))
167 /// Convert chars from a title for an id.
169 /// "Hello, world!" -> "hello-world"
170 fn slugify(c: char) -> Option<char> {
171 if c.is_alphanumeric() || c == '-' || c == '_' {
172 if c.is_ascii() { Some(c.to_ascii_lowercase()) } else { Some(c) }
173 } else if c.is_whitespace() && c.is_ascii() {
180 #[derive(Clone, Debug)]
181 pub struct Playground {
182 pub crate_name: Option<String>,
186 /// Adds syntax highlighting and playground Run buttons to Rust code blocks.
187 struct CodeBlocks<'p, 'a, I: Iterator<Item = Event<'a>>> {
189 check_error_codes: ErrorCodes,
191 // Information about the playground if a URL has been specified, containing an
192 // optional crate name and the URL.
193 playground: &'p Option<Playground>,
196 impl<'p, 'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'p, 'a, I> {
199 error_codes: ErrorCodes,
201 playground: &'p Option<Playground>,
203 CodeBlocks { inner: iter, check_error_codes: error_codes, edition, playground }
207 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
208 type Item = Event<'a>;
210 fn next(&mut self) -> Option<Self::Item> {
211 let event = self.inner.next();
216 let kind = if let Some(Event::Start(Tag::CodeBlock(kind))) = event {
222 let mut origtext = String::new();
223 for event in &mut self.inner {
225 Event::End(Tag::CodeBlock(..)) => break,
226 Event::Text(ref s) => {
227 origtext.push_str(s);
232 let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
233 let text = lines.collect::<Vec<Cow<'_, str>>>().join("\n");
235 let parse_result = match kind {
236 CodeBlockKind::Fenced(ref lang) => {
238 LangString::parse_without_check(&lang, self.check_error_codes, false);
239 if !parse_result.rust {
240 return Some(Event::Html(
242 "<div class=\"example-wrap\">\
243 <pre class=\"language-{}\"><code>{}</code></pre>\
253 CodeBlockKind::Indented => Default::default(),
256 compile_fail = parse_result.compile_fail;
257 should_panic = parse_result.should_panic;
258 ignore = parse_result.ignore;
259 edition = parse_result.edition;
261 let explicit_edition = edition.is_some();
262 let edition = edition.unwrap_or(self.edition);
264 let playground_button = self.playground.as_ref().and_then(|playground| {
265 let krate = &playground.crate_name;
266 let url = &playground.url;
272 .map(|l| map_line(l).for_code())
273 .collect::<Vec<Cow<'_, str>>>()
275 let krate = krate.as_ref().map(|s| &**s);
277 doctest::make_test(&test, krate, false, &Default::default(), edition, None);
278 let channel = if test.contains("#![feature(") { "&version=nightly" } else { "" };
280 let edition_string = format!("&edition={}", edition);
282 // These characters don't need to be escaped in a URI.
283 // FIXME: use a library function for percent encoding.
284 fn dont_escape(c: u8) -> bool {
285 (b'a' <= c && c <= b'z')
286 || (b'A' <= c && c <= b'Z')
287 || (b'0' <= c && c <= b'9')
298 let mut test_escaped = String::new();
299 for b in test.bytes() {
301 test_escaped.push(char::from(b));
303 write!(test_escaped, "%{:02X}", b).unwrap();
307 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}{}">Run</a>"#,
308 url, test_escaped, channel, edition_string
312 let tooltip = if ignore != Ignore::None {
313 Some((None, "ignore"))
314 } else if compile_fail {
315 Some((None, "compile_fail"))
316 } else if should_panic {
317 Some((None, "should_panic"))
318 } else if explicit_edition {
319 Some((Some(edition), "edition"))
324 // insert newline to clearly separate it from the
325 // previous block so we can shorten the html output
326 let mut s = Buffer::new();
328 highlight::render_with_highlighting(
332 "rust-example-rendered{}",
333 if let Some((_, class)) = tooltip { format!(" {}", class) } else { String::new() }
335 playground_button.as_deref(),
341 Some(Event::Html(s.into_inner().into()))
345 /// Make headings links with anchor IDs and build up TOC.
346 struct LinkReplacer<'a, I: Iterator<Item = Event<'a>>> {
348 links: &'a [RenderedLink],
349 shortcut_link: Option<&'a RenderedLink>,
352 impl<'a, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, I> {
353 fn new(iter: I, links: &'a [RenderedLink]) -> Self {
354 LinkReplacer { inner: iter, links, shortcut_link: None }
358 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
359 type Item = Event<'a>;
361 fn next(&mut self) -> Option<Self::Item> {
362 let mut event = self.inner.next();
364 // Replace intra-doc links and remove disambiguators from shortcut links (`[fn@f]`).
366 // This is a shortcut link that was resolved by the broken_link_callback: `[fn@f]`
367 // Remove any disambiguator.
368 Some(Event::Start(Tag::Link(
369 // [fn@f] or [fn@f][]
370 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
374 debug!("saw start of shortcut link to {} with title {}", dest, title);
375 // If this is a shortcut link, it was resolved by the broken_link_callback.
376 // So the URL will already be updated properly.
377 let link = self.links.iter().find(|&link| *link.href == **dest);
378 // Since this is an external iterator, we can't replace the inner text just yet.
379 // Store that we saw a link so we know to replace it later.
380 if let Some(link) = link {
381 trace!("it matched");
382 assert!(self.shortcut_link.is_none(), "shortcut links cannot be nested");
383 self.shortcut_link = Some(link);
386 // Now that we're done with the shortcut link, don't replace any more text.
387 Some(Event::End(Tag::Link(
388 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
392 debug!("saw end of shortcut link to {}", dest);
393 if self.links.iter().any(|link| *link.href == **dest) {
394 assert!(self.shortcut_link.is_some(), "saw closing link without opening tag");
395 self.shortcut_link = None;
398 // Handle backticks in inline code blocks, but only if we're in the middle of a shortcut link.
400 Some(Event::Code(text)) => {
401 trace!("saw code {}", text);
402 if let Some(link) = self.shortcut_link {
403 trace!("original text was {}", link.original_text);
404 // NOTE: this only replaces if the code block is the *entire* text.
405 // If only part of the link has code highlighting, the disambiguator will not be removed.
407 // This is a limitation from `collect_intra_doc_links`: it passes a full link,
408 // and does not distinguish at all between code blocks.
409 // So we could never be sure we weren't replacing too much:
410 // [fn@my_`f`unc] is treated the same as [my_func()] in that pass.
412 // NOTE: &[1..len() - 1] is to strip the backticks
413 if **text == link.original_text[1..link.original_text.len() - 1] {
414 debug!("replacing {} with {}", text, link.new_text);
415 *text = CowStr::Borrowed(&link.new_text);
419 // Replace plain text in links, but only in the middle of a shortcut link.
421 Some(Event::Text(text)) => {
422 trace!("saw text {}", text);
423 if let Some(link) = self.shortcut_link {
424 trace!("original text was {}", link.original_text);
425 // NOTE: same limitations as `Event::Code`
426 if **text == *link.original_text {
427 debug!("replacing {} with {}", text, link.new_text);
428 *text = CowStr::Borrowed(&link.new_text);
432 // If this is a link, but not a shortcut link,
433 // replace the URL, since the broken_link_callback was not called.
434 Some(Event::Start(Tag::Link(_, dest, _))) => {
435 if let Some(link) = self.links.iter().find(|&link| *link.original_text == **dest) {
436 *dest = CowStr::Borrowed(link.href.as_ref());
439 // Anything else couldn't have been a valid Rust path, so no need to replace the text.
443 // Yield the modified event
448 type SpannedEvent<'a> = (Event<'a>, Range<usize>);
450 /// Make headings links with anchor IDs and build up TOC.
451 struct HeadingLinks<'a, 'b, 'ids, I> {
453 toc: Option<&'b mut TocBuilder>,
454 buf: VecDeque<SpannedEvent<'a>>,
455 id_map: &'ids mut IdMap,
458 impl<'a, 'b, 'ids, I> HeadingLinks<'a, 'b, 'ids, I> {
459 fn new(iter: I, toc: Option<&'b mut TocBuilder>, ids: &'ids mut IdMap) -> Self {
460 HeadingLinks { inner: iter, toc, buf: VecDeque::new(), id_map: ids }
464 impl<'a, 'b, 'ids, I: Iterator<Item = SpannedEvent<'a>>> Iterator
465 for HeadingLinks<'a, 'b, 'ids, I>
467 type Item = SpannedEvent<'a>;
469 fn next(&mut self) -> Option<Self::Item> {
470 if let Some(e) = self.buf.pop_front() {
474 let event = self.inner.next();
475 if let Some((Event::Start(Tag::Heading(level)), _)) = event {
476 let mut id = String::new();
477 for event in &mut self.inner {
479 Event::End(Tag::Heading(..)) => break,
480 Event::Start(Tag::Link(_, _, _)) | Event::End(Tag::Link(..)) => {}
481 Event::Text(text) | Event::Code(text) => {
482 id.extend(text.chars().filter_map(slugify));
483 self.buf.push_back(event);
485 _ => self.buf.push_back(event),
488 let id = self.id_map.derive(id);
490 if let Some(ref mut builder) = self.toc {
491 let mut html_header = String::new();
492 html::push_html(&mut html_header, self.buf.iter().map(|(ev, _)| ev.clone()));
493 let sec = builder.push(level as u32, html_header, id.clone());
494 self.buf.push_front((Event::Html(format!("{} ", sec).into()), 0..0));
497 self.buf.push_back((Event::Html(format!("</a></h{}>", level).into()), 0..0));
499 let start_tags = format!(
500 "<h{level} id=\"{id}\" class=\"section-header\">\
505 return Some((Event::Html(start_tags.into()), 0..0));
511 /// Extracts just the first paragraph.
512 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
518 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
519 fn new(iter: I) -> Self {
520 SummaryLine { inner: iter, started: false, depth: 0 }
524 fn check_if_allowed_tag(t: &Tag<'_>) -> bool {
527 Tag::Paragraph | Tag::Item | Tag::Emphasis | Tag::Strong | Tag::Link(..) | Tag::BlockQuote
531 fn is_forbidden_tag(t: &Tag<'_>) -> bool {
532 matches!(t, Tag::CodeBlock(_) | Tag::Table(_) | Tag::TableHead | Tag::TableRow | Tag::TableCell)
535 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
536 type Item = Event<'a>;
538 fn next(&mut self) -> Option<Self::Item> {
539 if self.started && self.depth == 0 {
545 if let Some(event) = self.inner.next() {
546 let mut is_start = true;
547 let is_allowed_tag = match event {
548 Event::Start(ref c) => {
549 if is_forbidden_tag(c) {
553 check_if_allowed_tag(c)
555 Event::End(ref c) => {
556 if is_forbidden_tag(c) {
561 check_if_allowed_tag(c)
565 return if !is_allowed_tag {
567 Some(Event::Start(Tag::Paragraph))
569 Some(Event::End(Tag::Paragraph))
579 /// Moves all footnote definitions to the end and add back links to the
581 struct Footnotes<'a, I> {
583 footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
586 impl<'a, I> Footnotes<'a, I> {
587 fn new(iter: I) -> Self {
588 Footnotes { inner: iter, footnotes: FxHashMap::default() }
591 fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
592 let new_id = self.footnotes.keys().count() + 1;
593 let key = key.to_owned();
594 self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
598 impl<'a, I: Iterator<Item = SpannedEvent<'a>>> Iterator for Footnotes<'a, I> {
599 type Item = SpannedEvent<'a>;
601 fn next(&mut self) -> Option<Self::Item> {
603 match self.inner.next() {
604 Some((Event::FootnoteReference(ref reference), range)) => {
605 let entry = self.get_entry(&reference);
606 let reference = format!(
607 "<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}</a></sup>",
610 return Some((Event::Html(reference.into()), range));
612 Some((Event::Start(Tag::FootnoteDefinition(def)), _)) => {
613 let mut content = Vec::new();
614 for (event, _) in &mut self.inner {
615 if let Event::End(Tag::FootnoteDefinition(..)) = event {
620 let entry = self.get_entry(&def);
621 (*entry).0 = content;
623 Some(e) => return Some(e),
625 if !self.footnotes.is_empty() {
626 let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
627 v.sort_by(|a, b| a.1.cmp(&b.1));
628 let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
629 for (mut content, id) in v {
630 write!(ret, "<li id=\"fn{}\">", id).unwrap();
631 let mut is_paragraph = false;
632 if let Some(&Event::End(Tag::Paragraph)) = content.last() {
636 html::push_html(&mut ret, content.into_iter());
637 write!(ret, " <a href=\"#fnref{}\">↩</a>", id).unwrap();
639 ret.push_str("</p>");
641 ret.push_str("</li>");
643 ret.push_str("</ol></div>");
644 return Some((Event::Html(ret.into()), 0..0));
654 crate fn find_testable_code<T: doctest::Tester>(
657 error_codes: ErrorCodes,
658 enable_per_target_ignores: bool,
659 extra_info: Option<&ExtraInfo<'_>>,
661 let mut parser = Parser::new(doc).into_offset_iter();
662 let mut prev_offset = 0;
663 let mut nb_lines = 0;
664 let mut register_header = None;
665 while let Some((event, offset)) = parser.next() {
667 Event::Start(Tag::CodeBlock(kind)) => {
668 let block_info = match kind {
669 CodeBlockKind::Fenced(ref lang) => {
676 enable_per_target_ignores,
681 CodeBlockKind::Indented => Default::default(),
683 if !block_info.rust {
687 let mut test_s = String::new();
689 while let Some((Event::Text(s), _)) = parser.next() {
694 .map(|l| map_line(l).for_code())
695 .collect::<Vec<Cow<'_, str>>>()
698 nb_lines += doc[prev_offset..offset.start].lines().count();
699 let line = tests.get_line() + nb_lines + 1;
700 tests.add_test(text, block_info, line);
701 prev_offset = offset.start;
703 Event::Start(Tag::Heading(level)) => {
704 register_header = Some(level as u32);
706 Event::Text(ref s) if register_header.is_some() => {
707 let level = register_header.unwrap();
709 tests.register_header("", level);
711 tests.register_header(s, level);
713 register_header = None;
720 crate struct ExtraInfo<'tcx> {
731 impl<'tcx> ExtraInfo<'tcx> {
732 crate fn new(tcx: TyCtxt<'tcx>, hir_id: HirId, sp: Span) -> ExtraInfo<'tcx> {
733 ExtraInfo { id: ExtraInfoId::Hir(hir_id), sp, tcx }
736 crate fn new_did(tcx: TyCtxt<'tcx>, did: DefId, sp: Span) -> ExtraInfo<'tcx> {
737 ExtraInfo { id: ExtraInfoId::Def(did), sp, tcx }
740 fn error_invalid_codeblock_attr(&self, msg: &str, help: &str) {
741 let hir_id = match self.id {
742 ExtraInfoId::Hir(hir_id) => hir_id,
743 ExtraInfoId::Def(item_did) => {
744 match item_did.as_local() {
745 Some(item_did) => self.tcx.hir().local_def_id_to_hir_id(item_did),
747 // If non-local, no need to check anything.
753 self.tcx.struct_span_lint_hir(
754 crate::lint::INVALID_CODEBLOCK_ATTRIBUTES,
758 let mut diag = lint.build(msg);
766 #[derive(Eq, PartialEq, Clone, Debug)]
767 crate struct LangString {
769 crate should_panic: bool,
771 crate ignore: Ignore,
773 crate test_harness: bool,
774 crate compile_fail: bool,
775 crate error_codes: Vec<String>,
776 crate allow_fail: bool,
777 crate edition: Option<Edition>,
780 #[derive(Eq, PartialEq, Clone, Debug)]
787 impl Default for LangString {
788 fn default() -> Self {
790 original: String::new(),
793 ignore: Ignore::None,
797 error_codes: Vec::new(),
805 fn parse_without_check(
807 allow_error_code_check: ErrorCodes,
808 enable_per_target_ignores: bool,
810 Self::parse(string, allow_error_code_check, enable_per_target_ignores, None)
813 fn tokens(string: &str) -> impl Iterator<Item = &str> {
814 // Pandoc, which Rust once used for generating documentation,
815 // expects lang strings to be surrounded by `{}` and for each token
816 // to be proceeded by a `.`. Since some of these lang strings are still
817 // loose in the wild, we strip a pair of surrounding `{}` from the lang
818 // string and a leading `.` from each token.
820 let string = string.trim();
822 let first = string.chars().next();
823 let last = string.chars().last();
825 let string = if first == Some('{') && last == Some('}') {
826 &string[1..string.len() - 1]
832 .split(|c| c == ',' || c == ' ' || c == '\t')
834 .map(|token| if token.chars().next() == Some('.') { &token[1..] } else { token })
835 .filter(|token| !token.is_empty())
840 allow_error_code_check: ErrorCodes,
841 enable_per_target_ignores: bool,
842 extra: Option<&ExtraInfo<'_>>,
844 let allow_error_code_check = allow_error_code_check.as_bool();
845 let mut seen_rust_tags = false;
846 let mut seen_other_tags = false;
847 let mut data = LangString::default();
848 let mut ignores = vec![];
850 data.original = string.to_owned();
852 let tokens = Self::tokens(string).collect::<Vec<&str>>();
854 for token in tokens {
857 data.should_panic = true;
858 seen_rust_tags = !seen_other_tags;
862 seen_rust_tags = !seen_other_tags;
865 data.ignore = Ignore::All;
866 seen_rust_tags = !seen_other_tags;
868 x if x.starts_with("ignore-") => {
869 if enable_per_target_ignores {
870 ignores.push(x.trim_start_matches("ignore-").to_owned());
871 seen_rust_tags = !seen_other_tags;
875 data.allow_fail = true;
876 seen_rust_tags = !seen_other_tags;
880 seen_rust_tags = true;
883 data.test_harness = true;
884 seen_rust_tags = !seen_other_tags || seen_rust_tags;
887 data.compile_fail = true;
888 seen_rust_tags = !seen_other_tags || seen_rust_tags;
891 x if x.starts_with("edition") => {
892 data.edition = x[7..].parse::<Edition>().ok();
894 x if allow_error_code_check && x.starts_with('E') && x.len() == 5 => {
895 if x[1..].parse::<u32>().is_ok() {
896 data.error_codes.push(x.to_owned());
897 seen_rust_tags = !seen_other_tags || seen_rust_tags;
899 seen_other_tags = true;
902 x if extra.is_some() => {
903 let s = x.to_lowercase();
904 match if s == "compile-fail" || s == "compile_fail" || s == "compilefail" {
907 "the code block will either not be tested if not marked as a rust one \
908 or won't fail if it compiles successfully",
910 } else if s == "should-panic" || s == "should_panic" || s == "shouldpanic" {
913 "the code block will either not be tested if not marked as a rust one \
914 or won't fail if it doesn't panic when running",
916 } else if s == "no-run" || s == "no_run" || s == "norun" {
919 "the code block will either not be tested if not marked as a rust one \
920 or will be run (which you might not want)",
922 } else if s == "allow-fail" || s == "allow_fail" || s == "allowfail" {
925 "the code block will either not be tested if not marked as a rust one \
926 or will be run (which you might not want)",
928 } else if s == "test-harness" || s == "test_harness" || s == "testharness" {
931 "the code block will either not be tested if not marked as a rust one \
932 or the code will be wrapped inside a main function",
937 Some((flag, help)) => {
938 if let Some(ref extra) = extra {
939 extra.error_invalid_codeblock_attr(
940 &format!("unknown attribute `{}`. Did you mean `{}`?", x, flag),
947 seen_other_tags = true;
949 _ => seen_other_tags = true,
953 // ignore-foo overrides ignore
954 if !ignores.is_empty() {
955 data.ignore = Ignore::Some(ignores);
958 data.rust &= !seen_other_tags || seen_rust_tags;
965 pub fn into_string(self) -> String {
966 let Markdown(md, links, mut ids, codes, edition, playground) = self;
968 // This is actually common enough to special-case
970 return String::new();
972 let mut replacer = |broken_link: BrokenLink<'_>| {
974 links.iter().find(|link| &*link.original_text == broken_link.reference)
976 Some((link.href.as_str().into(), link.new_text.as_str().into()))
982 let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(&mut replacer));
983 let p = p.into_offset_iter();
985 let mut s = String::with_capacity(md.len() * 3 / 2);
987 let p = HeadingLinks::new(p, None, &mut ids);
988 let p = Footnotes::new(p);
989 let p = LinkReplacer::new(p.map(|(ev, _)| ev), links);
990 let p = CodeBlocks::new(p, codes, edition, playground);
991 html::push_html(&mut s, p);
997 impl MarkdownWithToc<'_> {
998 crate fn into_string(self) -> String {
999 let MarkdownWithToc(md, mut ids, codes, edition, playground) = self;
1001 let p = Parser::new_ext(md, main_body_opts()).into_offset_iter();
1003 let mut s = String::with_capacity(md.len() * 3 / 2);
1005 let mut toc = TocBuilder::new();
1008 let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
1009 let p = Footnotes::new(p);
1010 let p = CodeBlocks::new(p.map(|(ev, _)| ev), codes, edition, playground);
1011 html::push_html(&mut s, p);
1014 format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s)
1018 impl MarkdownHtml<'_> {
1019 crate fn into_string(self) -> String {
1020 let MarkdownHtml(md, mut ids, codes, edition, playground) = self;
1022 // This is actually common enough to special-case
1024 return String::new();
1026 let p = Parser::new_ext(md, main_body_opts()).into_offset_iter();
1028 // Treat inline HTML as plain text.
1029 let p = p.map(|event| match event.0 {
1030 Event::Html(text) => (Event::Text(text), event.1),
1034 let mut s = String::with_capacity(md.len() * 3 / 2);
1036 let p = HeadingLinks::new(p, None, &mut ids);
1037 let p = Footnotes::new(p);
1038 let p = CodeBlocks::new(p.map(|(ev, _)| ev), codes, edition, playground);
1039 html::push_html(&mut s, p);
1045 impl MarkdownSummaryLine<'_> {
1046 crate fn into_string(self) -> String {
1047 let MarkdownSummaryLine(md, links) = self;
1048 // This is actually common enough to special-case
1050 return String::new();
1053 let mut replacer = |broken_link: BrokenLink<'_>| {
1055 links.iter().find(|link| &*link.original_text == broken_link.reference)
1057 Some((link.href.as_str().into(), link.new_text.as_str().into()))
1063 let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1065 let mut s = String::new();
1067 html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
1073 /// Renders a subset of Markdown in the first paragraph of the provided Markdown.
1075 /// - *Italics*, **bold**, and `inline code` styles **are** rendered.
1076 /// - Headings and links are stripped (though the text *is* rendered).
1077 /// - HTML, code blocks, and everything else are ignored.
1079 /// Returns a tuple of the rendered HTML string and whether the output was shortened
1080 /// due to the provided `length_limit`.
1081 fn markdown_summary_with_limit(
1083 link_names: &[RenderedLink],
1084 length_limit: usize,
1085 ) -> (String, bool) {
1087 return (String::new(), false);
1090 let mut replacer = |broken_link: BrokenLink<'_>| {
1092 link_names.iter().find(|link| &*link.original_text == broken_link.reference)
1094 Some((link.href.as_str().into(), link.new_text.as_str().into()))
1100 let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1101 let mut p = LinkReplacer::new(p, link_names);
1103 let mut buf = HtmlWithLimit::new(length_limit);
1104 let mut stopped_early = false;
1105 p.try_for_each(|event| {
1107 Event::Text(text) => {
1109 text.split_inclusive(char::is_whitespace).try_for_each(|word| buf.push(word));
1111 stopped_early = true;
1115 Event::Code(code) => {
1116 buf.open_tag("code");
1117 let r = buf.push(code);
1119 stopped_early = true;
1125 Event::Start(tag) => match tag {
1126 Tag::Emphasis => buf.open_tag("em"),
1127 Tag::Strong => buf.open_tag("strong"),
1128 Tag::CodeBlock(..) => return ControlFlow::BREAK,
1131 Event::End(tag) => match tag {
1132 Tag::Emphasis | Tag::Strong => buf.close_tag(),
1133 Tag::Paragraph | Tag::Heading(..) => return ControlFlow::BREAK,
1136 Event::HardBreak | Event::SoftBreak => buf.push(" ")?,
1139 ControlFlow::CONTINUE
1142 (buf.finish(), stopped_early)
1145 /// Renders a shortened first paragraph of the given Markdown as a subset of Markdown,
1146 /// making it suitable for contexts like the search index.
1148 /// Will shorten to 59 or 60 characters, including an ellipsis (…) if it was shortened.
1150 /// See [`markdown_summary_with_limit`] for details about what is rendered and what is not.
1151 crate fn short_markdown_summary(markdown: &str, link_names: &[RenderedLink]) -> String {
1152 let (mut s, was_shortened) = markdown_summary_with_limit(markdown, link_names, 59);
1161 /// Renders the first paragraph of the provided markdown as plain text.
1162 /// Useful for alt-text.
1164 /// - Headings, links, and formatting are stripped.
1165 /// - Inline code is rendered as-is, surrounded by backticks.
1166 /// - HTML and code blocks are ignored.
1167 crate fn plain_text_summary(md: &str) -> String {
1169 return String::new();
1172 let mut s = String::with_capacity(md.len() * 3 / 2);
1174 for event in Parser::new_ext(md, summary_opts()) {
1176 Event::Text(text) => s.push_str(text),
1177 Event::Code(code) => {
1182 Event::HardBreak | Event::SoftBreak => s.push(' '),
1183 Event::Start(Tag::CodeBlock(..)) => break,
1184 Event::End(Tag::Paragraph) => break,
1185 Event::End(Tag::Heading(..)) => break,
1194 crate struct MarkdownLink {
1197 pub range: Range<usize>,
1200 crate fn markdown_links(md: &str) -> Vec<MarkdownLink> {
1205 let links = RefCell::new(vec![]);
1207 // FIXME: remove this function once pulldown_cmark can provide spans for link definitions.
1208 let locate = |s: &str, fallback: Range<usize>| unsafe {
1209 let s_start = s.as_ptr();
1210 let s_end = s_start.add(s.len());
1211 let md_start = md.as_ptr();
1212 let md_end = md_start.add(md.len());
1213 if md_start <= s_start && s_end <= md_end {
1214 let start = s_start.offset_from(md_start) as usize;
1215 let end = s_end.offset_from(md_start) as usize;
1222 let span_for_link = |link: &CowStr<'_>, span: Range<usize>| {
1223 // For diagnostics, we want to underline the link's definition but `span` will point at
1224 // where the link is used. This is a problem for reference-style links, where the definition
1225 // is separate from the usage.
1227 // `Borrowed` variant means the string (the link's destination) may come directly from
1228 // the markdown text and we can locate the original link destination.
1229 // NOTE: LinkReplacer also provides `Borrowed` but possibly from other sources,
1230 // so `locate()` can fall back to use `span`.
1231 CowStr::Borrowed(s) => locate(s, span),
1233 // For anything else, we can only use the provided range.
1234 CowStr::Boxed(_) | CowStr::Inlined(_) => span,
1238 let mut push = |link: BrokenLink<'_>| {
1239 let span = span_for_link(&CowStr::Borrowed(link.reference), link.span);
1240 links.borrow_mut().push(MarkdownLink {
1241 kind: LinkType::ShortcutUnknown,
1242 link: link.reference.to_owned(),
1247 let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(&mut push))
1248 .into_offset_iter();
1250 // There's no need to thread an IdMap through to here because
1251 // the IDs generated aren't going to be emitted anywhere.
1252 let mut ids = IdMap::new();
1253 let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids));
1256 if let Event::Start(Tag::Link(kind, dest, _)) = ev.0 {
1257 debug!("found link: {}", dest);
1258 let span = span_for_link(&dest, ev.1);
1259 links.borrow_mut().push(MarkdownLink { kind, link: dest.into_string(), range: span });
1267 crate struct RustCodeBlock {
1268 /// The range in the markdown that the code block occupies. Note that this includes the fences
1269 /// for fenced code blocks.
1270 crate range: Range<usize>,
1271 /// The range in the markdown that the code within the code block occupies.
1272 crate code: Range<usize>,
1273 crate is_fenced: bool,
1274 crate syntax: Option<String>,
1275 crate is_ignore: bool,
1278 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
1279 /// untagged (and assumed to be rust).
1280 crate fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_>) -> Vec<RustCodeBlock> {
1281 let mut code_blocks = vec![];
1287 let mut p = Parser::new_ext(md, main_body_opts()).into_offset_iter();
1289 while let Some((event, offset)) = p.next() {
1290 if let Event::Start(Tag::CodeBlock(syntax)) = event {
1291 let (syntax, code_start, code_end, range, is_fenced, is_ignore) = match syntax {
1292 CodeBlockKind::Fenced(syntax) => {
1293 let syntax = syntax.as_ref();
1294 let lang_string = if syntax.is_empty() {
1297 LangString::parse(&*syntax, ErrorCodes::Yes, false, Some(extra_info))
1299 if !lang_string.rust {
1302 let is_ignore = lang_string.ignore != Ignore::None;
1303 let syntax = if syntax.is_empty() { None } else { Some(syntax.to_owned()) };
1304 let (code_start, mut code_end) = match p.next() {
1305 Some((Event::Text(_), offset)) => (offset.start, offset.end),
1306 Some((_, sub_offset)) => {
1307 let code = Range { start: sub_offset.start, end: sub_offset.start };
1308 code_blocks.push(RustCodeBlock {
1318 let code = Range { start: offset.end, end: offset.end };
1319 code_blocks.push(RustCodeBlock {
1329 while let Some((Event::Text(_), offset)) = p.next() {
1330 code_end = offset.end;
1332 (syntax, code_start, code_end, offset, true, is_ignore)
1334 CodeBlockKind::Indented => {
1335 // The ending of the offset goes too far sometime so we reduce it by one in
1337 if offset.end > offset.start && md.get(offset.end..=offset.end) == Some(&"\n") {
1342 Range { start: offset.start, end: offset.end - 1 },
1347 (None, offset.start, offset.end, offset, false, false)
1352 code_blocks.push(RustCodeBlock {
1355 code: Range { start: code_start, end: code_end },
1365 #[derive(Clone, Default, Debug)]
1367 map: FxHashMap<String, usize>,
1370 fn init_id_map() -> FxHashMap<String, usize> {
1371 let mut map = FxHashMap::default();
1372 // This is the list of IDs used in Javascript.
1373 map.insert("help".to_owned(), 1);
1374 // This is the list of IDs used in HTML generated in Rust (including the ones
1375 // used in tera template files).
1376 map.insert("mainThemeStyle".to_owned(), 1);
1377 map.insert("themeStyle".to_owned(), 1);
1378 map.insert("theme-picker".to_owned(), 1);
1379 map.insert("theme-choices".to_owned(), 1);
1380 map.insert("settings-menu".to_owned(), 1);
1381 map.insert("help-button".to_owned(), 1);
1382 map.insert("main".to_owned(), 1);
1383 map.insert("search".to_owned(), 1);
1384 map.insert("crate-search".to_owned(), 1);
1385 map.insert("render-detail".to_owned(), 1);
1386 map.insert("toggle-all-docs".to_owned(), 1);
1387 map.insert("all-types".to_owned(), 1);
1388 map.insert("default-settings".to_owned(), 1);
1389 map.insert("rustdoc-vars".to_owned(), 1);
1390 map.insert("sidebar-vars".to_owned(), 1);
1391 map.insert("copy-path".to_owned(), 1);
1392 map.insert("TOC".to_owned(), 1);
1393 // This is the list of IDs used by rustdoc sections (but still generated by
1395 map.insert("fields".to_owned(), 1);
1396 map.insert("variants".to_owned(), 1);
1397 map.insert("implementors-list".to_owned(), 1);
1398 map.insert("synthetic-implementors-list".to_owned(), 1);
1399 map.insert("foreign-impls".to_owned(), 1);
1400 map.insert("implementations".to_owned(), 1);
1401 map.insert("trait-implementations".to_owned(), 1);
1402 map.insert("synthetic-implementations".to_owned(), 1);
1403 map.insert("blanket-implementations".to_owned(), 1);
1404 map.insert("associated-types".to_owned(), 1);
1405 map.insert("associated-const".to_owned(), 1);
1406 map.insert("required-methods".to_owned(), 1);
1407 map.insert("provided-methods".to_owned(), 1);
1408 map.insert("implementors".to_owned(), 1);
1409 map.insert("synthetic-implementors".to_owned(), 1);
1410 map.insert("trait-implementations-list".to_owned(), 1);
1411 map.insert("synthetic-implementations-list".to_owned(), 1);
1412 map.insert("blanket-implementations-list".to_owned(), 1);
1413 map.insert("deref-methods".to_owned(), 1);
1418 pub fn new() -> Self {
1419 IdMap { map: init_id_map() }
1422 crate fn derive<S: AsRef<str> + ToString>(&mut self, candidate: S) -> String {
1423 let id = match self.map.get_mut(candidate.as_ref()) {
1424 None => candidate.to_string(),
1426 let id = format!("{}-{}", candidate.as_ref(), *a);
1432 self.map.insert(id.clone(), 1);