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