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;
27 use std::cell::RefCell;
28 use std::collections::VecDeque;
29 use std::default::Default;
34 use crate::clean::RenderedLink;
36 use crate::html::escape::Escape;
37 use crate::html::highlight;
38 use crate::html::toc::TocBuilder;
41 html, BrokenLink, CodeBlockKind, CowStr, Event, LinkType, Options, Parser, Tag,
44 use super::format::Buffer;
49 /// Options for rendering Markdown in the main body of documentation.
50 pub(crate) fn opts() -> Options {
51 Options::ENABLE_TABLES
52 | Options::ENABLE_FOOTNOTES
53 | Options::ENABLE_STRIKETHROUGH
54 | Options::ENABLE_TASKLISTS
55 | Options::ENABLE_SMART_PUNCTUATION
58 /// A subset of [`opts()`] used for rendering summaries.
59 pub(crate) fn summary_opts() -> Options {
60 Options::ENABLE_STRIKETHROUGH | Options::ENABLE_SMART_PUNCTUATION | Options::ENABLE_TABLES
63 /// When `to_string` is called, this struct will emit the HTML corresponding to
64 /// the rendered version of the contained markdown string.
65 pub struct Markdown<'a>(
67 /// A list of link replacements.
68 pub &'a [RenderedLink],
69 /// The current list of used header IDs.
71 /// Whether to allow the use of explicit error codes in doctest lang strings.
73 /// Default edition to use when parsing doctests (to add a `fn main`).
75 pub &'a Option<Playground>,
77 /// A tuple struct like `Markdown` that renders the markdown with a table of contents.
78 crate struct MarkdownWithToc<'a>(
83 crate &'a Option<Playground>,
85 /// A tuple struct like `Markdown` that renders the markdown escaping HTML tags.
86 crate struct MarkdownHtml<'a>(
91 crate &'a Option<Playground>,
93 /// A tuple struct like `Markdown` that renders only the first paragraph.
94 crate struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [RenderedLink]);
96 #[derive(Copy, Clone, PartialEq, Debug)]
103 crate fn from(b: bool) -> Self {
105 true => ErrorCodes::Yes,
106 false => ErrorCodes::No,
110 crate fn as_bool(self) -> bool {
112 ErrorCodes::Yes => true,
113 ErrorCodes::No => false,
118 /// Controls whether a line will be hidden or shown in HTML output.
120 /// All lines are used in documentation tests.
127 fn for_html(self) -> Option<Cow<'a, str>> {
129 Line::Shown(l) => Some(l),
130 Line::Hidden(_) => None,
134 fn for_code(self) -> Cow<'a, str> {
137 Line::Hidden(l) => Cow::Borrowed(l),
142 // FIXME: There is a minor inconsistency here. For lines that start with ##, we
143 // have no easy way of removing a potential single space after the hashes, which
144 // is done in the single # case. This inconsistency seems okay, if non-ideal. In
145 // order to fix it we'd have to iterate to find the first non-# character, and
146 // then reallocate to remove it; which would make us return a String.
147 fn map_line(s: &str) -> Line<'_> {
148 let trimmed = s.trim();
149 if trimmed.starts_with("##") {
150 Line::Shown(Cow::Owned(s.replacen("##", "#", 1)))
151 } else if let Some(stripped) = trimmed.strip_prefix("# ") {
153 Line::Hidden(&stripped)
154 } else if trimmed == "#" {
155 // We cannot handle '#text' because it could be #[attr].
158 Line::Shown(Cow::Borrowed(s))
162 /// Convert chars from a title for an id.
164 /// "Hello, world!" -> "hello-world"
165 fn slugify(c: char) -> Option<char> {
166 if c.is_alphanumeric() || c == '-' || c == '_' {
167 if c.is_ascii() { Some(c.to_ascii_lowercase()) } else { Some(c) }
168 } else if c.is_whitespace() && c.is_ascii() {
175 #[derive(Clone, Debug)]
176 pub struct Playground {
177 pub crate_name: Option<String>,
181 /// Adds syntax highlighting and playground Run buttons to Rust code blocks.
182 struct CodeBlocks<'p, 'a, I: Iterator<Item = Event<'a>>> {
184 check_error_codes: ErrorCodes,
186 // Information about the playground if a URL has been specified, containing an
187 // optional crate name and the URL.
188 playground: &'p Option<Playground>,
191 impl<'p, 'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'p, 'a, I> {
194 error_codes: ErrorCodes,
196 playground: &'p Option<Playground>,
198 CodeBlocks { inner: iter, check_error_codes: error_codes, edition, playground }
202 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
203 type Item = Event<'a>;
205 fn next(&mut self) -> Option<Self::Item> {
206 let event = self.inner.next();
211 let kind = if let Some(Event::Start(Tag::CodeBlock(kind))) = event {
217 let mut origtext = String::new();
218 for event in &mut self.inner {
220 Event::End(Tag::CodeBlock(..)) => break,
221 Event::Text(ref s) => {
222 origtext.push_str(s);
227 let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
228 let text = lines.collect::<Vec<Cow<'_, str>>>().join("\n");
230 let parse_result = match kind {
231 CodeBlockKind::Fenced(ref lang) => {
233 LangString::parse_without_check(&lang, self.check_error_codes, false);
234 if !parse_result.rust {
235 return Some(Event::Html(
237 "<div class=\"example-wrap\">\
240 format!(" class=\"language-{}\"", lang),
248 CodeBlockKind::Indented => Default::default(),
251 compile_fail = parse_result.compile_fail;
252 should_panic = parse_result.should_panic;
253 ignore = parse_result.ignore;
254 edition = parse_result.edition;
256 let explicit_edition = edition.is_some();
257 let edition = edition.unwrap_or(self.edition);
259 let playground_button = self.playground.as_ref().and_then(|playground| {
260 let krate = &playground.crate_name;
261 let url = &playground.url;
267 .map(|l| map_line(l).for_code())
268 .collect::<Vec<Cow<'_, str>>>()
270 let krate = krate.as_ref().map(|s| &**s);
272 doctest::make_test(&test, krate, false, &Default::default(), edition, None);
273 let channel = if test.contains("#![feature(") { "&version=nightly" } else { "" };
275 let edition_string = format!("&edition={}", edition);
277 // These characters don't need to be escaped in a URI.
278 // FIXME: use a library function for percent encoding.
279 fn dont_escape(c: u8) -> bool {
280 (b'a' <= c && c <= b'z')
281 || (b'A' <= c && c <= b'Z')
282 || (b'0' <= c && c <= b'9')
293 let mut test_escaped = String::new();
294 for b in test.bytes() {
296 test_escaped.push(char::from(b));
298 write!(test_escaped, "%{:02X}", b).unwrap();
302 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}{}">Run</a>"#,
303 url, test_escaped, channel, edition_string
307 let tooltip = if ignore != Ignore::None {
308 Some((None, "ignore"))
309 } else if compile_fail {
310 Some((None, "compile_fail"))
311 } else if should_panic {
312 Some((None, "should_panic"))
313 } else if explicit_edition {
314 Some((Some(edition), "edition"))
319 // insert newline to clearly separate it from the
320 // previous block so we can shorten the html output
321 let mut s = Buffer::new();
323 highlight::render_with_highlighting(
327 "rust-example-rendered{}",
328 if let Some((_, class)) = tooltip { format!(" {}", class) } else { String::new() }
330 playground_button.as_deref(),
335 Some(Event::Html(s.into_inner().into()))
339 /// Make headings links with anchor IDs and build up TOC.
340 struct LinkReplacer<'a, I: Iterator<Item = Event<'a>>> {
342 links: &'a [RenderedLink],
343 shortcut_link: Option<&'a RenderedLink>,
346 impl<'a, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, I> {
347 fn new(iter: I, links: &'a [RenderedLink]) -> Self {
348 LinkReplacer { inner: iter, links, shortcut_link: None }
352 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
353 type Item = Event<'a>;
355 fn next(&mut self) -> Option<Self::Item> {
356 let mut event = self.inner.next();
358 // Replace intra-doc links and remove disambiguators from shortcut links (`[fn@f]`).
360 // This is a shortcut link that was resolved by the broken_link_callback: `[fn@f]`
361 // Remove any disambiguator.
362 Some(Event::Start(Tag::Link(
363 // [fn@f] or [fn@f][]
364 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
368 debug!("saw start of shortcut link to {} with title {}", dest, title);
369 // If this is a shortcut link, it was resolved by the broken_link_callback.
370 // So the URL will already be updated properly.
371 let link = self.links.iter().find(|&link| *link.href == **dest);
372 // Since this is an external iterator, we can't replace the inner text just yet.
373 // Store that we saw a link so we know to replace it later.
374 if let Some(link) = link {
375 trace!("it matched");
376 assert!(self.shortcut_link.is_none(), "shortcut links cannot be nested");
377 self.shortcut_link = Some(link);
380 // Now that we're done with the shortcut link, don't replace any more text.
381 Some(Event::End(Tag::Link(
382 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
386 debug!("saw end of shortcut link to {}", dest);
387 if self.links.iter().any(|link| *link.href == **dest) {
388 assert!(self.shortcut_link.is_some(), "saw closing link without opening tag");
389 self.shortcut_link = None;
392 // Handle backticks in inline code blocks, but only if we're in the middle of a shortcut link.
394 Some(Event::Code(text)) => {
395 trace!("saw code {}", text);
396 if let Some(link) = self.shortcut_link {
397 trace!("original text was {}", link.original_text);
398 // NOTE: this only replaces if the code block is the *entire* text.
399 // If only part of the link has code highlighting, the disambiguator will not be removed.
401 // This is a limitation from `collect_intra_doc_links`: it passes a full link,
402 // and does not distinguish at all between code blocks.
403 // So we could never be sure we weren't replacing too much:
404 // [fn@my_`f`unc] is treated the same as [my_func()] in that pass.
406 // NOTE: &[1..len() - 1] is to strip the backticks
407 if **text == link.original_text[1..link.original_text.len() - 1] {
408 debug!("replacing {} with {}", text, link.new_text);
409 *text = CowStr::Borrowed(&link.new_text);
413 // Replace plain text in links, but only in the middle of a shortcut link.
415 Some(Event::Text(text)) => {
416 trace!("saw text {}", text);
417 if let Some(link) = self.shortcut_link {
418 trace!("original text was {}", link.original_text);
419 // NOTE: same limitations as `Event::Code`
420 if **text == *link.original_text {
421 debug!("replacing {} with {}", text, link.new_text);
422 *text = CowStr::Borrowed(&link.new_text);
426 // If this is a link, but not a shortcut link,
427 // replace the URL, since the broken_link_callback was not called.
428 Some(Event::Start(Tag::Link(_, dest, _))) => {
429 if let Some(link) = self.links.iter().find(|&link| *link.original_text == **dest) {
430 *dest = CowStr::Borrowed(link.href.as_ref());
433 // Anything else couldn't have been a valid Rust path, so no need to replace the text.
437 // Yield the modified event
442 type SpannedEvent<'a> = (Event<'a>, Range<usize>);
444 /// Make headings links with anchor IDs and build up TOC.
445 struct HeadingLinks<'a, 'b, 'ids, I> {
447 toc: Option<&'b mut TocBuilder>,
448 buf: VecDeque<SpannedEvent<'a>>,
449 id_map: &'ids mut IdMap,
452 impl<'a, 'b, 'ids, I> HeadingLinks<'a, 'b, 'ids, I> {
453 fn new(iter: I, toc: Option<&'b mut TocBuilder>, ids: &'ids mut IdMap) -> Self {
454 HeadingLinks { inner: iter, toc, buf: VecDeque::new(), id_map: ids }
458 impl<'a, 'b, 'ids, I: Iterator<Item = SpannedEvent<'a>>> Iterator
459 for HeadingLinks<'a, 'b, 'ids, I>
461 type Item = SpannedEvent<'a>;
463 fn next(&mut self) -> Option<Self::Item> {
464 if let Some(e) = self.buf.pop_front() {
468 let event = self.inner.next();
469 if let Some((Event::Start(Tag::Heading(level)), _)) = event {
470 let mut id = String::new();
471 for event in &mut self.inner {
473 Event::End(Tag::Heading(..)) => break,
474 Event::Start(Tag::Link(_, _, _)) | Event::End(Tag::Link(..)) => {}
475 Event::Text(text) | Event::Code(text) => {
476 id.extend(text.chars().filter_map(slugify));
477 self.buf.push_back(event);
479 _ => self.buf.push_back(event),
482 let id = self.id_map.derive(id);
484 if let Some(ref mut builder) = self.toc {
485 let mut html_header = String::new();
486 html::push_html(&mut html_header, self.buf.iter().map(|(ev, _)| ev.clone()));
487 let sec = builder.push(level as u32, html_header, id.clone());
488 self.buf.push_front((Event::Html(format!("{} ", sec).into()), 0..0));
491 self.buf.push_back((Event::Html(format!("</a></h{}>", level).into()), 0..0));
493 let start_tags = format!(
494 "<h{level} id=\"{id}\" class=\"section-header\">\
499 return Some((Event::Html(start_tags.into()), 0..0));
505 /// Extracts just the first paragraph.
506 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
512 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
513 fn new(iter: I) -> Self {
514 SummaryLine { inner: iter, started: false, depth: 0 }
518 fn check_if_allowed_tag(t: &Tag<'_>) -> bool {
521 Tag::Paragraph | Tag::Item | Tag::Emphasis | Tag::Strong | Tag::Link(..) | Tag::BlockQuote
525 fn is_forbidden_tag(t: &Tag<'_>) -> bool {
526 matches!(t, Tag::CodeBlock(_) | Tag::Table(_) | Tag::TableHead | Tag::TableRow | Tag::TableCell)
529 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
530 type Item = Event<'a>;
532 fn next(&mut self) -> Option<Self::Item> {
533 if self.started && self.depth == 0 {
539 if let Some(event) = self.inner.next() {
540 let mut is_start = true;
541 let is_allowed_tag = match event {
542 Event::Start(ref c) => {
543 if is_forbidden_tag(c) {
547 check_if_allowed_tag(c)
549 Event::End(ref c) => {
550 if is_forbidden_tag(c) {
555 check_if_allowed_tag(c)
559 return if !is_allowed_tag {
561 Some(Event::Start(Tag::Paragraph))
563 Some(Event::End(Tag::Paragraph))
573 /// Moves all footnote definitions to the end and add back links to the
575 struct Footnotes<'a, I> {
577 footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
580 impl<'a, I> Footnotes<'a, I> {
581 fn new(iter: I) -> Self {
582 Footnotes { inner: iter, footnotes: FxHashMap::default() }
585 fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
586 let new_id = self.footnotes.keys().count() + 1;
587 let key = key.to_owned();
588 self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
592 impl<'a, I: Iterator<Item = SpannedEvent<'a>>> Iterator for Footnotes<'a, I> {
593 type Item = SpannedEvent<'a>;
595 fn next(&mut self) -> Option<Self::Item> {
597 match self.inner.next() {
598 Some((Event::FootnoteReference(ref reference), range)) => {
599 let entry = self.get_entry(&reference);
600 let reference = format!(
601 "<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}</a></sup>",
604 return Some((Event::Html(reference.into()), range));
606 Some((Event::Start(Tag::FootnoteDefinition(def)), _)) => {
607 let mut content = Vec::new();
608 for (event, _) in &mut self.inner {
609 if let Event::End(Tag::FootnoteDefinition(..)) = event {
614 let entry = self.get_entry(&def);
615 (*entry).0 = content;
617 Some(e) => return Some(e),
619 if !self.footnotes.is_empty() {
620 let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
621 v.sort_by(|a, b| a.1.cmp(&b.1));
622 let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
623 for (mut content, id) in v {
624 write!(ret, "<li id=\"fn{}\">", id).unwrap();
625 let mut is_paragraph = false;
626 if let Some(&Event::End(Tag::Paragraph)) = content.last() {
630 html::push_html(&mut ret, content.into_iter());
631 write!(ret, " <a href=\"#fnref{}\">↩</a>", id).unwrap();
633 ret.push_str("</p>");
635 ret.push_str("</li>");
637 ret.push_str("</ol></div>");
638 return Some((Event::Html(ret.into()), 0..0));
648 crate fn find_testable_code<T: doctest::Tester>(
651 error_codes: ErrorCodes,
652 enable_per_target_ignores: bool,
653 extra_info: Option<&ExtraInfo<'_>>,
655 let mut parser = Parser::new(doc).into_offset_iter();
656 let mut prev_offset = 0;
657 let mut nb_lines = 0;
658 let mut register_header = None;
659 while let Some((event, offset)) = parser.next() {
661 Event::Start(Tag::CodeBlock(kind)) => {
662 let block_info = match kind {
663 CodeBlockKind::Fenced(ref lang) => {
670 enable_per_target_ignores,
675 CodeBlockKind::Indented => Default::default(),
677 if !block_info.rust {
681 let mut test_s = String::new();
683 while let Some((Event::Text(s), _)) = parser.next() {
688 .map(|l| map_line(l).for_code())
689 .collect::<Vec<Cow<'_, str>>>()
692 nb_lines += doc[prev_offset..offset.start].lines().count();
693 let line = tests.get_line() + nb_lines + 1;
694 tests.add_test(text, block_info, line);
695 prev_offset = offset.start;
697 Event::Start(Tag::Heading(level)) => {
698 register_header = Some(level as u32);
700 Event::Text(ref s) if register_header.is_some() => {
701 let level = register_header.unwrap();
703 tests.register_header("", level);
705 tests.register_header(s, level);
707 register_header = None;
714 crate struct ExtraInfo<'tcx> {
725 impl<'tcx> ExtraInfo<'tcx> {
726 crate fn new(tcx: TyCtxt<'tcx>, hir_id: HirId, sp: Span) -> ExtraInfo<'tcx> {
727 ExtraInfo { id: ExtraInfoId::Hir(hir_id), sp, tcx }
730 crate fn new_did(tcx: TyCtxt<'tcx>, did: DefId, sp: Span) -> ExtraInfo<'tcx> {
731 ExtraInfo { id: ExtraInfoId::Def(did), sp, tcx }
734 fn error_invalid_codeblock_attr(&self, msg: &str, help: &str) {
735 let hir_id = match self.id {
736 ExtraInfoId::Hir(hir_id) => hir_id,
737 ExtraInfoId::Def(item_did) => {
738 match item_did.as_local() {
739 Some(item_did) => self.tcx.hir().local_def_id_to_hir_id(item_did),
741 // If non-local, no need to check anything.
747 self.tcx.struct_span_lint_hir(
748 crate::lint::INVALID_CODEBLOCK_ATTRIBUTES,
752 let mut diag = lint.build(msg);
760 #[derive(Eq, PartialEq, Clone, Debug)]
761 crate struct LangString {
763 crate should_panic: bool,
765 crate ignore: Ignore,
767 crate test_harness: bool,
768 crate compile_fail: bool,
769 crate error_codes: Vec<String>,
770 crate allow_fail: bool,
771 crate edition: Option<Edition>,
774 #[derive(Eq, PartialEq, Clone, Debug)]
781 impl Default for LangString {
782 fn default() -> Self {
784 original: String::new(),
787 ignore: Ignore::None,
791 error_codes: Vec::new(),
799 fn parse_without_check(
801 allow_error_code_check: ErrorCodes,
802 enable_per_target_ignores: bool,
804 Self::parse(string, allow_error_code_check, enable_per_target_ignores, None)
807 fn tokens(string: &str) -> impl Iterator<Item = &str> {
808 // Pandoc, which Rust once used for generating documentation,
809 // expects lang strings to be surrounded by `{}` and for each token
810 // to be proceeded by a `.`. Since some of these lang strings are still
811 // loose in the wild, we strip a pair of surrounding `{}` from the lang
812 // string and a leading `.` from each token.
814 let string = string.trim();
816 let first = string.chars().next();
817 let last = string.chars().last();
819 let string = if first == Some('{') && last == Some('}') {
820 &string[1..string.len() - 1]
826 .split(|c| c == ',' || c == ' ' || c == '\t')
828 .map(|token| if token.chars().next() == Some('.') { &token[1..] } else { token })
829 .filter(|token| !token.is_empty())
834 allow_error_code_check: ErrorCodes,
835 enable_per_target_ignores: bool,
836 extra: Option<&ExtraInfo<'_>>,
838 let allow_error_code_check = allow_error_code_check.as_bool();
839 let mut seen_rust_tags = false;
840 let mut seen_other_tags = false;
841 let mut data = LangString::default();
842 let mut ignores = vec![];
844 data.original = string.to_owned();
846 let tokens = Self::tokens(string).collect::<Vec<&str>>();
848 for token in tokens {
851 data.should_panic = true;
852 seen_rust_tags = !seen_other_tags;
856 seen_rust_tags = !seen_other_tags;
859 data.ignore = Ignore::All;
860 seen_rust_tags = !seen_other_tags;
862 x if x.starts_with("ignore-") => {
863 if enable_per_target_ignores {
864 ignores.push(x.trim_start_matches("ignore-").to_owned());
865 seen_rust_tags = !seen_other_tags;
869 data.allow_fail = true;
870 seen_rust_tags = !seen_other_tags;
874 seen_rust_tags = true;
877 data.test_harness = true;
878 seen_rust_tags = !seen_other_tags || seen_rust_tags;
881 data.compile_fail = true;
882 seen_rust_tags = !seen_other_tags || seen_rust_tags;
885 x if x.starts_with("edition") => {
886 data.edition = x[7..].parse::<Edition>().ok();
888 x if allow_error_code_check && x.starts_with('E') && x.len() == 5 => {
889 if x[1..].parse::<u32>().is_ok() {
890 data.error_codes.push(x.to_owned());
891 seen_rust_tags = !seen_other_tags || seen_rust_tags;
893 seen_other_tags = true;
896 x if extra.is_some() => {
897 let s = x.to_lowercase();
898 match if s == "compile-fail" || s == "compile_fail" || s == "compilefail" {
901 "the code block will either not be tested if not marked as a rust one \
902 or won't fail if it compiles successfully",
904 } else if s == "should-panic" || s == "should_panic" || s == "shouldpanic" {
907 "the code block will either not be tested if not marked as a rust one \
908 or won't fail if it doesn't panic when running",
910 } else if s == "no-run" || s == "no_run" || s == "norun" {
913 "the code block will either not be tested if not marked as a rust one \
914 or will be run (which you might not want)",
916 } else if s == "allow-fail" || s == "allow_fail" || s == "allowfail" {
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 == "test-harness" || s == "test_harness" || s == "testharness" {
925 "the code block will either not be tested if not marked as a rust one \
926 or the code will be wrapped inside a main function",
931 Some((flag, help)) => {
932 if let Some(ref extra) = extra {
933 extra.error_invalid_codeblock_attr(
934 &format!("unknown attribute `{}`. Did you mean `{}`?", x, flag),
941 seen_other_tags = true;
943 _ => seen_other_tags = true,
947 // ignore-foo overrides ignore
948 if !ignores.is_empty() {
949 data.ignore = Ignore::Some(ignores);
952 data.rust &= !seen_other_tags || seen_rust_tags;
959 pub fn into_string(self) -> String {
960 let Markdown(md, links, mut ids, codes, edition, playground) = self;
962 // This is actually common enough to special-case
964 return String::new();
966 let mut replacer = |broken_link: BrokenLink<'_>| {
968 links.iter().find(|link| &*link.original_text == broken_link.reference)
970 Some((link.href.as_str().into(), link.new_text.as_str().into()))
976 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut replacer));
977 let p = p.into_offset_iter();
979 let mut s = String::with_capacity(md.len() * 3 / 2);
981 let p = HeadingLinks::new(p, None, &mut ids);
982 let p = Footnotes::new(p);
983 let p = LinkReplacer::new(p.map(|(ev, _)| ev), links);
984 let p = CodeBlocks::new(p, codes, edition, playground);
985 html::push_html(&mut s, p);
991 impl MarkdownWithToc<'_> {
992 crate fn into_string(self) -> String {
993 let MarkdownWithToc(md, mut ids, codes, edition, playground) = self;
995 let p = Parser::new_ext(md, opts()).into_offset_iter();
997 let mut s = String::with_capacity(md.len() * 3 / 2);
999 let mut toc = TocBuilder::new();
1002 let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
1003 let p = Footnotes::new(p);
1004 let p = CodeBlocks::new(p.map(|(ev, _)| ev), codes, edition, playground);
1005 html::push_html(&mut s, p);
1008 format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s)
1012 impl MarkdownHtml<'_> {
1013 crate fn into_string(self) -> String {
1014 let MarkdownHtml(md, mut ids, codes, edition, playground) = self;
1016 // This is actually common enough to special-case
1018 return String::new();
1020 let p = Parser::new_ext(md, opts()).into_offset_iter();
1022 // Treat inline HTML as plain text.
1023 let p = p.map(|event| match event.0 {
1024 Event::Html(text) => (Event::Text(text), event.1),
1028 let mut s = String::with_capacity(md.len() * 3 / 2);
1030 let p = HeadingLinks::new(p, None, &mut ids);
1031 let p = Footnotes::new(p);
1032 let p = CodeBlocks::new(p.map(|(ev, _)| ev), codes, edition, playground);
1033 html::push_html(&mut s, p);
1039 impl MarkdownSummaryLine<'_> {
1040 crate fn into_string(self) -> String {
1041 let MarkdownSummaryLine(md, links) = self;
1042 // This is actually common enough to special-case
1044 return String::new();
1047 let mut replacer = |broken_link: BrokenLink<'_>| {
1049 links.iter().find(|link| &*link.original_text == broken_link.reference)
1051 Some((link.href.as_str().into(), link.new_text.as_str().into()))
1057 let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1059 let mut s = String::new();
1061 html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
1067 /// Renders a subset of Markdown in the first paragraph of the provided Markdown.
1069 /// - *Italics*, **bold**, and `inline code` styles **are** rendered.
1070 /// - Headings and links are stripped (though the text *is* rendered).
1071 /// - HTML, code blocks, and everything else are ignored.
1073 /// Returns a tuple of the rendered HTML string and whether the output was shortened
1074 /// due to the provided `length_limit`.
1075 fn markdown_summary_with_limit(
1077 link_names: &[RenderedLink],
1078 length_limit: usize,
1079 ) -> (String, bool) {
1081 return (String::new(), false);
1084 let mut s = String::with_capacity(md.len() * 3 / 2);
1085 let mut text_length = 0;
1086 let mut stopped_early = false;
1088 fn push(s: &mut String, text_length: &mut usize, text: &str) {
1090 *text_length += text.len();
1093 let mut replacer = |broken_link: BrokenLink<'_>| {
1095 link_names.iter().find(|link| &*link.original_text == broken_link.reference)
1097 Some((link.href.as_str().into(), link.new_text.as_str().into()))
1103 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut replacer));
1104 let p = LinkReplacer::new(p, link_names);
1106 'outer: for event in p {
1108 Event::Text(text) => {
1109 for word in text.split_inclusive(char::is_whitespace) {
1110 if text_length + word.len() >= length_limit {
1111 stopped_early = true;
1115 push(&mut s, &mut text_length, word);
1118 Event::Code(code) => {
1119 if text_length + code.len() >= length_limit {
1120 stopped_early = true;
1124 s.push_str("<code>");
1125 push(&mut s, &mut text_length, code);
1126 s.push_str("</code>");
1128 Event::Start(tag) => match tag {
1129 Tag::Emphasis => s.push_str("<em>"),
1130 Tag::Strong => s.push_str("<strong>"),
1131 Tag::CodeBlock(..) => break,
1134 Event::End(tag) => match tag {
1135 Tag::Emphasis => s.push_str("</em>"),
1136 Tag::Strong => s.push_str("</strong>"),
1137 Tag::Paragraph => break,
1138 Tag::Heading(..) => break,
1141 Event::HardBreak | Event::SoftBreak => {
1142 if text_length + 1 >= length_limit {
1143 stopped_early = true;
1147 push(&mut s, &mut text_length, " ");
1156 /// Renders a shortened first paragraph of the given Markdown as a subset of Markdown,
1157 /// making it suitable for contexts like the search index.
1159 /// Will shorten to 59 or 60 characters, including an ellipsis (…) if it was shortened.
1161 /// See [`markdown_summary_with_limit`] for details about what is rendered and what is not.
1162 crate fn short_markdown_summary(markdown: &str, link_names: &[RenderedLink]) -> String {
1163 let (mut s, was_shortened) = markdown_summary_with_limit(markdown, link_names, 59);
1172 /// Renders the first paragraph of the provided markdown as plain text.
1173 /// Useful for alt-text.
1175 /// - Headings, links, and formatting are stripped.
1176 /// - Inline code is rendered as-is, surrounded by backticks.
1177 /// - HTML and code blocks are ignored.
1178 crate fn plain_text_summary(md: &str) -> String {
1180 return String::new();
1183 let mut s = String::with_capacity(md.len() * 3 / 2);
1185 for event in Parser::new_ext(md, summary_opts()) {
1187 Event::Text(text) => s.push_str(text),
1188 Event::Code(code) => {
1193 Event::HardBreak | Event::SoftBreak => s.push(' '),
1194 Event::Start(Tag::CodeBlock(..)) => break,
1195 Event::End(Tag::Paragraph) => break,
1196 Event::End(Tag::Heading(..)) => break,
1205 crate struct MarkdownLink {
1208 pub range: Range<usize>,
1211 crate fn markdown_links(md: &str) -> Vec<MarkdownLink> {
1216 let links = RefCell::new(vec![]);
1218 // FIXME: remove this function once pulldown_cmark can provide spans for link definitions.
1219 let locate = |s: &str, fallback: Range<usize>| unsafe {
1220 let s_start = s.as_ptr();
1221 let s_end = s_start.add(s.len());
1222 let md_start = md.as_ptr();
1223 let md_end = md_start.add(md.len());
1224 if md_start <= s_start && s_end <= md_end {
1225 let start = s_start.offset_from(md_start) as usize;
1226 let end = s_end.offset_from(md_start) as usize;
1233 let span_for_link = |link: &CowStr<'_>, span: Range<usize>| {
1234 // For diagnostics, we want to underline the link's definition but `span` will point at
1235 // where the link is used. This is a problem for reference-style links, where the definition
1236 // is separate from the usage.
1238 // `Borrowed` variant means the string (the link's destination) may come directly from
1239 // the markdown text and we can locate the original link destination.
1240 // NOTE: LinkReplacer also provides `Borrowed` but possibly from other sources,
1241 // so `locate()` can fall back to use `span`.
1242 CowStr::Borrowed(s) => locate(s, span),
1244 // For anything else, we can only use the provided range.
1245 CowStr::Boxed(_) | CowStr::Inlined(_) => span,
1249 let mut push = |link: BrokenLink<'_>| {
1250 let span = span_for_link(&CowStr::Borrowed(link.reference), link.span);
1251 links.borrow_mut().push(MarkdownLink {
1252 kind: LinkType::ShortcutUnknown,
1253 link: link.reference.to_owned(),
1258 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut push)).into_offset_iter();
1260 // There's no need to thread an IdMap through to here because
1261 // the IDs generated aren't going to be emitted anywhere.
1262 let mut ids = IdMap::new();
1263 let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids));
1266 if let Event::Start(Tag::Link(kind, dest, _)) = ev.0 {
1267 debug!("found link: {}", dest);
1268 let span = span_for_link(&dest, ev.1);
1269 links.borrow_mut().push(MarkdownLink { kind, link: dest.into_string(), range: span });
1277 crate struct RustCodeBlock {
1278 /// The range in the markdown that the code block occupies. Note that this includes the fences
1279 /// for fenced code blocks.
1280 crate range: Range<usize>,
1281 /// The range in the markdown that the code within the code block occupies.
1282 crate code: Range<usize>,
1283 crate is_fenced: bool,
1284 crate syntax: Option<String>,
1285 crate is_ignore: bool,
1288 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
1289 /// untagged (and assumed to be rust).
1290 crate fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_>) -> Vec<RustCodeBlock> {
1291 let mut code_blocks = vec![];
1297 let mut p = Parser::new_ext(md, opts()).into_offset_iter();
1299 while let Some((event, offset)) = p.next() {
1300 if let Event::Start(Tag::CodeBlock(syntax)) = event {
1301 let (syntax, code_start, code_end, range, is_fenced, is_ignore) = match syntax {
1302 CodeBlockKind::Fenced(syntax) => {
1303 let syntax = syntax.as_ref();
1304 let lang_string = if syntax.is_empty() {
1307 LangString::parse(&*syntax, ErrorCodes::Yes, false, Some(extra_info))
1309 if !lang_string.rust {
1312 let is_ignore = lang_string.ignore != Ignore::None;
1313 let syntax = if syntax.is_empty() { None } else { Some(syntax.to_owned()) };
1314 let (code_start, mut code_end) = match p.next() {
1315 Some((Event::Text(_), offset)) => (offset.start, offset.end),
1316 Some((_, sub_offset)) => {
1317 let code = Range { start: sub_offset.start, end: sub_offset.start };
1318 code_blocks.push(RustCodeBlock {
1328 let code = Range { start: offset.end, end: offset.end };
1329 code_blocks.push(RustCodeBlock {
1339 while let Some((Event::Text(_), offset)) = p.next() {
1340 code_end = offset.end;
1342 (syntax, code_start, code_end, offset, true, is_ignore)
1344 CodeBlockKind::Indented => {
1345 // The ending of the offset goes too far sometime so we reduce it by one in
1347 if offset.end > offset.start && md.get(offset.end..=offset.end) == Some(&"\n") {
1352 Range { start: offset.start, end: offset.end - 1 },
1357 (None, offset.start, offset.end, offset, false, false)
1362 code_blocks.push(RustCodeBlock {
1365 code: Range { start: code_start, end: code_end },
1375 #[derive(Clone, Default, Debug)]
1377 map: FxHashMap<String, usize>,
1380 fn init_id_map() -> FxHashMap<String, usize> {
1381 let mut map = FxHashMap::default();
1382 // This is the list of IDs used in Javascript.
1383 map.insert("help".to_owned(), 1);
1384 // This is the list of IDs used in HTML generated in Rust (including the ones
1385 // used in tera template files).
1386 map.insert("mainThemeStyle".to_owned(), 1);
1387 map.insert("themeStyle".to_owned(), 1);
1388 map.insert("theme-picker".to_owned(), 1);
1389 map.insert("theme-choices".to_owned(), 1);
1390 map.insert("settings-menu".to_owned(), 1);
1391 map.insert("help-button".to_owned(), 1);
1392 map.insert("main".to_owned(), 1);
1393 map.insert("search".to_owned(), 1);
1394 map.insert("crate-search".to_owned(), 1);
1395 map.insert("render-detail".to_owned(), 1);
1396 map.insert("toggle-all-docs".to_owned(), 1);
1397 map.insert("all-types".to_owned(), 1);
1398 map.insert("default-settings".to_owned(), 1);
1399 map.insert("rustdoc-vars".to_owned(), 1);
1400 map.insert("sidebar-vars".to_owned(), 1);
1401 map.insert("copy-path".to_owned(), 1);
1402 map.insert("TOC".to_owned(), 1);
1403 // This is the list of IDs used by rustdoc sections (but still generated by
1405 map.insert("fields".to_owned(), 1);
1406 map.insert("variants".to_owned(), 1);
1407 map.insert("implementors-list".to_owned(), 1);
1408 map.insert("synthetic-implementors-list".to_owned(), 1);
1409 map.insert("foreign-impls".to_owned(), 1);
1410 map.insert("implementations".to_owned(), 1);
1411 map.insert("trait-implementations".to_owned(), 1);
1412 map.insert("synthetic-implementations".to_owned(), 1);
1413 map.insert("blanket-implementations".to_owned(), 1);
1414 map.insert("associated-types".to_owned(), 1);
1415 map.insert("associated-const".to_owned(), 1);
1416 map.insert("required-methods".to_owned(), 1);
1417 map.insert("provided-methods".to_owned(), 1);
1418 map.insert("implementors".to_owned(), 1);
1419 map.insert("synthetic-implementors".to_owned(), 1);
1420 map.insert("trait-implementations-list".to_owned(), 1);
1421 map.insert("synthetic-implementations-list".to_owned(), 1);
1422 map.insert("blanket-implementations-list".to_owned(), 1);
1423 map.insert("deref-methods".to_owned(), 1);
1428 pub fn new() -> Self {
1429 IdMap { map: init_id_map() }
1432 crate fn derive<S: AsRef<str> + ToString>(&mut self, candidate: S) -> String {
1433 let id = match self.map.get_mut(candidate.as_ref()) {
1434 None => candidate.to_string(),
1436 let id = format!("{}-{}", candidate.as_ref(), *a);
1442 self.map.insert(id.clone(), 1);