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