]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/highlight.rs
Auto merge of #101410 - dingxiangfei2009:fix-let-else-scoping, r=jackh726
[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 pub(crate) struct HrefContext<'a, 'b, 'c> {
26     pub(crate) context: &'a Context<'b>,
27     /// This span contains the current file we're going through.
28     pub(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     pub(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 #[derive(Default)]
37 pub(crate) struct DecorationInfo(pub(crate) FxHashMap<&'static str, Vec<(u32, u32)>>);
38
39 #[derive(Eq, PartialEq, Clone, Copy)]
40 pub(crate) enum Tooltip {
41     Ignore,
42     CompileFail,
43     ShouldPanic,
44     Edition(Edition),
45     None,
46 }
47
48 /// Highlights `src` as an inline example, returning the HTML output.
49 pub(crate) fn render_example_with_highlighting(
50     src: &str,
51     out: &mut Buffer,
52     tooltip: Tooltip,
53     playground_button: Option<&str>,
54 ) {
55     write_header(out, "rust-example-rendered", None, tooltip);
56     write_code(out, src, None, None);
57     write_footer(out, playground_button);
58 }
59
60 /// Highlights `src` as a macro, returning the HTML output.
61 pub(crate) fn render_macro_with_highlighting(src: &str, out: &mut Buffer) {
62     write_header(out, "macro", None, Tooltip::None);
63     write_code(out, src, None, None);
64     write_footer(out, None);
65 }
66
67 /// Highlights `src` as a source code page, returning the HTML output.
68 pub(crate) fn render_source_with_highlighting(
69     src: &str,
70     out: &mut Buffer,
71     line_numbers: Buffer,
72     href_context: HrefContext<'_, '_, '_>,
73     decoration_info: DecorationInfo,
74 ) {
75     write_header(out, "", Some(line_numbers), Tooltip::None);
76     write_code(out, src, Some(href_context), Some(decoration_info));
77     write_footer(out, None);
78 }
79
80 fn write_header(out: &mut Buffer, class: &str, extra_content: Option<Buffer>, tooltip: Tooltip) {
81     write!(
82         out,
83         "<div class=\"example-wrap{}\">",
84         match tooltip {
85             Tooltip::Ignore => " ignore",
86             Tooltip::CompileFail => " compile_fail",
87             Tooltip::ShouldPanic => " should_panic",
88             Tooltip::Edition(_) => " edition",
89             Tooltip::None => "",
90         },
91     );
92
93     if tooltip != Tooltip::None {
94         write!(
95             out,
96             "<div class='tooltip'{}>ⓘ</div>",
97             if let Tooltip::Edition(edition_info) = tooltip {
98                 format!(" data-edition=\"{}\"", edition_info)
99             } else {
100                 String::new()
101             },
102         );
103     }
104
105     if let Some(extra) = extra_content {
106         out.push_buffer(extra);
107     }
108     if class.is_empty() {
109         write!(out, "<pre class=\"rust\">");
110     } else {
111         write!(out, "<pre class=\"rust {class}\">");
112     }
113     write!(out, "<code>");
114 }
115
116 /// Check if two `Class` can be merged together. In the following rules, "unclassified" means `None`
117 /// basically (since it's `Option<Class>`). The following rules apply:
118 ///
119 /// * If two `Class` have the same variant, then they can be merged.
120 /// * If the other `Class` is unclassified and only contains white characters (backline,
121 ///   whitespace, etc), it can be merged.
122 /// * `Class::Ident` is considered the same as unclassified (because it doesn't have an associated
123 ///    CSS class).
124 fn can_merge(class1: Option<Class>, class2: Option<Class>, text: &str) -> bool {
125     match (class1, class2) {
126         (Some(c1), Some(c2)) => c1.is_equal_to(c2),
127         (Some(Class::Ident(_)), None) | (None, Some(Class::Ident(_))) => true,
128         (Some(_), None) | (None, Some(_)) => text.trim().is_empty(),
129         (None, None) => true,
130     }
131 }
132
133 /// This type is used as a conveniency to prevent having to pass all its fields as arguments into
134 /// the various functions (which became its methods).
135 struct TokenHandler<'a, 'b, 'c, 'd, 'e> {
136     out: &'a mut Buffer,
137     /// It contains the closing tag and the associated `Class`.
138     closing_tags: Vec<(&'static str, Class)>,
139     /// This is used because we don't automatically generate the closing tag on `ExitSpan` in
140     /// case an `EnterSpan` event with the same class follows.
141     pending_exit_span: Option<Class>,
142     /// `current_class` and `pending_elems` are used to group HTML elements with same `class`
143     /// attributes to reduce the DOM size.
144     current_class: Option<Class>,
145     /// We need to keep the `Class` for each element because it could contain a `Span` which is
146     /// used to generate links.
147     pending_elems: Vec<(&'b str, Option<Class>)>,
148     href_context: Option<HrefContext<'c, 'd, 'e>>,
149 }
150
151 impl<'a, 'b, 'c, 'd, 'e> TokenHandler<'a, 'b, 'c, 'd, 'e> {
152     fn handle_exit_span(&mut self) {
153         // We can't get the last `closing_tags` element using `pop()` because `closing_tags` is
154         // being used in `write_pending_elems`.
155         let class = self.closing_tags.last().expect("ExitSpan without EnterSpan").1;
156         // We flush everything just in case...
157         self.write_pending_elems(Some(class));
158
159         exit_span(self.out, self.closing_tags.pop().expect("ExitSpan without EnterSpan").0);
160         self.pending_exit_span = None;
161     }
162
163     /// Write all the pending elements sharing a same (or at mergeable) `Class`.
164     ///
165     /// If there is a "parent" (if a `EnterSpan` event was encountered) and the parent can be merged
166     /// with the elements' class, then we simply write the elements since the `ExitSpan` event will
167     /// close the tag.
168     ///
169     /// Otherwise, if there is only one pending element, we let the `string` function handle both
170     /// opening and closing the tag, otherwise we do it into this function.
171     ///
172     /// It returns `true` if `current_class` must be set to `None` afterwards.
173     fn write_pending_elems(&mut self, current_class: Option<Class>) -> bool {
174         if self.pending_elems.is_empty() {
175             return false;
176         }
177         if let Some((_, parent_class)) = self.closing_tags.last() &&
178             can_merge(current_class, Some(*parent_class), "")
179         {
180             for (text, class) in self.pending_elems.iter() {
181                 string(self.out, Escape(text), *class, &self.href_context, false);
182             }
183         } else {
184             // We only want to "open" the tag ourselves if we have more than one pending and if the
185             // current parent tag is not the same as our pending content.
186             let close_tag = if self.pending_elems.len() > 1 && current_class.is_some() {
187                 Some(enter_span(self.out, current_class.unwrap(), &self.href_context))
188             } else {
189                 None
190             };
191             for (text, class) in self.pending_elems.iter() {
192                 string(self.out, Escape(text), *class, &self.href_context, close_tag.is_none());
193             }
194             if let Some(close_tag) = close_tag {
195                 exit_span(self.out, close_tag);
196             }
197         }
198         self.pending_elems.clear();
199         true
200     }
201 }
202
203 impl<'a, 'b, 'c, 'd, 'e> Drop for TokenHandler<'a, 'b, 'c, 'd, 'e> {
204     /// When leaving, we need to flush all pending data to not have missing content.
205     fn drop(&mut self) {
206         if self.pending_exit_span.is_some() {
207             self.handle_exit_span();
208         } else {
209             self.write_pending_elems(self.current_class);
210         }
211     }
212 }
213
214 /// Convert the given `src` source code into HTML by adding classes for highlighting.
215 ///
216 /// This code is used to render code blocks (in the documentation) as well as the source code pages.
217 ///
218 /// Some explanations on the last arguments:
219 ///
220 /// In case we are rendering a code block and not a source code file, `href_context` will be `None`.
221 /// To put it more simply: if `href_context` is `None`, the code won't try to generate links to an
222 /// item definition.
223 ///
224 /// More explanations about spans and how we use them here are provided in the
225 fn write_code(
226     out: &mut Buffer,
227     src: &str,
228     href_context: Option<HrefContext<'_, '_, '_>>,
229     decoration_info: Option<DecorationInfo>,
230 ) {
231     // This replace allows to fix how the code source with DOS backline characters is displayed.
232     let src = src.replace("\r\n", "\n");
233     let mut token_handler = TokenHandler {
234         out,
235         closing_tags: Vec::new(),
236         pending_exit_span: None,
237         current_class: None,
238         pending_elems: Vec::new(),
239         href_context,
240     };
241
242     Classifier::new(
243         &src,
244         token_handler.href_context.as_ref().map(|c| c.file_span).unwrap_or(DUMMY_SP),
245         decoration_info,
246     )
247     .highlight(&mut |highlight| {
248         match highlight {
249             Highlight::Token { text, class } => {
250                 // If we received a `ExitSpan` event and then have a non-compatible `Class`, we
251                 // need to close the `<span>`.
252                 let need_current_class_update = if let Some(pending) = token_handler.pending_exit_span &&
253                     !can_merge(Some(pending), class, text) {
254                         token_handler.handle_exit_span();
255                         true
256                 // If the two `Class` are different, time to flush the current content and start
257                 // a new one.
258                 } else if !can_merge(token_handler.current_class, class, text) {
259                     token_handler.write_pending_elems(token_handler.current_class);
260                     true
261                 } else {
262                     token_handler.current_class.is_none()
263                 };
264
265                 if need_current_class_update {
266                     token_handler.current_class = class.map(Class::dummy);
267                 }
268                 token_handler.pending_elems.push((text, class));
269             }
270             Highlight::EnterSpan { class } => {
271                 let mut should_add = true;
272                 if let Some(pending_exit_span) = token_handler.pending_exit_span {
273                     if class.is_equal_to(pending_exit_span) {
274                         should_add = false;
275                     } else {
276                         token_handler.handle_exit_span();
277                     }
278                 } else {
279                     // We flush everything just in case...
280                     if token_handler.write_pending_elems(token_handler.current_class) {
281                         token_handler.current_class = None;
282                     }
283                 }
284                 if should_add {
285                     let closing_tag = enter_span(token_handler.out, class, &token_handler.href_context);
286                     token_handler.closing_tags.push((closing_tag, class));
287                 }
288
289                 token_handler.current_class = None;
290                 token_handler.pending_exit_span = None;
291             }
292             Highlight::ExitSpan => {
293                 token_handler.current_class = None;
294                 token_handler.pending_exit_span =
295                     Some(token_handler.closing_tags.last().as_ref().expect("ExitSpan without EnterSpan").1);
296             }
297         };
298     });
299 }
300
301 fn write_footer(out: &mut Buffer, playground_button: Option<&str>) {
302     writeln!(out, "</code></pre>{}</div>", playground_button.unwrap_or_default());
303 }
304
305 /// How a span of text is classified. Mostly corresponds to token kinds.
306 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
307 enum Class {
308     Comment,
309     DocComment,
310     Attribute,
311     KeyWord,
312     /// Keywords that do pointer/reference stuff.
313     RefKeyWord,
314     Self_(Span),
315     Macro(Span),
316     MacroNonTerminal,
317     String,
318     Number,
319     Bool,
320     /// `Ident` isn't rendered in the HTML but we still need it for the `Span` it contains.
321     Ident(Span),
322     Lifetime,
323     PreludeTy,
324     PreludeVal,
325     QuestionMark,
326     Decoration(&'static str),
327 }
328
329 impl Class {
330     /// It is only looking at the variant, not the variant content.
331     ///
332     /// It is used mostly to group multiple similar HTML elements into one `<span>` instead of
333     /// multiple ones.
334     fn is_equal_to(self, other: Self) -> bool {
335         match (self, other) {
336             (Self::Self_(_), Self::Self_(_))
337             | (Self::Macro(_), Self::Macro(_))
338             | (Self::Ident(_), Self::Ident(_)) => true,
339             (Self::Decoration(c1), Self::Decoration(c2)) => c1 == c2,
340             (x, y) => x == y,
341         }
342     }
343
344     /// If `self` contains a `Span`, it'll be replaced with `DUMMY_SP` to prevent creating links
345     /// on "empty content" (because of the attributes merge).
346     fn dummy(self) -> Self {
347         match self {
348             Self::Self_(_) => Self::Self_(DUMMY_SP),
349             Self::Macro(_) => Self::Macro(DUMMY_SP),
350             Self::Ident(_) => Self::Ident(DUMMY_SP),
351             s => s,
352         }
353     }
354
355     /// Returns the css class expected by rustdoc for each `Class`.
356     fn as_html(self) -> &'static str {
357         match self {
358             Class::Comment => "comment",
359             Class::DocComment => "doccomment",
360             Class::Attribute => "attribute",
361             Class::KeyWord => "kw",
362             Class::RefKeyWord => "kw-2",
363             Class::Self_(_) => "self",
364             Class::Macro(_) => "macro",
365             Class::MacroNonTerminal => "macro-nonterminal",
366             Class::String => "string",
367             Class::Number => "number",
368             Class::Bool => "bool-val",
369             Class::Ident(_) => "",
370             Class::Lifetime => "lifetime",
371             Class::PreludeTy => "prelude-ty",
372             Class::PreludeVal => "prelude-val",
373             Class::QuestionMark => "question-mark",
374             Class::Decoration(kind) => kind,
375         }
376     }
377
378     /// In case this is an item which can be converted into a link to a definition, it'll contain
379     /// a "span" (a tuple representing `(lo, hi)` equivalent of `Span`).
380     fn get_span(self) -> Option<Span> {
381         match self {
382             Self::Ident(sp) | Self::Self_(sp) | Self::Macro(sp) => Some(sp),
383             Self::Comment
384             | Self::DocComment
385             | Self::Attribute
386             | Self::KeyWord
387             | Self::RefKeyWord
388             | Self::MacroNonTerminal
389             | Self::String
390             | Self::Number
391             | Self::Bool
392             | Self::Lifetime
393             | Self::PreludeTy
394             | Self::PreludeVal
395             | Self::QuestionMark
396             | Self::Decoration(_) => None,
397         }
398     }
399 }
400
401 enum Highlight<'a> {
402     Token { text: &'a str, class: Option<Class> },
403     EnterSpan { class: Class },
404     ExitSpan,
405 }
406
407 struct TokenIter<'a> {
408     src: &'a str,
409 }
410
411 impl<'a> Iterator for TokenIter<'a> {
412     type Item = (TokenKind, &'a str);
413     fn next(&mut self) -> Option<(TokenKind, &'a str)> {
414         if self.src.is_empty() {
415             return None;
416         }
417         let token = rustc_lexer::first_token(self.src);
418         let (text, rest) = self.src.split_at(token.len as usize);
419         self.src = rest;
420         Some((token.kind, text))
421     }
422 }
423
424 /// Classifies into identifier class; returns `None` if this is a non-keyword identifier.
425 fn get_real_ident_class(text: &str, allow_path_keywords: bool) -> Option<Class> {
426     let ignore: &[&str] =
427         if allow_path_keywords { &["self", "Self", "super", "crate"] } else { &["self", "Self"] };
428     if ignore.iter().any(|k| *k == text) {
429         return None;
430     }
431     Some(match text {
432         "ref" | "mut" => Class::RefKeyWord,
433         "false" | "true" => Class::Bool,
434         _ if Symbol::intern(text).is_reserved(|| Edition::Edition2021) => Class::KeyWord,
435         _ => return None,
436     })
437 }
438
439 /// This iterator comes from the same idea than "Peekable" except that it allows to "peek" more than
440 /// just the next item by using `peek_next`. The `peek` method always returns the next item after
441 /// the current one whereas `peek_next` will return the next item after the last one peeked.
442 ///
443 /// You can use both `peek` and `peek_next` at the same time without problem.
444 struct PeekIter<'a> {
445     stored: VecDeque<(TokenKind, &'a str)>,
446     /// This position is reinitialized when using `next`. It is used in `peek_next`.
447     peek_pos: usize,
448     iter: TokenIter<'a>,
449 }
450
451 impl<'a> PeekIter<'a> {
452     fn new(iter: TokenIter<'a>) -> Self {
453         Self { stored: VecDeque::new(), peek_pos: 0, iter }
454     }
455     /// Returns the next item after the current one. It doesn't interfere with `peek_next` output.
456     fn peek(&mut self) -> Option<&(TokenKind, &'a str)> {
457         if self.stored.is_empty() {
458             if let Some(next) = self.iter.next() {
459                 self.stored.push_back(next);
460             }
461         }
462         self.stored.front()
463     }
464     /// Returns the next item after the last one peeked. It doesn't interfere with `peek` output.
465     fn peek_next(&mut self) -> Option<&(TokenKind, &'a str)> {
466         self.peek_pos += 1;
467         if self.peek_pos - 1 < self.stored.len() {
468             self.stored.get(self.peek_pos - 1)
469         } else if let Some(next) = self.iter.next() {
470             self.stored.push_back(next);
471             self.stored.back()
472         } else {
473             None
474         }
475     }
476 }
477
478 impl<'a> Iterator for PeekIter<'a> {
479     type Item = (TokenKind, &'a str);
480     fn next(&mut self) -> Option<Self::Item> {
481         self.peek_pos = 0;
482         if let Some(first) = self.stored.pop_front() { Some(first) } else { self.iter.next() }
483     }
484 }
485
486 /// Custom spans inserted into the source. Eg --scrape-examples uses this to highlight function calls
487 struct Decorations {
488     starts: Vec<(u32, &'static str)>,
489     ends: Vec<u32>,
490 }
491
492 impl Decorations {
493     fn new(info: DecorationInfo) -> Self {
494         // Extract tuples (start, end, kind) into separate sequences of (start, kind) and (end).
495         let (mut starts, mut ends): (Vec<_>, Vec<_>) = info
496             .0
497             .into_iter()
498             .flat_map(|(kind, ranges)| ranges.into_iter().map(move |(lo, hi)| ((lo, kind), hi)))
499             .unzip();
500
501         // Sort the sequences in document order.
502         starts.sort_by_key(|(lo, _)| *lo);
503         ends.sort();
504
505         Decorations { starts, ends }
506     }
507 }
508
509 /// Processes program tokens, classifying strings of text by highlighting
510 /// category (`Class`).
511 struct Classifier<'a> {
512     tokens: PeekIter<'a>,
513     in_attribute: bool,
514     in_macro: bool,
515     in_macro_nonterminal: bool,
516     byte_pos: u32,
517     file_span: Span,
518     src: &'a str,
519     decorations: Option<Decorations>,
520 }
521
522 impl<'a> Classifier<'a> {
523     /// Takes as argument the source code to HTML-ify, the rust edition to use and the source code
524     /// file span which will be used later on by the `span_correspondance_map`.
525     fn new(src: &str, file_span: Span, decoration_info: Option<DecorationInfo>) -> Classifier<'_> {
526         let tokens = PeekIter::new(TokenIter { src });
527         let decorations = decoration_info.map(Decorations::new);
528         Classifier {
529             tokens,
530             in_attribute: false,
531             in_macro: false,
532             in_macro_nonterminal: false,
533             byte_pos: 0,
534             file_span,
535             src,
536             decorations,
537         }
538     }
539
540     /// Convenient wrapper to create a [`Span`] from a position in the file.
541     fn new_span(&self, lo: u32, text: &str) -> Span {
542         let hi = lo + text.len() as u32;
543         let file_lo = self.file_span.lo();
544         self.file_span.with_lo(file_lo + BytePos(lo)).with_hi(file_lo + BytePos(hi))
545     }
546
547     /// Concatenate colons and idents as one when possible.
548     fn get_full_ident_path(&mut self) -> Vec<(TokenKind, usize, usize)> {
549         let start = self.byte_pos as usize;
550         let mut pos = start;
551         let mut has_ident = false;
552
553         loop {
554             let mut nb = 0;
555             while let Some((TokenKind::Colon, _)) = self.tokens.peek() {
556                 self.tokens.next();
557                 nb += 1;
558             }
559             // Ident path can start with "::" but if we already have content in the ident path,
560             // the "::" is mandatory.
561             if has_ident && nb == 0 {
562                 return vec![(TokenKind::Ident, start, pos)];
563             } else if nb != 0 && nb != 2 {
564                 if has_ident {
565                     return vec![(TokenKind::Ident, start, pos), (TokenKind::Colon, pos, pos + nb)];
566                 } else {
567                     return vec![(TokenKind::Colon, start, pos + nb)];
568                 }
569             }
570
571             if let Some((None, text)) = self.tokens.peek().map(|(token, text)| {
572                 if *token == TokenKind::Ident {
573                     let class = get_real_ident_class(text, true);
574                     (class, text)
575                 } else {
576                     // Doesn't matter which Class we put in here...
577                     (Some(Class::Comment), text)
578                 }
579             }) {
580                 // We only "add" the colon if there is an ident behind.
581                 pos += text.len() + nb;
582                 has_ident = true;
583                 self.tokens.next();
584             } else if nb > 0 && has_ident {
585                 return vec![(TokenKind::Ident, start, pos), (TokenKind::Colon, pos, pos + nb)];
586             } else if nb > 0 {
587                 return vec![(TokenKind::Colon, start, start + nb)];
588             } else if has_ident {
589                 return vec![(TokenKind::Ident, start, pos)];
590             } else {
591                 return Vec::new();
592             }
593         }
594     }
595
596     /// Wraps the tokens iteration to ensure that the `byte_pos` is always correct.
597     ///
598     /// It returns the token's kind, the token as a string and its byte position in the source
599     /// string.
600     fn next(&mut self) -> Option<(TokenKind, &'a str, u32)> {
601         if let Some((kind, text)) = self.tokens.next() {
602             let before = self.byte_pos;
603             self.byte_pos += text.len() as u32;
604             Some((kind, text, before))
605         } else {
606             None
607         }
608     }
609
610     /// Exhausts the `Classifier` writing the output into `sink`.
611     ///
612     /// The general structure for this method is to iterate over each token,
613     /// possibly giving it an HTML span with a class specifying what flavor of
614     /// token is used.
615     fn highlight(mut self, sink: &mut dyn FnMut(Highlight<'a>)) {
616         loop {
617             if let Some(decs) = self.decorations.as_mut() {
618                 let byte_pos = self.byte_pos;
619                 let n_starts = decs.starts.iter().filter(|(i, _)| byte_pos >= *i).count();
620                 for (_, kind) in decs.starts.drain(0..n_starts) {
621                     sink(Highlight::EnterSpan { class: Class::Decoration(kind) });
622                 }
623
624                 let n_ends = decs.ends.iter().filter(|i| byte_pos >= **i).count();
625                 for _ in decs.ends.drain(0..n_ends) {
626                     sink(Highlight::ExitSpan);
627                 }
628             }
629
630             if self
631                 .tokens
632                 .peek()
633                 .map(|t| matches!(t.0, TokenKind::Colon | TokenKind::Ident))
634                 .unwrap_or(false)
635             {
636                 let tokens = self.get_full_ident_path();
637                 for (token, start, end) in &tokens {
638                     let text = &self.src[*start..*end];
639                     self.advance(*token, text, sink, *start as u32);
640                     self.byte_pos += text.len() as u32;
641                 }
642                 if !tokens.is_empty() {
643                     continue;
644                 }
645             }
646             if let Some((token, text, before)) = self.next() {
647                 self.advance(token, text, sink, before);
648             } else {
649                 break;
650             }
651         }
652     }
653
654     /// Single step of highlighting. This will classify `token`, but maybe also a couple of
655     /// following ones as well.
656     ///
657     /// `before` is the position of the given token in the `source` string and is used as "lo" byte
658     /// in case we want to try to generate a link for this token using the
659     /// `span_correspondance_map`.
660     fn advance(
661         &mut self,
662         token: TokenKind,
663         text: &'a str,
664         sink: &mut dyn FnMut(Highlight<'a>),
665         before: u32,
666     ) {
667         let lookahead = self.peek();
668         let no_highlight = |sink: &mut dyn FnMut(_)| sink(Highlight::Token { text, class: None });
669         let class = match token {
670             TokenKind::Whitespace => return no_highlight(sink),
671             TokenKind::LineComment { doc_style } | TokenKind::BlockComment { doc_style, .. } => {
672                 if doc_style.is_some() {
673                     Class::DocComment
674                 } else {
675                     Class::Comment
676                 }
677             }
678             // Consider this as part of a macro invocation if there was a
679             // leading identifier.
680             TokenKind::Bang if self.in_macro => {
681                 self.in_macro = false;
682                 sink(Highlight::Token { text, class: None });
683                 sink(Highlight::ExitSpan);
684                 return;
685             }
686
687             // Assume that '&' or '*' is the reference or dereference operator
688             // or a reference or pointer type. Unless, of course, it looks like
689             // a logical and or a multiplication operator: `&&` or `* `.
690             TokenKind::Star => match self.tokens.peek() {
691                 Some((TokenKind::Whitespace, _)) => return no_highlight(sink),
692                 Some((TokenKind::Ident, "mut")) => {
693                     self.next();
694                     sink(Highlight::Token { text: "*mut", class: Some(Class::RefKeyWord) });
695                     return;
696                 }
697                 Some((TokenKind::Ident, "const")) => {
698                     self.next();
699                     sink(Highlight::Token { text: "*const", class: Some(Class::RefKeyWord) });
700                     return;
701                 }
702                 _ => Class::RefKeyWord,
703             },
704             TokenKind::And => match self.tokens.peek() {
705                 Some((TokenKind::And, _)) => {
706                     self.next();
707                     sink(Highlight::Token { text: "&&", class: None });
708                     return;
709                 }
710                 Some((TokenKind::Eq, _)) => {
711                     self.next();
712                     sink(Highlight::Token { text: "&=", class: None });
713                     return;
714                 }
715                 Some((TokenKind::Whitespace, _)) => return no_highlight(sink),
716                 Some((TokenKind::Ident, "mut")) => {
717                     self.next();
718                     sink(Highlight::Token { text: "&mut", class: Some(Class::RefKeyWord) });
719                     return;
720                 }
721                 _ => Class::RefKeyWord,
722             },
723
724             // These can either be operators, or arrows.
725             TokenKind::Eq => match lookahead {
726                 Some(TokenKind::Eq) => {
727                     self.next();
728                     sink(Highlight::Token { text: "==", class: None });
729                     return;
730                 }
731                 Some(TokenKind::Gt) => {
732                     self.next();
733                     sink(Highlight::Token { text: "=>", class: None });
734                     return;
735                 }
736                 _ => return no_highlight(sink),
737             },
738             TokenKind::Minus if lookahead == Some(TokenKind::Gt) => {
739                 self.next();
740                 sink(Highlight::Token { text: "->", class: None });
741                 return;
742             }
743
744             // Other operators.
745             TokenKind::Minus
746             | TokenKind::Plus
747             | TokenKind::Or
748             | TokenKind::Slash
749             | TokenKind::Caret
750             | TokenKind::Percent
751             | TokenKind::Bang
752             | TokenKind::Lt
753             | TokenKind::Gt => return no_highlight(sink),
754
755             // Miscellaneous, no highlighting.
756             TokenKind::Dot
757             | TokenKind::Semi
758             | TokenKind::Comma
759             | TokenKind::OpenParen
760             | TokenKind::CloseParen
761             | TokenKind::OpenBrace
762             | TokenKind::CloseBrace
763             | TokenKind::OpenBracket
764             | TokenKind::At
765             | TokenKind::Tilde
766             | TokenKind::Colon
767             | TokenKind::Unknown => return no_highlight(sink),
768
769             TokenKind::Question => Class::QuestionMark,
770
771             TokenKind::Dollar => match lookahead {
772                 Some(TokenKind::Ident) => {
773                     self.in_macro_nonterminal = true;
774                     Class::MacroNonTerminal
775                 }
776                 _ => return no_highlight(sink),
777             },
778
779             // This might be the start of an attribute. We're going to want to
780             // continue highlighting it as an attribute until the ending ']' is
781             // seen, so skip out early. Down below we terminate the attribute
782             // span when we see the ']'.
783             TokenKind::Pound => {
784                 match lookahead {
785                     // Case 1: #![inner_attribute]
786                     Some(TokenKind::Bang) => {
787                         self.next();
788                         if let Some(TokenKind::OpenBracket) = self.peek() {
789                             self.in_attribute = true;
790                             sink(Highlight::EnterSpan { class: Class::Attribute });
791                         }
792                         sink(Highlight::Token { text: "#", class: None });
793                         sink(Highlight::Token { text: "!", class: None });
794                         return;
795                     }
796                     // Case 2: #[outer_attribute]
797                     Some(TokenKind::OpenBracket) => {
798                         self.in_attribute = true;
799                         sink(Highlight::EnterSpan { class: Class::Attribute });
800                     }
801                     _ => (),
802                 }
803                 return no_highlight(sink);
804             }
805             TokenKind::CloseBracket => {
806                 if self.in_attribute {
807                     self.in_attribute = false;
808                     sink(Highlight::Token { text: "]", class: None });
809                     sink(Highlight::ExitSpan);
810                     return;
811                 }
812                 return no_highlight(sink);
813             }
814             TokenKind::Literal { kind, .. } => match kind {
815                 // Text literals.
816                 LiteralKind::Byte { .. }
817                 | LiteralKind::Char { .. }
818                 | LiteralKind::Str { .. }
819                 | LiteralKind::ByteStr { .. }
820                 | LiteralKind::RawStr { .. }
821                 | LiteralKind::RawByteStr { .. } => Class::String,
822                 // Number literals.
823                 LiteralKind::Float { .. } | LiteralKind::Int { .. } => Class::Number,
824             },
825             TokenKind::Ident | TokenKind::RawIdent if lookahead == Some(TokenKind::Bang) => {
826                 self.in_macro = true;
827                 sink(Highlight::EnterSpan { class: Class::Macro(self.new_span(before, text)) });
828                 sink(Highlight::Token { text, class: None });
829                 return;
830             }
831             TokenKind::Ident => match get_real_ident_class(text, false) {
832                 None => match text {
833                     "Option" | "Result" => Class::PreludeTy,
834                     "Some" | "None" | "Ok" | "Err" => Class::PreludeVal,
835                     // "union" is a weak keyword and is only considered as a keyword when declaring
836                     // a union type.
837                     "union" if self.check_if_is_union_keyword() => Class::KeyWord,
838                     _ if self.in_macro_nonterminal => {
839                         self.in_macro_nonterminal = false;
840                         Class::MacroNonTerminal
841                     }
842                     "self" | "Self" => Class::Self_(self.new_span(before, text)),
843                     _ => Class::Ident(self.new_span(before, text)),
844                 },
845                 Some(c) => c,
846             },
847             TokenKind::RawIdent | TokenKind::UnknownPrefix | TokenKind::InvalidIdent => {
848                 Class::Ident(self.new_span(before, text))
849             }
850             TokenKind::Lifetime { .. } => Class::Lifetime,
851         };
852         // Anything that didn't return above is the simple case where we the
853         // class just spans a single token, so we can use the `string` method.
854         sink(Highlight::Token { text, class: Some(class) });
855     }
856
857     fn peek(&mut self) -> Option<TokenKind> {
858         self.tokens.peek().map(|(token_kind, _text)| *token_kind)
859     }
860
861     fn check_if_is_union_keyword(&mut self) -> bool {
862         while let Some(kind) = self.tokens.peek_next().map(|(token_kind, _text)| token_kind) {
863             if *kind == TokenKind::Whitespace {
864                 continue;
865             }
866             return *kind == TokenKind::Ident;
867         }
868         false
869     }
870 }
871
872 /// Called when we start processing a span of text that should be highlighted.
873 /// The `Class` argument specifies how it should be highlighted.
874 fn enter_span(
875     out: &mut Buffer,
876     klass: Class,
877     href_context: &Option<HrefContext<'_, '_, '_>>,
878 ) -> &'static str {
879     string_without_closing_tag(out, "", Some(klass), href_context, true).expect(
880         "internal error: enter_span was called with Some(klass) but did not return a \
881             closing HTML tag",
882     )
883 }
884
885 /// Called at the end of a span of highlighted text.
886 fn exit_span(out: &mut Buffer, closing_tag: &str) {
887     out.write_str(closing_tag);
888 }
889
890 /// Called for a span of text. If the text should be highlighted differently
891 /// from the surrounding text, then the `Class` argument will be a value other
892 /// than `None`.
893 ///
894 /// The following sequences of callbacks are equivalent:
895 /// ```plain
896 ///     enter_span(Foo), string("text", None), exit_span()
897 ///     string("text", Foo)
898 /// ```
899 ///
900 /// The latter can be thought of as a shorthand for the former, which is more
901 /// flexible.
902 ///
903 /// Note that if `context` is not `None` and that the given `klass` contains a `Span`, the function
904 /// will then try to find this `span` in the `span_correspondance_map`. If found, it'll then
905 /// generate a link for this element (which corresponds to where its definition is located).
906 fn string<T: Display>(
907     out: &mut Buffer,
908     text: T,
909     klass: Option<Class>,
910     href_context: &Option<HrefContext<'_, '_, '_>>,
911     open_tag: bool,
912 ) {
913     if let Some(closing_tag) = string_without_closing_tag(out, text, klass, href_context, open_tag)
914     {
915         out.write_str(closing_tag);
916     }
917 }
918
919 /// This function writes `text` into `out` with some modifications depending on `klass`:
920 ///
921 /// * If `klass` is `None`, `text` is written into `out` with no modification.
922 /// * If `klass` is `Some` but `klass.get_span()` is `None`, it writes the text wrapped in a
923 ///   `<span>` with the provided `klass`.
924 /// * If `klass` is `Some` and has a [`rustc_span::Span`], it then tries to generate a link (`<a>`
925 ///   element) by retrieving the link information from the `span_correspondance_map` that was filled
926 ///   in `span_map.rs::collect_spans_and_sources`. If it cannot retrieve the information, then it's
927 ///   the same as the second point (`klass` is `Some` but doesn't have a [`rustc_span::Span`]).
928 fn string_without_closing_tag<T: Display>(
929     out: &mut Buffer,
930     text: T,
931     klass: Option<Class>,
932     href_context: &Option<HrefContext<'_, '_, '_>>,
933     open_tag: bool,
934 ) -> Option<&'static str> {
935     let Some(klass) = klass
936     else {
937         write!(out, "{}", text);
938         return None;
939     };
940     let Some(def_span) = klass.get_span()
941     else {
942         if !open_tag {
943             write!(out, "{}", text);
944             return None;
945         }
946         write!(out, "<span class=\"{}\">{}", klass.as_html(), text);
947         return Some("</span>");
948     };
949
950     let mut text_s = text.to_string();
951     if text_s.contains("::") {
952         text_s = text_s.split("::").intersperse("::").fold(String::new(), |mut path, t| {
953             match t {
954                 "self" | "Self" => write!(
955                     &mut path,
956                     "<span class=\"{}\">{}</span>",
957                     Class::Self_(DUMMY_SP).as_html(),
958                     t
959                 ),
960                 "crate" | "super" => {
961                     write!(&mut path, "<span class=\"{}\">{}</span>", Class::KeyWord.as_html(), t)
962                 }
963                 t => write!(&mut path, "{}", t),
964             }
965             .expect("Failed to build source HTML path");
966             path
967         });
968     }
969
970     if let Some(href_context) = href_context {
971         if let Some(href) =
972             href_context.context.shared.span_correspondance_map.get(&def_span).and_then(|href| {
973                 let context = href_context.context;
974                 // FIXME: later on, it'd be nice to provide two links (if possible) for all items:
975                 // one to the documentation page and one to the source definition.
976                 // FIXME: currently, external items only generate a link to their documentation,
977                 // a link to their definition can be generated using this:
978                 // https://github.com/rust-lang/rust/blob/60f1a2fc4b535ead9c85ce085fdce49b1b097531/src/librustdoc/html/render/context.rs#L315-L338
979                 match href {
980                     LinkFromSrc::Local(span) => context
981                         .href_from_span(*span, true)
982                         .map(|s| format!("{}{}", href_context.root_path, s)),
983                     LinkFromSrc::External(def_id) => {
984                         format::href_with_root_path(*def_id, context, Some(href_context.root_path))
985                             .ok()
986                             .map(|(url, _, _)| url)
987                     }
988                     LinkFromSrc::Primitive(prim) => format::href_with_root_path(
989                         PrimitiveType::primitive_locations(context.tcx())[prim],
990                         context,
991                         Some(href_context.root_path),
992                     )
993                     .ok()
994                     .map(|(url, _, _)| url),
995                 }
996             })
997         {
998             if !open_tag {
999                 // We're already inside an element which has the same klass, no need to give it
1000                 // again.
1001                 write!(out, "<a href=\"{}\">{}", href, text_s);
1002             } else {
1003                 let klass_s = klass.as_html();
1004                 if klass_s.is_empty() {
1005                     write!(out, "<a href=\"{}\">{}", href, text_s);
1006                 } else {
1007                     write!(out, "<a class=\"{}\" href=\"{}\">{}", klass_s, href, text_s);
1008                 }
1009             }
1010             return Some("</a>");
1011         }
1012     }
1013     if !open_tag {
1014         write!(out, "{}", text_s);
1015         return None;
1016     }
1017     let klass_s = klass.as_html();
1018     if klass_s.is_empty() {
1019         write!(out, "{}", text_s);
1020         Some("")
1021     } else {
1022         write!(out, "<span class=\"{}\">{}", klass_s, text_s);
1023         Some("</span>")
1024     }
1025 }
1026
1027 #[cfg(test)]
1028 mod tests;