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