]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/markdown.rs
Remove inline script tags
[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::{
41     html, BrokenLink, CodeBlockKind, CowStr, Event, LinkType, Options, Parser, Tag,
42 };
43
44 #[cfg(test)]
45 mod tests;
46
47 /// Options for rendering Markdown in the main body of documentation.
48 pub(crate) fn opts() -> Options {
49     Options::ENABLE_TABLES | Options::ENABLE_FOOTNOTES | Options::ENABLE_STRIKETHROUGH
50 }
51
52 /// A subset of [`opts()`] used for rendering summaries.
53 pub(crate) fn summary_opts() -> Options {
54     Options::ENABLE_STRIKETHROUGH
55 }
56
57 /// When `to_string` is called, this struct will emit the HTML corresponding to
58 /// the rendered version of the contained markdown string.
59 pub struct Markdown<'a>(
60     pub &'a str,
61     /// A list of link replacements.
62     pub &'a [RenderedLink],
63     /// The current list of used header IDs.
64     pub &'a mut IdMap,
65     /// Whether to allow the use of explicit error codes in doctest lang strings.
66     pub ErrorCodes,
67     /// Default edition to use when parsing doctests (to add a `fn main`).
68     pub Edition,
69     pub &'a Option<Playground>,
70 );
71 /// A tuple struct like `Markdown` that renders the markdown with a table of contents.
72 crate struct MarkdownWithToc<'a>(
73     crate &'a str,
74     crate &'a mut IdMap,
75     crate ErrorCodes,
76     crate Edition,
77     crate &'a Option<Playground>,
78 );
79 /// A tuple struct like `Markdown` that renders the markdown escaping HTML tags.
80 crate struct MarkdownHtml<'a>(
81     crate &'a str,
82     crate &'a mut IdMap,
83     crate ErrorCodes,
84     crate Edition,
85     crate &'a Option<Playground>,
86 );
87 /// A tuple struct like `Markdown` that renders only the first paragraph.
88 crate struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [RenderedLink]);
89
90 #[derive(Copy, Clone, PartialEq, Debug)]
91 pub enum ErrorCodes {
92     Yes,
93     No,
94 }
95
96 impl ErrorCodes {
97     crate fn from(b: bool) -> Self {
98         match b {
99             true => ErrorCodes::Yes,
100             false => ErrorCodes::No,
101         }
102     }
103
104     crate fn as_bool(self) -> bool {
105         match self {
106             ErrorCodes::Yes => true,
107             ErrorCodes::No => false,
108         }
109     }
110 }
111
112 /// Controls whether a line will be hidden or shown in HTML output.
113 ///
114 /// All lines are used in documentation tests.
115 enum Line<'a> {
116     Hidden(&'a str),
117     Shown(Cow<'a, str>),
118 }
119
120 impl<'a> Line<'a> {
121     fn for_html(self) -> Option<Cow<'a, str>> {
122         match self {
123             Line::Shown(l) => Some(l),
124             Line::Hidden(_) => None,
125         }
126     }
127
128     fn for_code(self) -> Cow<'a, str> {
129         match self {
130             Line::Shown(l) => l,
131             Line::Hidden(l) => Cow::Borrowed(l),
132         }
133     }
134 }
135
136 // FIXME: There is a minor inconsistency here. For lines that start with ##, we
137 // have no easy way of removing a potential single space after the hashes, which
138 // is done in the single # case. This inconsistency seems okay, if non-ideal. In
139 // order to fix it we'd have to iterate to find the first non-# character, and
140 // then reallocate to remove it; which would make us return a String.
141 fn map_line(s: &str) -> Line<'_> {
142     let trimmed = s.trim();
143     if trimmed.starts_with("##") {
144         Line::Shown(Cow::Owned(s.replacen("##", "#", 1)))
145     } else if let Some(stripped) = trimmed.strip_prefix("# ") {
146         // # text
147         Line::Hidden(&stripped)
148     } else if trimmed == "#" {
149         // We cannot handle '#text' because it could be #[attr].
150         Line::Hidden("")
151     } else {
152         Line::Shown(Cow::Borrowed(s))
153     }
154 }
155
156 /// Convert chars from a title for an id.
157 ///
158 /// "Hello, world!" -> "hello-world"
159 fn slugify(c: char) -> Option<char> {
160     if c.is_alphanumeric() || c == '-' || c == '_' {
161         if c.is_ascii() { Some(c.to_ascii_lowercase()) } else { Some(c) }
162     } else if c.is_whitespace() && c.is_ascii() {
163         Some('-')
164     } else {
165         None
166     }
167 }
168
169 #[derive(Clone, Debug)]
170 pub struct Playground {
171     pub crate_name: Option<String>,
172     pub url: String,
173 }
174
175 /// Adds syntax highlighting and playground Run buttons to Rust code blocks.
176 struct CodeBlocks<'p, 'a, I: Iterator<Item = Event<'a>>> {
177     inner: I,
178     check_error_codes: ErrorCodes,
179     edition: Edition,
180     // Information about the playground if a URL has been specified, containing an
181     // optional crate name and the URL.
182     playground: &'p Option<Playground>,
183 }
184
185 impl<'p, 'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'p, 'a, I> {
186     fn new(
187         iter: I,
188         error_codes: ErrorCodes,
189         edition: Edition,
190         playground: &'p Option<Playground>,
191     ) -> Self {
192         CodeBlocks { inner: iter, check_error_codes: error_codes, edition, playground }
193     }
194 }
195
196 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
197     type Item = Event<'a>;
198
199     fn next(&mut self) -> Option<Self::Item> {
200         let event = self.inner.next();
201         let compile_fail;
202         let should_panic;
203         let ignore;
204         let edition;
205         if let Some(Event::Start(Tag::CodeBlock(kind))) = event {
206             let parse_result = match kind {
207                 CodeBlockKind::Fenced(ref lang) => {
208                     LangString::parse_without_check(&lang, self.check_error_codes, false)
209                 }
210                 CodeBlockKind::Indented => Default::default(),
211             };
212             if !parse_result.rust {
213                 return Some(Event::Start(Tag::CodeBlock(kind)));
214             }
215             compile_fail = parse_result.compile_fail;
216             should_panic = parse_result.should_panic;
217             ignore = parse_result.ignore;
218             edition = parse_result.edition;
219         } else {
220             return event;
221         }
222
223         let explicit_edition = edition.is_some();
224         let edition = edition.unwrap_or(self.edition);
225
226         let mut origtext = String::new();
227         for event in &mut self.inner {
228             match event {
229                 Event::End(Tag::CodeBlock(..)) => break,
230                 Event::Text(ref s) => {
231                     origtext.push_str(s);
232                 }
233                 _ => {}
234             }
235         }
236         let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
237         let text = lines.collect::<Vec<Cow<'_, str>>>().join("\n");
238         // insert newline to clearly separate it from the
239         // previous block so we can shorten the html output
240         let mut s = String::from("\n");
241         let playground_button = self.playground.as_ref().and_then(|playground| {
242             let krate = &playground.crate_name;
243             let url = &playground.url;
244             if url.is_empty() {
245                 return None;
246             }
247             let test = origtext
248                 .lines()
249                 .map(|l| map_line(l).for_code())
250                 .collect::<Vec<Cow<'_, str>>>()
251                 .join("\n");
252             let krate = krate.as_ref().map(|s| &**s);
253             let (test, _, _) =
254                 doctest::make_test(&test, krate, false, &Default::default(), edition, None);
255             let channel = if test.contains("#![feature(") { "&amp;version=nightly" } else { "" };
256
257             let edition_string = format!("&amp;edition={}", edition);
258
259             // These characters don't need to be escaped in a URI.
260             // FIXME: use a library function for percent encoding.
261             fn dont_escape(c: u8) -> bool {
262                 (b'a' <= c && c <= b'z')
263                     || (b'A' <= c && c <= b'Z')
264                     || (b'0' <= c && c <= b'9')
265                     || c == b'-'
266                     || c == b'_'
267                     || c == b'.'
268                     || c == b'~'
269                     || c == b'!'
270                     || c == b'\''
271                     || c == b'('
272                     || c == b')'
273                     || c == b'*'
274             }
275             let mut test_escaped = String::new();
276             for b in test.bytes() {
277                 if dont_escape(b) {
278                     test_escaped.push(char::from(b));
279                 } else {
280                     write!(test_escaped, "%{:02X}", b).unwrap();
281                 }
282             }
283             Some(format!(
284                 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}{}">Run</a>"#,
285                 url, test_escaped, channel, edition_string
286             ))
287         });
288
289         let tooltip = if ignore != Ignore::None {
290             Some((None, "ignore"))
291         } else if compile_fail {
292             Some((None, "compile_fail"))
293         } else if should_panic {
294             Some((None, "should_panic"))
295         } else if explicit_edition {
296             Some((Some(edition), "edition"))
297         } else {
298             None
299         };
300
301         s.push_str(&highlight::render_with_highlighting(
302             text,
303             Some(&format!(
304                 "rust-example-rendered{}",
305                 if let Some((_, class)) = tooltip { format!(" {}", class) } else { String::new() }
306             )),
307             playground_button.as_deref(),
308             tooltip,
309             edition,
310         ));
311         Some(Event::Html(s.into()))
312     }
313 }
314
315 /// Make headings links with anchor IDs and build up TOC.
316 struct LinkReplacer<'a, I: Iterator<Item = Event<'a>>> {
317     inner: I,
318     links: &'a [RenderedLink],
319     shortcut_link: Option<&'a RenderedLink>,
320 }
321
322 impl<'a, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, I> {
323     fn new(iter: I, links: &'a [RenderedLink]) -> Self {
324         LinkReplacer { inner: iter, links, shortcut_link: None }
325     }
326 }
327
328 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
329     type Item = Event<'a>;
330
331     fn next(&mut self) -> Option<Self::Item> {
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 struct MarkdownLink {
1127     pub kind: LinkType,
1128     pub link: String,
1129     pub range: Range<usize>,
1130 }
1131
1132 crate fn markdown_links(md: &str) -> Vec<MarkdownLink> {
1133     if md.is_empty() {
1134         return vec![];
1135     }
1136
1137     let links = RefCell::new(vec![]);
1138
1139     // FIXME: remove this function once pulldown_cmark can provide spans for link definitions.
1140     let locate = |s: &str, fallback: Range<usize>| unsafe {
1141         let s_start = s.as_ptr();
1142         let s_end = s_start.add(s.len());
1143         let md_start = md.as_ptr();
1144         let md_end = md_start.add(md.len());
1145         if md_start <= s_start && s_end <= md_end {
1146             let start = s_start.offset_from(md_start) as usize;
1147             let end = s_end.offset_from(md_start) as usize;
1148             start..end
1149         } else {
1150             fallback
1151         }
1152     };
1153
1154     let span_for_link = |link: &CowStr<'_>, span: Range<usize>| {
1155         // For diagnostics, we want to underline the link's definition but `span` will point at
1156         // where the link is used. This is a problem for reference-style links, where the definition
1157         // is separate from the usage.
1158         match link {
1159             // `Borrowed` variant means the string (the link's destination) may come directly from
1160             // the markdown text and we can locate the original link destination.
1161             // NOTE: LinkReplacer also provides `Borrowed` but possibly from other sources,
1162             // so `locate()` can fall back to use `span`.
1163             CowStr::Borrowed(s) => locate(s, span),
1164
1165             // For anything else, we can only use the provided range.
1166             CowStr::Boxed(_) | CowStr::Inlined(_) => span,
1167         }
1168     };
1169
1170     let mut push = |link: BrokenLink<'_>| {
1171         let span = span_for_link(&CowStr::Borrowed(link.reference), link.span);
1172         links.borrow_mut().push(MarkdownLink {
1173             kind: LinkType::ShortcutUnknown,
1174             link: link.reference.to_owned(),
1175             range: span,
1176         });
1177         None
1178     };
1179     let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut push)).into_offset_iter();
1180
1181     // There's no need to thread an IdMap through to here because
1182     // the IDs generated aren't going to be emitted anywhere.
1183     let mut ids = IdMap::new();
1184     let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids));
1185
1186     for ev in iter {
1187         if let Event::Start(Tag::Link(kind, dest, _)) = ev.0 {
1188             debug!("found link: {}", dest);
1189             let span = span_for_link(&dest, ev.1);
1190             links.borrow_mut().push(MarkdownLink { kind, link: dest.into_string(), range: span });
1191         }
1192     }
1193
1194     links.into_inner()
1195 }
1196
1197 #[derive(Debug)]
1198 crate struct RustCodeBlock {
1199     /// The range in the markdown that the code block occupies. Note that this includes the fences
1200     /// for fenced code blocks.
1201     crate range: Range<usize>,
1202     /// The range in the markdown that the code within the code block occupies.
1203     crate code: Range<usize>,
1204     crate is_fenced: bool,
1205     crate syntax: Option<String>,
1206     crate is_ignore: bool,
1207 }
1208
1209 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
1210 /// untagged (and assumed to be rust).
1211 crate fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_, '_>) -> Vec<RustCodeBlock> {
1212     let mut code_blocks = vec![];
1213
1214     if md.is_empty() {
1215         return code_blocks;
1216     }
1217
1218     let mut p = Parser::new_ext(md, opts()).into_offset_iter();
1219
1220     while let Some((event, offset)) = p.next() {
1221         if let Event::Start(Tag::CodeBlock(syntax)) = event {
1222             let (syntax, code_start, code_end, range, is_fenced, is_ignore) = match syntax {
1223                 CodeBlockKind::Fenced(syntax) => {
1224                     let syntax = syntax.as_ref();
1225                     let lang_string = if syntax.is_empty() {
1226                         Default::default()
1227                     } else {
1228                         LangString::parse(&*syntax, ErrorCodes::Yes, false, Some(extra_info))
1229                     };
1230                     if !lang_string.rust {
1231                         continue;
1232                     }
1233                     let is_ignore = lang_string.ignore != Ignore::None;
1234                     let syntax = if syntax.is_empty() { None } else { Some(syntax.to_owned()) };
1235                     let (code_start, mut code_end) = match p.next() {
1236                         Some((Event::Text(_), offset)) => (offset.start, offset.end),
1237                         Some((_, sub_offset)) => {
1238                             let code = Range { start: sub_offset.start, end: sub_offset.start };
1239                             code_blocks.push(RustCodeBlock {
1240                                 is_fenced: true,
1241                                 range: offset,
1242                                 code,
1243                                 syntax,
1244                                 is_ignore,
1245                             });
1246                             continue;
1247                         }
1248                         None => {
1249                             let code = Range { start: offset.end, end: offset.end };
1250                             code_blocks.push(RustCodeBlock {
1251                                 is_fenced: true,
1252                                 range: offset,
1253                                 code,
1254                                 syntax,
1255                                 is_ignore,
1256                             });
1257                             continue;
1258                         }
1259                     };
1260                     while let Some((Event::Text(_), offset)) = p.next() {
1261                         code_end = offset.end;
1262                     }
1263                     (syntax, code_start, code_end, offset, true, is_ignore)
1264                 }
1265                 CodeBlockKind::Indented => {
1266                     // The ending of the offset goes too far sometime so we reduce it by one in
1267                     // these cases.
1268                     if offset.end > offset.start && md.get(offset.end..=offset.end) == Some(&"\n") {
1269                         (
1270                             None,
1271                             offset.start,
1272                             offset.end,
1273                             Range { start: offset.start, end: offset.end - 1 },
1274                             false,
1275                             false,
1276                         )
1277                     } else {
1278                         (None, offset.start, offset.end, offset, false, false)
1279                     }
1280                 }
1281             };
1282
1283             code_blocks.push(RustCodeBlock {
1284                 is_fenced,
1285                 range,
1286                 code: Range { start: code_start, end: code_end },
1287                 syntax,
1288                 is_ignore,
1289             });
1290         }
1291     }
1292
1293     code_blocks
1294 }
1295
1296 #[derive(Clone, Default, Debug)]
1297 pub struct IdMap {
1298     map: FxHashMap<String, usize>,
1299 }
1300
1301 fn init_id_map() -> FxHashMap<String, usize> {
1302     let mut map = FxHashMap::default();
1303     // This is the list of IDs used by rustdoc templates.
1304     map.insert("mainThemeStyle".to_owned(), 1);
1305     map.insert("themeStyle".to_owned(), 1);
1306     map.insert("theme-picker".to_owned(), 1);
1307     map.insert("theme-choices".to_owned(), 1);
1308     map.insert("settings-menu".to_owned(), 1);
1309     map.insert("main".to_owned(), 1);
1310     map.insert("search".to_owned(), 1);
1311     map.insert("crate-search".to_owned(), 1);
1312     map.insert("render-detail".to_owned(), 1);
1313     map.insert("toggle-all-docs".to_owned(), 1);
1314     map.insert("all-types".to_owned(), 1);
1315     map.insert("default-settings".to_owned(), 1);
1316     map.insert("rustdoc-vars".to_owned(), 1);
1317     map.insert("sidebar-vars".to_owned(), 1);
1318     // This is the list of IDs used by rustdoc sections.
1319     map.insert("fields".to_owned(), 1);
1320     map.insert("variants".to_owned(), 1);
1321     map.insert("implementors-list".to_owned(), 1);
1322     map.insert("synthetic-implementors-list".to_owned(), 1);
1323     map.insert("implementations".to_owned(), 1);
1324     map.insert("trait-implementations".to_owned(), 1);
1325     map.insert("synthetic-implementations".to_owned(), 1);
1326     map.insert("blanket-implementations".to_owned(), 1);
1327     map
1328 }
1329
1330 impl IdMap {
1331     pub fn new() -> Self {
1332         IdMap { map: init_id_map() }
1333     }
1334
1335     crate fn populate<I: IntoIterator<Item = String>>(&mut self, ids: I) {
1336         for id in ids {
1337             let _ = self.derive(id);
1338         }
1339     }
1340
1341     crate fn reset(&mut self) {
1342         self.map = init_id_map();
1343     }
1344
1345     crate fn derive(&mut self, candidate: String) -> String {
1346         let id = match self.map.get_mut(&candidate) {
1347             None => candidate,
1348             Some(a) => {
1349                 let id = format!("{}-{}", candidate, *a);
1350                 *a += 1;
1351                 id
1352             }
1353         };
1354
1355         self.map.insert(id.clone(), 1);
1356         id
1357     }
1358 }