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