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