]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/markdown.rs
Add a test that rustc compiles and links separately
[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);
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> {
451     inner: I,
452     toc: Option<&'b mut TocBuilder>,
453     buf: VecDeque<(Event<'a>, Range<usize>)>,
454     id_map: &'ids mut IdMap,
455 }
456
457 impl<'a, 'b, 'ids, I> 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>, Range<usize>)>> Iterator
464     for HeadingLinks<'a, 'b, 'ids, I>
465 {
466     type Item = (Event<'a>, Range<usize>);
467
468     fn next(&mut self) -> Option<Self::Item> {
469         if let Some(e) = self.buf.pop_front() {
470             return Some(e);
471         }
472
473         let event = self.inner.next();
474         if let Some((Event::Start(Tag::Heading(level)), _)) = event {
475             let mut id = String::new();
476             for event in &mut self.inner {
477                 match &event.0 {
478                     Event::End(Tag::Heading(..)) => break,
479                     Event::Start(Tag::Link(_, _, _)) | Event::End(Tag::Link(..)) => {}
480                     Event::Text(text) | Event::Code(text) => {
481                         id.extend(text.chars().filter_map(slugify));
482                         self.buf.push_back(event);
483                     }
484                     _ => 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().map(|(ev, _)| ev.clone()));
492                 let sec = builder.push(level as u32, html_header, id.clone());
493                 self.buf.push_front((Event::Html(format!("{} ", sec).into()), 0..0));
494             }
495
496             self.buf.push_back((Event::Html(format!("</a></h{}>", level).into()), 0..0));
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()), 0..0));
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> {
579     inner: I,
580     footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
581 }
582
583 impl<'a, I> Footnotes<'a, I> {
584     fn new(iter: I) -> Self {
585         Footnotes { inner: iter, footnotes: FxHashMap::default() }
586     }
587
588     fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
589         let new_id = self.footnotes.keys().count() + 1;
590         let key = key.to_owned();
591         self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
592     }
593 }
594
595 impl<'a, I: Iterator<Item = (Event<'a>, Range<usize>)>> Iterator for Footnotes<'a, I> {
596     type Item = (Event<'a>, Range<usize>);
597
598     fn next(&mut self) -> Option<Self::Item> {
599         loop {
600             match self.inner.next() {
601                 Some((Event::FootnoteReference(ref reference), range)) => {
602                     let entry = self.get_entry(&reference);
603                     let reference = format!(
604                         "<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}</a></sup>",
605                         (*entry).1
606                     );
607                     return Some((Event::Html(reference.into()), range));
608                 }
609                 Some((Event::Start(Tag::FootnoteDefinition(def)), _)) => {
610                     let mut content = Vec::new();
611                     for (event, _) in &mut self.inner {
612                         if let Event::End(Tag::FootnoteDefinition(..)) = event {
613                             break;
614                         }
615                         content.push(event);
616                     }
617                     let entry = self.get_entry(&def);
618                     (*entry).0 = content;
619                 }
620                 Some(e) => return Some(e),
621                 None => {
622                     if !self.footnotes.is_empty() {
623                         let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
624                         v.sort_by(|a, b| a.1.cmp(&b.1));
625                         let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
626                         for (mut content, id) in v {
627                             write!(ret, "<li id=\"fn{}\">", id).unwrap();
628                             let mut is_paragraph = false;
629                             if let Some(&Event::End(Tag::Paragraph)) = content.last() {
630                                 content.pop();
631                                 is_paragraph = true;
632                             }
633                             html::push_html(&mut ret, content.into_iter());
634                             write!(ret, "&nbsp;<a href=\"#fnref{}\" rev=\"footnote\">↩</a>", id)
635                                 .unwrap();
636                             if is_paragraph {
637                                 ret.push_str("</p>");
638                             }
639                             ret.push_str("</li>");
640                         }
641                         ret.push_str("</ol></div>");
642                         return Some((Event::Html(ret.into()), 0..0));
643                     } else {
644                         return None;
645                     }
646                 }
647             }
648         }
649     }
650 }
651
652 crate fn find_testable_code<T: doctest::Tester>(
653     doc: &str,
654     tests: &mut T,
655     error_codes: ErrorCodes,
656     enable_per_target_ignores: bool,
657     extra_info: Option<&ExtraInfo<'_, '_>>,
658 ) {
659     let mut parser = Parser::new(doc).into_offset_iter();
660     let mut prev_offset = 0;
661     let mut nb_lines = 0;
662     let mut register_header = None;
663     while let Some((event, offset)) = parser.next() {
664         match event {
665             Event::Start(Tag::CodeBlock(kind)) => {
666                 let block_info = match kind {
667                     CodeBlockKind::Fenced(ref lang) => {
668                         if lang.is_empty() {
669                             Default::default()
670                         } else {
671                             LangString::parse(
672                                 lang,
673                                 error_codes,
674                                 enable_per_target_ignores,
675                                 extra_info,
676                             )
677                         }
678                     }
679                     CodeBlockKind::Indented => Default::default(),
680                 };
681                 if !block_info.rust {
682                     continue;
683                 }
684
685                 let mut test_s = String::new();
686
687                 while let Some((Event::Text(s), _)) = parser.next() {
688                     test_s.push_str(&s);
689                 }
690                 let text = test_s
691                     .lines()
692                     .map(|l| map_line(l).for_code())
693                     .collect::<Vec<Cow<'_, str>>>()
694                     .join("\n");
695
696                 nb_lines += doc[prev_offset..offset.start].lines().count();
697                 let line = tests.get_line() + nb_lines + 1;
698                 tests.add_test(text, block_info, line);
699                 prev_offset = offset.start;
700             }
701             Event::Start(Tag::Heading(level)) => {
702                 register_header = Some(level as u32);
703             }
704             Event::Text(ref s) if register_header.is_some() => {
705                 let level = register_header.unwrap();
706                 if s.is_empty() {
707                     tests.register_header("", level);
708                 } else {
709                     tests.register_header(s, level);
710                 }
711                 register_header = None;
712             }
713             _ => {}
714         }
715     }
716 }
717
718 crate struct ExtraInfo<'a, 'b> {
719     hir_id: Option<HirId>,
720     item_did: Option<DefId>,
721     sp: Span,
722     tcx: &'a TyCtxt<'b>,
723 }
724
725 impl<'a, 'b> ExtraInfo<'a, 'b> {
726     crate fn new(tcx: &'a TyCtxt<'b>, hir_id: HirId, sp: Span) -> ExtraInfo<'a, 'b> {
727         ExtraInfo { hir_id: Some(hir_id), item_did: None, sp, tcx }
728     }
729
730     crate fn new_did(tcx: &'a TyCtxt<'b>, did: DefId, sp: Span) -> ExtraInfo<'a, 'b> {
731         ExtraInfo { hir_id: None, item_did: Some(did), sp, tcx }
732     }
733
734     fn error_invalid_codeblock_attr(&self, msg: &str, help: &str) {
735         let hir_id = match (self.hir_id, self.item_did) {
736             (Some(h), _) => h,
737             (None, Some(item_did)) => {
738                 match item_did.as_local() {
739                     Some(item_did) => self.tcx.hir().local_def_id_to_hir_id(item_did),
740                     None => {
741                         // If non-local, no need to check anything.
742                         return;
743                     }
744                 }
745             }
746             (None, None) => return,
747         };
748         self.tcx.struct_span_lint_hir(
749             lint::builtin::INVALID_CODEBLOCK_ATTRIBUTES,
750             hir_id,
751             self.sp,
752             |lint| {
753                 let mut diag = lint.build(msg);
754                 diag.help(help);
755                 diag.emit();
756             },
757         );
758     }
759 }
760
761 #[derive(Eq, PartialEq, Clone, Debug)]
762 crate struct LangString {
763     original: String,
764     crate should_panic: bool,
765     crate no_run: bool,
766     crate ignore: Ignore,
767     crate rust: bool,
768     crate test_harness: bool,
769     crate compile_fail: bool,
770     crate error_codes: Vec<String>,
771     crate allow_fail: bool,
772     crate edition: Option<Edition>,
773 }
774
775 #[derive(Eq, PartialEq, Clone, Debug)]
776 crate enum Ignore {
777     All,
778     None,
779     Some(Vec<String>),
780 }
781
782 impl Default for LangString {
783     fn default() -> Self {
784         Self {
785             original: String::new(),
786             should_panic: false,
787             no_run: false,
788             ignore: Ignore::None,
789             rust: true,
790             test_harness: false,
791             compile_fail: false,
792             error_codes: Vec::new(),
793             allow_fail: false,
794             edition: None,
795         }
796     }
797 }
798
799 impl LangString {
800     fn parse_without_check(
801         string: &str,
802         allow_error_code_check: ErrorCodes,
803         enable_per_target_ignores: bool,
804     ) -> LangString {
805         Self::parse(string, allow_error_code_check, enable_per_target_ignores, None)
806     }
807
808     fn parse(
809         string: &str,
810         allow_error_code_check: ErrorCodes,
811         enable_per_target_ignores: bool,
812         extra: Option<&ExtraInfo<'_, '_>>,
813     ) -> LangString {
814         let allow_error_code_check = allow_error_code_check.as_bool();
815         let mut seen_rust_tags = false;
816         let mut seen_other_tags = false;
817         let mut data = LangString::default();
818         let mut ignores = vec![];
819
820         data.original = string.to_owned();
821         let tokens = string.split(|c: char| !(c == '_' || c == '-' || c.is_alphanumeric()));
822
823         for token in tokens {
824             match token.trim() {
825                 "" => {}
826                 "should_panic" => {
827                     data.should_panic = true;
828                     seen_rust_tags = !seen_other_tags;
829                 }
830                 "no_run" => {
831                     data.no_run = true;
832                     seen_rust_tags = !seen_other_tags;
833                 }
834                 "ignore" => {
835                     data.ignore = Ignore::All;
836                     seen_rust_tags = !seen_other_tags;
837                 }
838                 x if x.starts_with("ignore-") => {
839                     if enable_per_target_ignores {
840                         ignores.push(x.trim_start_matches("ignore-").to_owned());
841                         seen_rust_tags = !seen_other_tags;
842                     }
843                 }
844                 "allow_fail" => {
845                     data.allow_fail = true;
846                     seen_rust_tags = !seen_other_tags;
847                 }
848                 "rust" => {
849                     data.rust = true;
850                     seen_rust_tags = true;
851                 }
852                 "test_harness" => {
853                     data.test_harness = true;
854                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
855                 }
856                 "compile_fail" => {
857                     data.compile_fail = true;
858                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
859                     data.no_run = true;
860                 }
861                 x if x.starts_with("edition") => {
862                     data.edition = x[7..].parse::<Edition>().ok();
863                 }
864                 x if allow_error_code_check && x.starts_with('E') && x.len() == 5 => {
865                     if x[1..].parse::<u32>().is_ok() {
866                         data.error_codes.push(x.to_owned());
867                         seen_rust_tags = !seen_other_tags || seen_rust_tags;
868                     } else {
869                         seen_other_tags = true;
870                     }
871                 }
872                 x if extra.is_some() => {
873                     let s = x.to_lowercase();
874                     match if s == "compile-fail" || s == "compile_fail" || s == "compilefail" {
875                         Some((
876                             "compile_fail",
877                             "the code block will either not be tested if not marked as a rust one \
878                              or won't fail if it compiles successfully",
879                         ))
880                     } else if s == "should-panic" || s == "should_panic" || s == "shouldpanic" {
881                         Some((
882                             "should_panic",
883                             "the code block will either not be tested if not marked as a rust one \
884                              or won't fail if it doesn't panic when running",
885                         ))
886                     } else if s == "no-run" || s == "no_run" || s == "norun" {
887                         Some((
888                             "no_run",
889                             "the code block will either not be tested if not marked as a rust one \
890                              or will be run (which you might not want)",
891                         ))
892                     } else if s == "allow-fail" || s == "allow_fail" || s == "allowfail" {
893                         Some((
894                             "allow_fail",
895                             "the code block will either not be tested if not marked as a rust one \
896                              or will be run (which you might not want)",
897                         ))
898                     } else if s == "test-harness" || s == "test_harness" || s == "testharness" {
899                         Some((
900                             "test_harness",
901                             "the code block will either not be tested if not marked as a rust one \
902                              or the code will be wrapped inside a main function",
903                         ))
904                     } else {
905                         None
906                     } {
907                         Some((flag, help)) => {
908                             if let Some(ref extra) = extra {
909                                 extra.error_invalid_codeblock_attr(
910                                     &format!("unknown attribute `{}`. Did you mean `{}`?", x, flag),
911                                     help,
912                                 );
913                             }
914                         }
915                         None => {}
916                     }
917                     seen_other_tags = true;
918                 }
919                 _ => seen_other_tags = true,
920             }
921         }
922         // ignore-foo overrides ignore
923         if !ignores.is_empty() {
924             data.ignore = Ignore::Some(ignores);
925         }
926
927         data.rust &= !seen_other_tags || seen_rust_tags;
928
929         data
930     }
931 }
932
933 impl Markdown<'_> {
934     pub fn into_string(self) -> String {
935         let Markdown(md, links, mut ids, codes, edition, playground) = self;
936
937         // This is actually common enough to special-case
938         if md.is_empty() {
939             return String::new();
940         }
941         let mut replacer = |broken_link: BrokenLink<'_>| {
942             if let Some(link) =
943                 links.iter().find(|link| &*link.original_text == broken_link.reference)
944             {
945                 Some((link.href.as_str().into(), link.new_text.as_str().into()))
946             } else {
947                 None
948             }
949         };
950
951         let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut replacer));
952         let p = p.into_offset_iter();
953
954         let mut s = String::with_capacity(md.len() * 3 / 2);
955
956         let p = HeadingLinks::new(p, None, &mut ids);
957         let p = Footnotes::new(p);
958         let p = LinkReplacer::new(p.map(|(ev, _)| ev), links);
959         let p = CodeBlocks::new(p, codes, edition, playground);
960         html::push_html(&mut s, p);
961
962         s
963     }
964 }
965
966 impl MarkdownWithToc<'_> {
967     crate fn into_string(self) -> String {
968         let MarkdownWithToc(md, mut ids, codes, edition, playground) = self;
969
970         let p = Parser::new_ext(md, opts()).into_offset_iter();
971
972         let mut s = String::with_capacity(md.len() * 3 / 2);
973
974         let mut toc = TocBuilder::new();
975
976         {
977             let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
978             let p = Footnotes::new(p);
979             let p = CodeBlocks::new(p.map(|(ev, _)| ev), codes, edition, playground);
980             html::push_html(&mut s, p);
981         }
982
983         format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s)
984     }
985 }
986
987 impl MarkdownHtml<'_> {
988     crate fn into_string(self) -> String {
989         let MarkdownHtml(md, mut ids, codes, edition, playground) = self;
990
991         // This is actually common enough to special-case
992         if md.is_empty() {
993             return String::new();
994         }
995         let p = Parser::new_ext(md, opts()).into_offset_iter();
996
997         // Treat inline HTML as plain text.
998         let p = p.map(|event| match event.0 {
999             Event::Html(text) => (Event::Text(text), event.1),
1000             _ => event,
1001         });
1002
1003         let mut s = String::with_capacity(md.len() * 3 / 2);
1004
1005         let p = HeadingLinks::new(p, None, &mut ids);
1006         let p = Footnotes::new(p);
1007         let p = CodeBlocks::new(p.map(|(ev, _)| ev), codes, edition, playground);
1008         html::push_html(&mut s, p);
1009
1010         s
1011     }
1012 }
1013
1014 impl MarkdownSummaryLine<'_> {
1015     crate fn into_string(self) -> String {
1016         let MarkdownSummaryLine(md, links) = self;
1017         // This is actually common enough to special-case
1018         if md.is_empty() {
1019             return String::new();
1020         }
1021
1022         let mut replacer = |broken_link: BrokenLink<'_>| {
1023             if let Some(link) =
1024                 links.iter().find(|link| &*link.original_text == broken_link.reference)
1025             {
1026                 Some((link.href.as_str().into(), link.new_text.as_str().into()))
1027             } else {
1028                 None
1029             }
1030         };
1031
1032         let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1033
1034         let mut s = String::new();
1035
1036         html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
1037
1038         s
1039     }
1040 }
1041
1042 /// Renders a subset of Markdown in the first paragraph of the provided Markdown.
1043 ///
1044 /// - *Italics*, **bold**, and `inline code` styles **are** rendered.
1045 /// - Headings and links are stripped (though the text *is* rendered).
1046 /// - HTML, code blocks, and everything else are ignored.
1047 ///
1048 /// Returns a tuple of the rendered HTML string and whether the output was shortened
1049 /// due to the provided `length_limit`.
1050 fn markdown_summary_with_limit(md: &str, length_limit: usize) -> (String, bool) {
1051     if md.is_empty() {
1052         return (String::new(), false);
1053     }
1054
1055     let mut s = String::with_capacity(md.len() * 3 / 2);
1056     let mut text_length = 0;
1057     let mut stopped_early = false;
1058
1059     fn push(s: &mut String, text_length: &mut usize, text: &str) {
1060         s.push_str(text);
1061         *text_length += text.len();
1062     };
1063
1064     'outer: for event in Parser::new_ext(md, summary_opts()) {
1065         match &event {
1066             Event::Text(text) => {
1067                 for word in text.split_inclusive(char::is_whitespace) {
1068                     if text_length + word.len() >= length_limit {
1069                         stopped_early = true;
1070                         break 'outer;
1071                     }
1072
1073                     push(&mut s, &mut text_length, word);
1074                 }
1075             }
1076             Event::Code(code) => {
1077                 if text_length + code.len() >= length_limit {
1078                     stopped_early = true;
1079                     break;
1080                 }
1081
1082                 s.push_str("<code>");
1083                 push(&mut s, &mut text_length, code);
1084                 s.push_str("</code>");
1085             }
1086             Event::Start(tag) => match tag {
1087                 Tag::Emphasis => s.push_str("<em>"),
1088                 Tag::Strong => s.push_str("<strong>"),
1089                 Tag::CodeBlock(..) => break,
1090                 _ => {}
1091             },
1092             Event::End(tag) => match tag {
1093                 Tag::Emphasis => s.push_str("</em>"),
1094                 Tag::Strong => s.push_str("</strong>"),
1095                 Tag::Paragraph => break,
1096                 _ => {}
1097             },
1098             Event::HardBreak | Event::SoftBreak => {
1099                 if text_length + 1 >= length_limit {
1100                     stopped_early = true;
1101                     break;
1102                 }
1103
1104                 push(&mut s, &mut text_length, " ");
1105             }
1106             _ => {}
1107         }
1108     }
1109
1110     (s, stopped_early)
1111 }
1112
1113 /// Renders a shortened first paragraph of the given Markdown as a subset of Markdown,
1114 /// making it suitable for contexts like the search index.
1115 ///
1116 /// Will shorten to 59 or 60 characters, including an ellipsis (…) if it was shortened.
1117 ///
1118 /// See [`markdown_summary_with_limit`] for details about what is rendered and what is not.
1119 crate fn short_markdown_summary(markdown: &str) -> String {
1120     let (mut s, was_shortened) = markdown_summary_with_limit(markdown, 59);
1121
1122     if was_shortened {
1123         s.push('…');
1124     }
1125
1126     s
1127 }
1128
1129 /// Renders the first paragraph of the provided markdown as plain text.
1130 /// Useful for alt-text.
1131 ///
1132 /// - Headings, links, and formatting are stripped.
1133 /// - Inline code is rendered as-is, surrounded by backticks.
1134 /// - HTML and code blocks are ignored.
1135 crate fn plain_text_summary(md: &str) -> String {
1136     if md.is_empty() {
1137         return String::new();
1138     }
1139
1140     let mut s = String::with_capacity(md.len() * 3 / 2);
1141
1142     for event in Parser::new_ext(md, summary_opts()) {
1143         match &event {
1144             Event::Text(text) => s.push_str(text),
1145             Event::Code(code) => {
1146                 s.push('`');
1147                 s.push_str(code);
1148                 s.push('`');
1149             }
1150             Event::HardBreak | Event::SoftBreak => s.push(' '),
1151             Event::Start(Tag::CodeBlock(..)) => break,
1152             Event::End(Tag::Paragraph) => break,
1153             _ => (),
1154         }
1155     }
1156
1157     s
1158 }
1159
1160 crate fn markdown_links(md: &str) -> Vec<(String, Range<usize>)> {
1161     if md.is_empty() {
1162         return vec![];
1163     }
1164
1165     let mut links = vec![];
1166     // Used to avoid mutable borrow issues in the `push` closure
1167     // Probably it would be more efficient to use a `RefCell` but it doesn't seem worth the churn.
1168     let mut shortcut_links = vec![];
1169
1170     let span_for_link = |link: &str, span: Range<usize>| {
1171         // Pulldown includes the `[]` as well as the URL. Only highlight the relevant span.
1172         // NOTE: uses `rfind` in case the title and url are the same: `[Ok][Ok]`
1173         match md[span.clone()].rfind(link) {
1174             Some(start) => {
1175                 let start = span.start + start;
1176                 start..start + link.len()
1177             }
1178             // This can happen for things other than intra-doc links, like `#1` expanded to `https://github.com/rust-lang/rust/issues/1`.
1179             None => span,
1180         }
1181     };
1182     let mut push = |link: BrokenLink<'_>| {
1183         let span = span_for_link(link.reference, link.span);
1184         shortcut_links.push((link.reference.to_owned(), span));
1185         None
1186     };
1187     let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut push));
1188
1189     // There's no need to thread an IdMap through to here because
1190     // the IDs generated aren't going to be emitted anywhere.
1191     let mut ids = IdMap::new();
1192     let iter = Footnotes::new(HeadingLinks::new(p.into_offset_iter(), None, &mut ids));
1193
1194     for ev in iter {
1195         if let Event::Start(Tag::Link(_, dest, _)) = ev.0 {
1196             debug!("found link: {}", dest);
1197             let span = span_for_link(&dest, ev.1);
1198             links.push((dest.into_string(), span));
1199         }
1200     }
1201
1202     links.append(&mut shortcut_links);
1203
1204     links
1205 }
1206
1207 #[derive(Debug)]
1208 crate struct RustCodeBlock {
1209     /// The range in the markdown that the code block occupies. Note that this includes the fences
1210     /// for fenced code blocks.
1211     crate range: Range<usize>,
1212     /// The range in the markdown that the code within the code block occupies.
1213     crate code: Range<usize>,
1214     crate is_fenced: bool,
1215     crate syntax: Option<String>,
1216 }
1217
1218 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
1219 /// untagged (and assumed to be rust).
1220 crate fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_, '_>) -> Vec<RustCodeBlock> {
1221     let mut code_blocks = vec![];
1222
1223     if md.is_empty() {
1224         return code_blocks;
1225     }
1226
1227     let mut p = Parser::new_ext(md, opts()).into_offset_iter();
1228
1229     while let Some((event, offset)) = p.next() {
1230         if let Event::Start(Tag::CodeBlock(syntax)) = event {
1231             let (syntax, code_start, code_end, range, is_fenced) = match syntax {
1232                 CodeBlockKind::Fenced(syntax) => {
1233                     let syntax = syntax.as_ref();
1234                     let lang_string = if syntax.is_empty() {
1235                         Default::default()
1236                     } else {
1237                         LangString::parse(&*syntax, ErrorCodes::Yes, false, Some(extra_info))
1238                     };
1239                     if !lang_string.rust {
1240                         continue;
1241                     }
1242                     let syntax = if syntax.is_empty() { None } else { Some(syntax.to_owned()) };
1243                     let (code_start, mut code_end) = match p.next() {
1244                         Some((Event::Text(_), offset)) => (offset.start, offset.end),
1245                         Some((_, sub_offset)) => {
1246                             let code = Range { start: sub_offset.start, end: sub_offset.start };
1247                             code_blocks.push(RustCodeBlock {
1248                                 is_fenced: true,
1249                                 range: offset,
1250                                 code,
1251                                 syntax,
1252                             });
1253                             continue;
1254                         }
1255                         None => {
1256                             let code = Range { start: offset.end, end: offset.end };
1257                             code_blocks.push(RustCodeBlock {
1258                                 is_fenced: true,
1259                                 range: offset,
1260                                 code,
1261                                 syntax,
1262                             });
1263                             continue;
1264                         }
1265                     };
1266                     while let Some((Event::Text(_), offset)) = p.next() {
1267                         code_end = offset.end;
1268                     }
1269                     (syntax, code_start, code_end, offset, true)
1270                 }
1271                 CodeBlockKind::Indented => {
1272                     // The ending of the offset goes too far sometime so we reduce it by one in
1273                     // these cases.
1274                     if offset.end > offset.start && md.get(offset.end..=offset.end) == Some(&"\n") {
1275                         (
1276                             None,
1277                             offset.start,
1278                             offset.end,
1279                             Range { start: offset.start, end: offset.end - 1 },
1280                             false,
1281                         )
1282                     } else {
1283                         (None, offset.start, offset.end, offset, false)
1284                     }
1285                 }
1286             };
1287
1288             code_blocks.push(RustCodeBlock {
1289                 is_fenced,
1290                 range,
1291                 code: Range { start: code_start, end: code_end },
1292                 syntax,
1293             });
1294         }
1295     }
1296
1297     code_blocks
1298 }
1299
1300 #[derive(Clone, Default, Debug)]
1301 pub struct IdMap {
1302     map: FxHashMap<String, usize>,
1303 }
1304
1305 fn init_id_map() -> FxHashMap<String, usize> {
1306     let mut map = FxHashMap::default();
1307     // This is the list of IDs used by rustdoc templates.
1308     map.insert("mainThemeStyle".to_owned(), 1);
1309     map.insert("themeStyle".to_owned(), 1);
1310     map.insert("theme-picker".to_owned(), 1);
1311     map.insert("theme-choices".to_owned(), 1);
1312     map.insert("settings-menu".to_owned(), 1);
1313     map.insert("main".to_owned(), 1);
1314     map.insert("search".to_owned(), 1);
1315     map.insert("crate-search".to_owned(), 1);
1316     map.insert("render-detail".to_owned(), 1);
1317     map.insert("toggle-all-docs".to_owned(), 1);
1318     map.insert("all-types".to_owned(), 1);
1319     map.insert("default-settings".to_owned(), 1);
1320     // This is the list of IDs used by rustdoc sections.
1321     map.insert("fields".to_owned(), 1);
1322     map.insert("variants".to_owned(), 1);
1323     map.insert("implementors-list".to_owned(), 1);
1324     map.insert("synthetic-implementors-list".to_owned(), 1);
1325     map.insert("implementations".to_owned(), 1);
1326     map.insert("trait-implementations".to_owned(), 1);
1327     map.insert("synthetic-implementations".to_owned(), 1);
1328     map.insert("blanket-implementations".to_owned(), 1);
1329     map.insert("deref-methods".to_owned(), 1);
1330     map
1331 }
1332
1333 impl IdMap {
1334     pub fn new() -> Self {
1335         IdMap { map: init_id_map() }
1336     }
1337
1338     crate fn populate<I: IntoIterator<Item = String>>(&mut self, ids: I) {
1339         for id in ids {
1340             let _ = self.derive(id);
1341         }
1342     }
1343
1344     crate fn reset(&mut self) {
1345         self.map = init_id_map();
1346     }
1347
1348     crate fn derive(&mut self, candidate: String) -> String {
1349         let id = match self.map.get_mut(&candidate) {
1350             None => candidate,
1351             Some(a) => {
1352                 let id = format!("{}-{}", candidate, *a);
1353                 *a += 1;
1354                 id
1355             }
1356         };
1357
1358         self.map.insert(id.clone(), 1);
1359         id
1360     }
1361 }