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