]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/highlight.rs
Rollup merge of #91504 - cynecx:used_retain, r=nikic
[rust.git] / src / librustdoc / html / highlight.rs
1 //! Basic syntax highlighting functionality.
2 //!
3 //! This module uses librustc_ast's lexer to provide token-based highlighting for
4 //! the HTML documentation generated by rustdoc.
5 //!
6 //! Use the `render_with_highlighting` to highlight some rust code.
7
8 use crate::clean::PrimitiveType;
9 use crate::html::escape::Escape;
10 use crate::html::render::Context;
11
12 use std::collections::VecDeque;
13 use std::fmt::{Display, Write};
14
15 use rustc_data_structures::fx::FxHashMap;
16 use rustc_lexer::{LiteralKind, TokenKind};
17 use rustc_span::edition::Edition;
18 use rustc_span::symbol::Symbol;
19 use rustc_span::{BytePos, Span, DUMMY_SP};
20
21 use super::format::{self, Buffer};
22 use super::render::LinkFromSrc;
23
24 /// This type is needed in case we want to render links on items to allow to go to their definition.
25 crate struct ContextInfo<'a, 'b, 'c> {
26     crate context: &'a Context<'b>,
27     /// This span contains the current file we're going through.
28     crate file_span: Span,
29     /// This field is used to know "how far" from the top of the directory we are to link to either
30     /// documentation pages or other source pages.
31     crate root_path: &'c str,
32 }
33
34 /// Decorations are represented as a map from CSS class to vector of character ranges.
35 /// Each range will be wrapped in a span with that class.
36 crate struct DecorationInfo(crate FxHashMap<&'static str, Vec<(u32, u32)>>);
37
38 /// Highlights `src`, returning the HTML output.
39 crate fn render_with_highlighting(
40     src: &str,
41     out: &mut Buffer,
42     class: Option<&str>,
43     playground_button: Option<&str>,
44     tooltip: Option<(Option<Edition>, &str)>,
45     edition: Edition,
46     extra_content: Option<Buffer>,
47     context_info: Option<ContextInfo<'_, '_, '_>>,
48     decoration_info: Option<DecorationInfo>,
49 ) {
50     debug!("highlighting: ================\n{}\n==============", src);
51     if let Some((edition_info, class)) = tooltip {
52         write!(
53             out,
54             "<div class='information'><div class='tooltip {}'{}>ⓘ</div></div>",
55             class,
56             if let Some(edition_info) = edition_info {
57                 format!(" data-edition=\"{}\"", edition_info)
58             } else {
59                 String::new()
60             },
61         );
62     }
63
64     write_header(out, class, extra_content);
65     write_code(out, src, edition, context_info, decoration_info);
66     write_footer(out, playground_button);
67 }
68
69 fn write_header(out: &mut Buffer, class: Option<&str>, extra_content: Option<Buffer>) {
70     write!(out, "<div class=\"example-wrap\">");
71     if let Some(extra) = extra_content {
72         out.push_buffer(extra);
73     }
74     if let Some(class) = class {
75         write!(out, "<pre class=\"rust {}\">", class);
76     } else {
77         write!(out, "<pre class=\"rust\">");
78     }
79     write!(out, "<code>");
80 }
81
82 /// Convert the given `src` source code into HTML by adding classes for highlighting.
83 ///
84 /// This code is used to render code blocks (in the documentation) as well as the source code pages.
85 ///
86 /// Some explanations on the last arguments:
87 ///
88 /// In case we are rendering a code block and not a source code file, `context_info` will be `None`.
89 /// To put it more simply: if `context_info` is `None`, the code won't try to generate links to an
90 /// item definition.
91 ///
92 /// More explanations about spans and how we use them here are provided in the
93 fn write_code(
94     out: &mut Buffer,
95     src: &str,
96     edition: Edition,
97     context_info: Option<ContextInfo<'_, '_, '_>>,
98     decoration_info: Option<DecorationInfo>,
99 ) {
100     // This replace allows to fix how the code source with DOS backline characters is displayed.
101     let src = src.replace("\r\n", "\n");
102     Classifier::new(
103         &src,
104         edition,
105         context_info.as_ref().map(|c| c.file_span).unwrap_or(DUMMY_SP),
106         decoration_info,
107     )
108     .highlight(&mut |highlight| {
109         match highlight {
110             Highlight::Token { text, class } => string(out, Escape(text), class, &context_info),
111             Highlight::EnterSpan { class } => enter_span(out, class),
112             Highlight::ExitSpan => exit_span(out),
113         };
114     });
115 }
116
117 fn write_footer(out: &mut Buffer, playground_button: Option<&str>) {
118     writeln!(out, "</code></pre>{}</div>", playground_button.unwrap_or_default());
119 }
120
121 /// How a span of text is classified. Mostly corresponds to token kinds.
122 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
123 enum Class {
124     Comment,
125     DocComment,
126     Attribute,
127     KeyWord,
128     // Keywords that do pointer/reference stuff.
129     RefKeyWord,
130     Self_(Span),
131     Op,
132     Macro,
133     MacroNonTerminal,
134     String,
135     Number,
136     Bool,
137     Ident(Span),
138     Lifetime,
139     PreludeTy,
140     PreludeVal,
141     QuestionMark,
142     Decoration(&'static str),
143 }
144
145 impl Class {
146     /// Returns the css class expected by rustdoc for each `Class`.
147     fn as_html(self) -> &'static str {
148         match self {
149             Class::Comment => "comment",
150             Class::DocComment => "doccomment",
151             Class::Attribute => "attribute",
152             Class::KeyWord => "kw",
153             Class::RefKeyWord => "kw-2",
154             Class::Self_(_) => "self",
155             Class::Op => "op",
156             Class::Macro => "macro",
157             Class::MacroNonTerminal => "macro-nonterminal",
158             Class::String => "string",
159             Class::Number => "number",
160             Class::Bool => "bool-val",
161             Class::Ident(_) => "ident",
162             Class::Lifetime => "lifetime",
163             Class::PreludeTy => "prelude-ty",
164             Class::PreludeVal => "prelude-val",
165             Class::QuestionMark => "question-mark",
166             Class::Decoration(kind) => kind,
167         }
168     }
169
170     /// In case this is an item which can be converted into a link to a definition, it'll contain
171     /// a "span" (a tuple representing `(lo, hi)` equivalent of `Span`).
172     fn get_span(self) -> Option<Span> {
173         match self {
174             Self::Ident(sp) | Self::Self_(sp) => Some(sp),
175             _ => None,
176         }
177     }
178 }
179
180 enum Highlight<'a> {
181     Token { text: &'a str, class: Option<Class> },
182     EnterSpan { class: Class },
183     ExitSpan,
184 }
185
186 struct TokenIter<'a> {
187     src: &'a str,
188 }
189
190 impl<'a> Iterator for TokenIter<'a> {
191     type Item = (TokenKind, &'a str);
192     fn next(&mut self) -> Option<(TokenKind, &'a str)> {
193         if self.src.is_empty() {
194             return None;
195         }
196         let token = rustc_lexer::first_token(self.src);
197         let (text, rest) = self.src.split_at(token.len);
198         self.src = rest;
199         Some((token.kind, text))
200     }
201 }
202
203 /// Classifies into identifier class; returns `None` if this is a non-keyword identifier.
204 fn get_real_ident_class(text: &str, edition: Edition, allow_path_keywords: bool) -> Option<Class> {
205     let ignore: &[&str] =
206         if allow_path_keywords { &["self", "Self", "super", "crate"] } else { &["self", "Self"] };
207     if ignore.iter().any(|k| *k == text) {
208         return None;
209     }
210     Some(match text {
211         "ref" | "mut" => Class::RefKeyWord,
212         "false" | "true" => Class::Bool,
213         _ if Symbol::intern(text).is_reserved(|| edition) => Class::KeyWord,
214         _ => return None,
215     })
216 }
217
218 /// This iterator comes from the same idea than "Peekable" except that it allows to "peek" more than
219 /// just the next item by using `peek_next`. The `peek` method always returns the next item after
220 /// the current one whereas `peek_next` will return the next item after the last one peeked.
221 ///
222 /// You can use both `peek` and `peek_next` at the same time without problem.
223 struct PeekIter<'a> {
224     stored: VecDeque<(TokenKind, &'a str)>,
225     /// This position is reinitialized when using `next`. It is used in `peek_next`.
226     peek_pos: usize,
227     iter: TokenIter<'a>,
228 }
229
230 impl<'a> PeekIter<'a> {
231     fn new(iter: TokenIter<'a>) -> Self {
232         Self { stored: VecDeque::new(), peek_pos: 0, iter }
233     }
234     /// Returns the next item after the current one. It doesn't interfer with `peek_next` output.
235     fn peek(&mut self) -> Option<&(TokenKind, &'a str)> {
236         if self.stored.is_empty() {
237             if let Some(next) = self.iter.next() {
238                 self.stored.push_back(next);
239             }
240         }
241         self.stored.front()
242     }
243     /// Returns the next item after the last one peeked. It doesn't interfer with `peek` output.
244     fn peek_next(&mut self) -> Option<&(TokenKind, &'a str)> {
245         self.peek_pos += 1;
246         if self.peek_pos - 1 < self.stored.len() {
247             self.stored.get(self.peek_pos - 1)
248         } else if let Some(next) = self.iter.next() {
249             self.stored.push_back(next);
250             self.stored.back()
251         } else {
252             None
253         }
254     }
255 }
256
257 impl<'a> Iterator for PeekIter<'a> {
258     type Item = (TokenKind, &'a str);
259     fn next(&mut self) -> Option<Self::Item> {
260         self.peek_pos = 0;
261         if let Some(first) = self.stored.pop_front() { Some(first) } else { self.iter.next() }
262     }
263 }
264
265 /// Custom spans inserted into the source. Eg --scrape-examples uses this to highlight function calls
266 struct Decorations {
267     starts: Vec<(u32, &'static str)>,
268     ends: Vec<u32>,
269 }
270
271 impl Decorations {
272     fn new(info: DecorationInfo) -> Self {
273         // Extract tuples (start, end, kind) into separate sequences of (start, kind) and (end).
274         let (mut starts, mut ends): (Vec<_>, Vec<_>) = info
275             .0
276             .into_iter()
277             .flat_map(|(kind, ranges)| ranges.into_iter().map(move |(lo, hi)| ((lo, kind), hi)))
278             .unzip();
279
280         // Sort the sequences in document order.
281         starts.sort_by_key(|(lo, _)| *lo);
282         ends.sort();
283
284         Decorations { starts, ends }
285     }
286 }
287
288 /// Processes program tokens, classifying strings of text by highlighting
289 /// category (`Class`).
290 struct Classifier<'a> {
291     tokens: PeekIter<'a>,
292     in_attribute: bool,
293     in_macro: bool,
294     in_macro_nonterminal: bool,
295     edition: Edition,
296     byte_pos: u32,
297     file_span: Span,
298     src: &'a str,
299     decorations: Option<Decorations>,
300 }
301
302 impl<'a> Classifier<'a> {
303     /// Takes as argument the source code to HTML-ify, the rust edition to use and the source code
304     /// file span which will be used later on by the `span_correspondance_map`.
305     fn new(
306         src: &str,
307         edition: Edition,
308         file_span: Span,
309         decoration_info: Option<DecorationInfo>,
310     ) -> Classifier<'_> {
311         let tokens = PeekIter::new(TokenIter { src });
312         let decorations = decoration_info.map(Decorations::new);
313         Classifier {
314             tokens,
315             in_attribute: false,
316             in_macro: false,
317             in_macro_nonterminal: false,
318             edition,
319             byte_pos: 0,
320             file_span,
321             src,
322             decorations,
323         }
324     }
325
326     /// Convenient wrapper to create a [`Span`] from a position in the file.
327     fn new_span(&self, lo: u32, text: &str) -> Span {
328         let hi = lo + text.len() as u32;
329         let file_lo = self.file_span.lo();
330         self.file_span.with_lo(file_lo + BytePos(lo)).with_hi(file_lo + BytePos(hi))
331     }
332
333     /// Concatenate colons and idents as one when possible.
334     fn get_full_ident_path(&mut self) -> Vec<(TokenKind, usize, usize)> {
335         let start = self.byte_pos as usize;
336         let mut pos = start;
337         let mut has_ident = false;
338         let edition = self.edition;
339
340         loop {
341             let mut nb = 0;
342             while let Some((TokenKind::Colon, _)) = self.tokens.peek() {
343                 self.tokens.next();
344                 nb += 1;
345             }
346             // Ident path can start with "::" but if we already have content in the ident path,
347             // the "::" is mandatory.
348             if has_ident && nb == 0 {
349                 return vec![(TokenKind::Ident, start, pos)];
350             } else if nb != 0 && nb != 2 {
351                 if has_ident {
352                     return vec![(TokenKind::Ident, start, pos), (TokenKind::Colon, pos, pos + nb)];
353                 } else {
354                     return vec![(TokenKind::Colon, start, pos + nb)];
355                 }
356             }
357
358             if let Some((None, text)) = self.tokens.peek().map(|(token, text)| {
359                 if *token == TokenKind::Ident {
360                     let class = get_real_ident_class(text, edition, true);
361                     (class, text)
362                 } else {
363                     // Doesn't matter which Class we put in here...
364                     (Some(Class::Comment), text)
365                 }
366             }) {
367                 // We only "add" the colon if there is an ident behind.
368                 pos += text.len() + nb;
369                 has_ident = true;
370                 self.tokens.next();
371             } else if nb > 0 && has_ident {
372                 return vec![(TokenKind::Ident, start, pos), (TokenKind::Colon, pos, pos + nb)];
373             } else if nb > 0 {
374                 return vec![(TokenKind::Colon, start, start + nb)];
375             } else if has_ident {
376                 return vec![(TokenKind::Ident, start, pos)];
377             } else {
378                 return Vec::new();
379             }
380         }
381     }
382
383     /// Wraps the tokens iteration to ensure that the `byte_pos` is always correct.
384     ///
385     /// It returns the token's kind, the token as a string and its byte position in the source
386     /// string.
387     fn next(&mut self) -> Option<(TokenKind, &'a str, u32)> {
388         if let Some((kind, text)) = self.tokens.next() {
389             let before = self.byte_pos;
390             self.byte_pos += text.len() as u32;
391             Some((kind, text, before))
392         } else {
393             None
394         }
395     }
396
397     /// Exhausts the `Classifier` writing the output into `sink`.
398     ///
399     /// The general structure for this method is to iterate over each token,
400     /// possibly giving it an HTML span with a class specifying what flavor of
401     /// token is used.
402     fn highlight(mut self, sink: &mut dyn FnMut(Highlight<'a>)) {
403         loop {
404             if let Some(decs) = self.decorations.as_mut() {
405                 let byte_pos = self.byte_pos;
406                 let n_starts = decs.starts.iter().filter(|(i, _)| byte_pos >= *i).count();
407                 for (_, kind) in decs.starts.drain(0..n_starts) {
408                     sink(Highlight::EnterSpan { class: Class::Decoration(kind) });
409                 }
410
411                 let n_ends = decs.ends.iter().filter(|i| byte_pos >= **i).count();
412                 for _ in decs.ends.drain(0..n_ends) {
413                     sink(Highlight::ExitSpan);
414                 }
415             }
416
417             if self
418                 .tokens
419                 .peek()
420                 .map(|t| matches!(t.0, TokenKind::Colon | TokenKind::Ident))
421                 .unwrap_or(false)
422             {
423                 let tokens = self.get_full_ident_path();
424                 for (token, start, end) in &tokens {
425                     let text = &self.src[*start..*end];
426                     self.advance(*token, text, sink, *start as u32);
427                     self.byte_pos += text.len() as u32;
428                 }
429                 if !tokens.is_empty() {
430                     continue;
431                 }
432             }
433             if let Some((token, text, before)) = self.next() {
434                 self.advance(token, text, sink, before);
435             } else {
436                 break;
437             }
438         }
439     }
440
441     /// Single step of highlighting. This will classify `token`, but maybe also a couple of
442     /// following ones as well.
443     ///
444     /// `before` is the position of the given token in the `source` string and is used as "lo" byte
445     /// in case we want to try to generate a link for this token using the
446     /// `span_correspondance_map`.
447     fn advance(
448         &mut self,
449         token: TokenKind,
450         text: &'a str,
451         sink: &mut dyn FnMut(Highlight<'a>),
452         before: u32,
453     ) {
454         let lookahead = self.peek();
455         let no_highlight = |sink: &mut dyn FnMut(_)| sink(Highlight::Token { text, class: None });
456         let class = match token {
457             TokenKind::Whitespace => return no_highlight(sink),
458             TokenKind::LineComment { doc_style } | TokenKind::BlockComment { doc_style, .. } => {
459                 if doc_style.is_some() {
460                     Class::DocComment
461                 } else {
462                     Class::Comment
463                 }
464             }
465             // Consider this as part of a macro invocation if there was a
466             // leading identifier.
467             TokenKind::Bang if self.in_macro => {
468                 self.in_macro = false;
469                 sink(Highlight::Token { text, class: None });
470                 sink(Highlight::ExitSpan);
471                 return;
472             }
473
474             // Assume that '&' or '*' is the reference or dereference operator
475             // or a reference or pointer type. Unless, of course, it looks like
476             // a logical and or a multiplication operator: `&&` or `* `.
477             TokenKind::Star => match self.tokens.peek() {
478                 Some((TokenKind::Whitespace, _)) => Class::Op,
479                 Some((TokenKind::Ident, "mut")) => {
480                     self.next();
481                     sink(Highlight::Token { text: "*mut", class: Some(Class::RefKeyWord) });
482                     return;
483                 }
484                 Some((TokenKind::Ident, "const")) => {
485                     self.next();
486                     sink(Highlight::Token { text: "*const", class: Some(Class::RefKeyWord) });
487                     return;
488                 }
489                 _ => Class::RefKeyWord,
490             },
491             TokenKind::And => match self.tokens.peek() {
492                 Some((TokenKind::And, _)) => {
493                     self.next();
494                     sink(Highlight::Token { text: "&&", class: Some(Class::Op) });
495                     return;
496                 }
497                 Some((TokenKind::Eq, _)) => {
498                     self.next();
499                     sink(Highlight::Token { text: "&=", class: Some(Class::Op) });
500                     return;
501                 }
502                 Some((TokenKind::Whitespace, _)) => Class::Op,
503                 Some((TokenKind::Ident, "mut")) => {
504                     self.next();
505                     sink(Highlight::Token { text: "&mut", class: Some(Class::RefKeyWord) });
506                     return;
507                 }
508                 _ => Class::RefKeyWord,
509             },
510
511             // These can either be operators, or arrows.
512             TokenKind::Eq => match lookahead {
513                 Some(TokenKind::Eq) => {
514                     self.next();
515                     sink(Highlight::Token { text: "==", class: Some(Class::Op) });
516                     return;
517                 }
518                 Some(TokenKind::Gt) => {
519                     self.next();
520                     sink(Highlight::Token { text: "=>", class: None });
521                     return;
522                 }
523                 _ => Class::Op,
524             },
525             TokenKind::Minus if lookahead == Some(TokenKind::Gt) => {
526                 self.next();
527                 sink(Highlight::Token { text: "->", class: None });
528                 return;
529             }
530
531             // Other operators.
532             TokenKind::Minus
533             | TokenKind::Plus
534             | TokenKind::Or
535             | TokenKind::Slash
536             | TokenKind::Caret
537             | TokenKind::Percent
538             | TokenKind::Bang
539             | TokenKind::Lt
540             | TokenKind::Gt => Class::Op,
541
542             // Miscellaneous, no highlighting.
543             TokenKind::Dot
544             | TokenKind::Semi
545             | TokenKind::Comma
546             | TokenKind::OpenParen
547             | TokenKind::CloseParen
548             | TokenKind::OpenBrace
549             | TokenKind::CloseBrace
550             | TokenKind::OpenBracket
551             | TokenKind::At
552             | TokenKind::Tilde
553             | TokenKind::Colon
554             | TokenKind::Unknown => return no_highlight(sink),
555
556             TokenKind::Question => Class::QuestionMark,
557
558             TokenKind::Dollar => match lookahead {
559                 Some(TokenKind::Ident) => {
560                     self.in_macro_nonterminal = true;
561                     Class::MacroNonTerminal
562                 }
563                 _ => return no_highlight(sink),
564             },
565
566             // This might be the start of an attribute. We're going to want to
567             // continue highlighting it as an attribute until the ending ']' is
568             // seen, so skip out early. Down below we terminate the attribute
569             // span when we see the ']'.
570             TokenKind::Pound => {
571                 match lookahead {
572                     // Case 1: #![inner_attribute]
573                     Some(TokenKind::Bang) => {
574                         self.next();
575                         if let Some(TokenKind::OpenBracket) = self.peek() {
576                             self.in_attribute = true;
577                             sink(Highlight::EnterSpan { class: Class::Attribute });
578                         }
579                         sink(Highlight::Token { text: "#", class: None });
580                         sink(Highlight::Token { text: "!", class: None });
581                         return;
582                     }
583                     // Case 2: #[outer_attribute]
584                     Some(TokenKind::OpenBracket) => {
585                         self.in_attribute = true;
586                         sink(Highlight::EnterSpan { class: Class::Attribute });
587                     }
588                     _ => (),
589                 }
590                 return no_highlight(sink);
591             }
592             TokenKind::CloseBracket => {
593                 if self.in_attribute {
594                     self.in_attribute = false;
595                     sink(Highlight::Token { text: "]", class: None });
596                     sink(Highlight::ExitSpan);
597                     return;
598                 }
599                 return no_highlight(sink);
600             }
601             TokenKind::Literal { kind, .. } => match kind {
602                 // Text literals.
603                 LiteralKind::Byte { .. }
604                 | LiteralKind::Char { .. }
605                 | LiteralKind::Str { .. }
606                 | LiteralKind::ByteStr { .. }
607                 | LiteralKind::RawStr { .. }
608                 | LiteralKind::RawByteStr { .. } => Class::String,
609                 // Number literals.
610                 LiteralKind::Float { .. } | LiteralKind::Int { .. } => Class::Number,
611             },
612             TokenKind::Ident | TokenKind::RawIdent if lookahead == Some(TokenKind::Bang) => {
613                 self.in_macro = true;
614                 sink(Highlight::EnterSpan { class: Class::Macro });
615                 sink(Highlight::Token { text, class: None });
616                 return;
617             }
618             TokenKind::Ident => match get_real_ident_class(text, self.edition, false) {
619                 None => match text {
620                     "Option" | "Result" => Class::PreludeTy,
621                     "Some" | "None" | "Ok" | "Err" => Class::PreludeVal,
622                     // "union" is a weak keyword and is only considered as a keyword when declaring
623                     // a union type.
624                     "union" if self.check_if_is_union_keyword() => Class::KeyWord,
625                     _ if self.in_macro_nonterminal => {
626                         self.in_macro_nonterminal = false;
627                         Class::MacroNonTerminal
628                     }
629                     "self" | "Self" => Class::Self_(self.new_span(before, text)),
630                     _ => Class::Ident(self.new_span(before, text)),
631                 },
632                 Some(c) => c,
633             },
634             TokenKind::RawIdent | TokenKind::UnknownPrefix | TokenKind::InvalidIdent => {
635                 Class::Ident(self.new_span(before, text))
636             }
637             TokenKind::Lifetime { .. } => Class::Lifetime,
638         };
639         // Anything that didn't return above is the simple case where we the
640         // class just spans a single token, so we can use the `string` method.
641         sink(Highlight::Token { text, class: Some(class) });
642     }
643
644     fn peek(&mut self) -> Option<TokenKind> {
645         self.tokens.peek().map(|(token_kind, _text)| *token_kind)
646     }
647
648     fn check_if_is_union_keyword(&mut self) -> bool {
649         while let Some(kind) = self.tokens.peek_next().map(|(token_kind, _text)| token_kind) {
650             if *kind == TokenKind::Whitespace {
651                 continue;
652             }
653             return *kind == TokenKind::Ident;
654         }
655         false
656     }
657 }
658
659 /// Called when we start processing a span of text that should be highlighted.
660 /// The `Class` argument specifies how it should be highlighted.
661 fn enter_span(out: &mut Buffer, klass: Class) {
662     write!(out, "<span class=\"{}\">", klass.as_html());
663 }
664
665 /// Called at the end of a span of highlighted text.
666 fn exit_span(out: &mut Buffer) {
667     out.write_str("</span>");
668 }
669
670 /// Called for a span of text. If the text should be highlighted differently
671 /// from the surrounding text, then the `Class` argument will be a value other
672 /// than `None`.
673 ///
674 /// The following sequences of callbacks are equivalent:
675 /// ```plain
676 ///     enter_span(Foo), string("text", None), exit_span()
677 ///     string("text", Foo)
678 /// ```
679 ///
680 /// The latter can be thought of as a shorthand for the former, which is more
681 /// flexible.
682 ///
683 /// Note that if `context` is not `None` and that the given `klass` contains a `Span`, the function
684 /// will then try to find this `span` in the `span_correspondance_map`. If found, it'll then
685 /// generate a link for this element (which corresponds to where its definition is located).
686 fn string<T: Display>(
687     out: &mut Buffer,
688     text: T,
689     klass: Option<Class>,
690     context_info: &Option<ContextInfo<'_, '_, '_>>,
691 ) {
692     let klass = match klass {
693         None => return write!(out, "{}", text),
694         Some(klass) => klass,
695     };
696     let def_span = match klass.get_span() {
697         Some(d) => d,
698         None => {
699             write!(out, "<span class=\"{}\">{}</span>", klass.as_html(), text);
700             return;
701         }
702     };
703     let mut text_s = text.to_string();
704     if text_s.contains("::") {
705         text_s = text_s.split("::").intersperse("::").fold(String::new(), |mut path, t| {
706             match t {
707                 "self" | "Self" => write!(
708                     &mut path,
709                     "<span class=\"{}\">{}</span>",
710                     Class::Self_(DUMMY_SP).as_html(),
711                     t
712                 ),
713                 "crate" | "super" => {
714                     write!(&mut path, "<span class=\"{}\">{}</span>", Class::KeyWord.as_html(), t)
715                 }
716                 t => write!(&mut path, "{}", t),
717             }
718             .expect("Failed to build source HTML path");
719             path
720         });
721     }
722     if let Some(context_info) = context_info {
723         if let Some(href) =
724             context_info.context.shared.span_correspondance_map.get(&def_span).and_then(|href| {
725                 let context = context_info.context;
726                 // FIXME: later on, it'd be nice to provide two links (if possible) for all items:
727                 // one to the documentation page and one to the source definition.
728                 // FIXME: currently, external items only generate a link to their documentation,
729                 // a link to their definition can be generated using this:
730                 // https://github.com/rust-lang/rust/blob/60f1a2fc4b535ead9c85ce085fdce49b1b097531/src/librustdoc/html/render/context.rs#L315-L338
731                 match href {
732                     LinkFromSrc::Local(span) => context
733                         .href_from_span(*span, true)
734                         .map(|s| format!("{}{}", context_info.root_path, s)),
735                     LinkFromSrc::External(def_id) => {
736                         format::href_with_root_path(*def_id, context, Some(context_info.root_path))
737                             .ok()
738                             .map(|(url, _, _)| url)
739                     }
740                     LinkFromSrc::Primitive(prim) => format::href_with_root_path(
741                         PrimitiveType::primitive_locations(context.tcx())[prim],
742                         context,
743                         Some(context_info.root_path),
744                     )
745                     .ok()
746                     .map(|(url, _, _)| url),
747                 }
748             })
749         {
750             write!(out, "<a class=\"{}\" href=\"{}\">{}</a>", klass.as_html(), href, text_s);
751             return;
752         }
753     }
754     write!(out, "<span class=\"{}\">{}</span>", klass.as_html(), text_s);
755 }
756
757 #[cfg(test)]
758 mod tests;