1 //! Basic syntax highlighting functionality.
3 //! This module uses librustc_ast's lexer to provide token-based highlighting for
4 //! the HTML documentation generated by rustdoc.
6 //! Use the `render_with_highlighting` to highlight some rust code.
8 use crate::clean::PrimitiveType;
9 use crate::html::escape::Escape;
10 use crate::html::render::Context;
12 use std::collections::VecDeque;
13 use std::fmt::{Display, Write};
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};
21 use super::format::{self, Buffer};
22 use super::render::LinkFromSrc;
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,
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)>>);
38 /// Highlights `src`, returning the HTML output.
39 crate fn render_with_highlighting(
43 playground_button: Option<&str>,
44 tooltip: Option<(Option<Edition>, &str)>,
46 extra_content: Option<Buffer>,
47 context_info: Option<ContextInfo<'_, '_, '_>>,
48 decoration_info: Option<DecorationInfo>,
50 debug!("highlighting: ================\n{}\n==============", src);
51 if let Some((edition_info, class)) = tooltip {
54 "<div class='information'><div class='tooltip {}'{}>ⓘ</div></div>",
56 if let Some(edition_info) = edition_info {
57 format!(" data-edition=\"{}\"", edition_info)
64 write_header(out, class, extra_content);
65 write_code(out, src, edition, context_info, decoration_info);
66 write_footer(out, playground_button);
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);
74 if let Some(class) = class {
75 write!(out, "<pre class=\"rust {}\">", class);
77 write!(out, "<pre class=\"rust\">");
79 write!(out, "<code>");
82 /// Convert the given `src` source code into HTML by adding classes for highlighting.
84 /// This code is used to render code blocks (in the documentation) as well as the source code pages.
86 /// Some explanations on the last arguments:
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
92 /// More explanations about spans and how we use them here are provided in the
97 context_info: Option<ContextInfo<'_, '_, '_>>,
98 decoration_info: Option<DecorationInfo>,
100 // This replace allows to fix how the code source with DOS backline characters is displayed.
101 let src = src.replace("\r\n", "\n");
105 context_info.as_ref().map(|c| c.file_span).unwrap_or(DUMMY_SP),
108 .highlight(&mut |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),
117 fn write_footer(out: &mut Buffer, playground_button: Option<&str>) {
118 writeln!(out, "</code></pre>{}</div>", playground_button.unwrap_or_default());
121 /// How a span of text is classified. Mostly corresponds to token kinds.
122 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
128 // Keywords that do pointer/reference stuff.
142 Decoration(&'static str),
146 /// Returns the css class expected by rustdoc for each `Class`.
147 fn as_html(self) -> &'static str {
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",
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,
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> {
174 Self::Ident(sp) | Self::Self_(sp) => Some(sp),
181 Token { text: &'a str, class: Option<Class> },
182 EnterSpan { class: Class },
186 struct TokenIter<'a> {
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() {
196 let token = rustc_lexer::first_token(self.src);
197 let (text, rest) = self.src.split_at(token.len);
199 Some((token.kind, text))
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) {
211 "ref" | "mut" => Class::RefKeyWord,
212 "false" | "true" => Class::Bool,
213 _ if Symbol::intern(text).is_reserved(|| edition) => Class::KeyWord,
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.
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`.
230 impl<'a> PeekIter<'a> {
231 fn new(iter: TokenIter<'a>) -> Self {
232 Self { stored: VecDeque::new(), peek_pos: 0, iter }
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);
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)> {
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);
257 impl<'a> Iterator for PeekIter<'a> {
258 type Item = (TokenKind, &'a str);
259 fn next(&mut self) -> Option<Self::Item> {
261 if let Some(first) = self.stored.pop_front() { Some(first) } else { self.iter.next() }
265 /// Custom spans inserted into the source. Eg --scrape-examples uses this to highlight function calls
267 starts: Vec<(u32, &'static str)>,
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
277 .flat_map(|(kind, ranges)| ranges.into_iter().map(move |(lo, hi)| ((lo, kind), hi)))
280 // Sort the sequences in document order.
281 starts.sort_by_key(|(lo, _)| *lo);
284 Decorations { starts, ends }
288 /// Processes program tokens, classifying strings of text by highlighting
289 /// category (`Class`).
290 struct Classifier<'a> {
291 tokens: PeekIter<'a>,
294 in_macro_nonterminal: bool,
299 decorations: Option<Decorations>,
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`.
309 decoration_info: Option<DecorationInfo>,
310 ) -> Classifier<'_> {
311 let tokens = PeekIter::new(TokenIter { src });
312 let decorations = decoration_info.map(Decorations::new);
317 in_macro_nonterminal: false,
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))
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;
337 let mut has_ident = false;
338 let edition = self.edition;
342 while let Some((TokenKind::Colon, _)) = self.tokens.peek() {
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 {
352 return vec![(TokenKind::Ident, start, pos), (TokenKind::Colon, pos, pos + nb)];
354 return vec![(TokenKind::Colon, start, pos + nb)];
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);
363 // Doesn't matter which Class we put in here...
364 (Some(Class::Comment), text)
367 // We only "add" the colon if there is an ident behind.
368 pos += text.len() + nb;
371 } else if nb > 0 && has_ident {
372 return vec![(TokenKind::Ident, start, pos), (TokenKind::Colon, pos, pos + nb)];
374 return vec![(TokenKind::Colon, start, start + nb)];
375 } else if has_ident {
376 return vec![(TokenKind::Ident, start, pos)];
383 /// Wraps the tokens iteration to ensure that the `byte_pos` is always correct.
385 /// It returns the token's kind, the token as a string and its byte position in the source
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))
397 /// Exhausts the `Classifier` writing the output into `sink`.
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
402 fn highlight(mut self, sink: &mut dyn FnMut(Highlight<'a>)) {
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) });
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);
420 .map(|t| matches!(t.0, TokenKind::Colon | TokenKind::Ident))
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;
429 if !tokens.is_empty() {
433 if let Some((token, text, before)) = self.next() {
434 self.advance(token, text, sink, before);
441 /// Single step of highlighting. This will classify `token`, but maybe also a couple of
442 /// following ones as well.
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`.
451 sink: &mut dyn FnMut(Highlight<'a>),
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() {
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);
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")) => {
481 sink(Highlight::Token { text: "*mut", class: Some(Class::RefKeyWord) });
484 Some((TokenKind::Ident, "const")) => {
486 sink(Highlight::Token { text: "*const", class: Some(Class::RefKeyWord) });
489 _ => Class::RefKeyWord,
491 TokenKind::And => match self.tokens.peek() {
492 Some((TokenKind::And, _)) => {
494 sink(Highlight::Token { text: "&&", class: Some(Class::Op) });
497 Some((TokenKind::Eq, _)) => {
499 sink(Highlight::Token { text: "&=", class: Some(Class::Op) });
502 Some((TokenKind::Whitespace, _)) => Class::Op,
503 Some((TokenKind::Ident, "mut")) => {
505 sink(Highlight::Token { text: "&mut", class: Some(Class::RefKeyWord) });
508 _ => Class::RefKeyWord,
511 // These can either be operators, or arrows.
512 TokenKind::Eq => match lookahead {
513 Some(TokenKind::Eq) => {
515 sink(Highlight::Token { text: "==", class: Some(Class::Op) });
518 Some(TokenKind::Gt) => {
520 sink(Highlight::Token { text: "=>", class: None });
525 TokenKind::Minus if lookahead == Some(TokenKind::Gt) => {
527 sink(Highlight::Token { text: "->", class: None });
540 | TokenKind::Gt => Class::Op,
542 // Miscellaneous, no highlighting.
546 | TokenKind::OpenParen
547 | TokenKind::CloseParen
548 | TokenKind::OpenBrace
549 | TokenKind::CloseBrace
550 | TokenKind::OpenBracket
554 | TokenKind::Unknown => return no_highlight(sink),
556 TokenKind::Question => Class::QuestionMark,
558 TokenKind::Dollar => match lookahead {
559 Some(TokenKind::Ident) => {
560 self.in_macro_nonterminal = true;
561 Class::MacroNonTerminal
563 _ => return no_highlight(sink),
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 => {
572 // Case 1: #![inner_attribute]
573 Some(TokenKind::Bang) => {
575 if let Some(TokenKind::OpenBracket) = self.peek() {
576 self.in_attribute = true;
577 sink(Highlight::EnterSpan { class: Class::Attribute });
579 sink(Highlight::Token { text: "#", class: None });
580 sink(Highlight::Token { text: "!", class: None });
583 // Case 2: #[outer_attribute]
584 Some(TokenKind::OpenBracket) => {
585 self.in_attribute = true;
586 sink(Highlight::EnterSpan { class: Class::Attribute });
590 return no_highlight(sink);
592 TokenKind::CloseBracket => {
593 if self.in_attribute {
594 self.in_attribute = false;
595 sink(Highlight::Token { text: "]", class: None });
596 sink(Highlight::ExitSpan);
599 return no_highlight(sink);
601 TokenKind::Literal { kind, .. } => match kind {
603 LiteralKind::Byte { .. }
604 | LiteralKind::Char { .. }
605 | LiteralKind::Str { .. }
606 | LiteralKind::ByteStr { .. }
607 | LiteralKind::RawStr { .. }
608 | LiteralKind::RawByteStr { .. } => Class::String,
610 LiteralKind::Float { .. } | LiteralKind::Int { .. } => Class::Number,
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 });
618 TokenKind::Ident => match get_real_ident_class(text, self.edition, false) {
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
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
629 "self" | "Self" => Class::Self_(self.new_span(before, text)),
630 _ => Class::Ident(self.new_span(before, text)),
634 TokenKind::RawIdent | TokenKind::UnknownPrefix | TokenKind::InvalidIdent => {
635 Class::Ident(self.new_span(before, text))
637 TokenKind::Lifetime { .. } => Class::Lifetime,
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) });
644 fn peek(&mut self) -> Option<TokenKind> {
645 self.tokens.peek().map(|(token_kind, _text)| *token_kind)
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 {
653 return *kind == TokenKind::Ident;
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());
665 /// Called at the end of a span of highlighted text.
666 fn exit_span(out: &mut Buffer) {
667 out.write_str("</span>");
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
674 /// The following sequences of callbacks are equivalent:
676 /// enter_span(Foo), string("text", None), exit_span()
677 /// string("text", Foo)
680 /// The latter can be thought of as a shorthand for the former, which is more
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>(
689 klass: Option<Class>,
690 context_info: &Option<ContextInfo<'_, '_, '_>>,
692 let klass = match klass {
693 None => return write!(out, "{}", text),
694 Some(klass) => klass,
696 let def_span = match klass.get_span() {
699 write!(out, "<span class=\"{}\">{}</span>", klass.as_html(), text);
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| {
707 "self" | "Self" => write!(
709 "<span class=\"{}\">{}</span>",
710 Class::Self_(DUMMY_SP).as_html(),
713 "crate" | "super" => {
714 write!(&mut path, "<span class=\"{}\">{}</span>", Class::KeyWord.as_html(), t)
716 t => write!(&mut path, "{}", t),
718 .expect("Failed to build source HTML path");
722 if let Some(context_info) = context_info {
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
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))
738 .map(|(url, _, _)| url)
740 LinkFromSrc::Primitive(prim) => format::href_with_root_path(
741 PrimitiveType::primitive_locations(context.tcx())[prim],
743 Some(context_info.root_path),
746 .map(|(url, _, _)| url),
750 write!(out, "<a class=\"{}\" href=\"{}\">{}</a>", klass.as_html(), href, text_s);
754 write!(out, "<span class=\"{}\">{}</span>", klass.as_html(), text_s);