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