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