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