]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/highlight.rs
Rollup merge of #68500 - Mark-Simulacrum:fix-bootstrap-clearing, r=alexcrichton
[rust.git] / src / librustdoc / html / highlight.rs
1 //! Basic syntax highlighting functionality.
2 //!
3 //! This module uses libsyntax'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::html::escape::Escape;
9
10 use std::fmt::Display;
11 use std::io;
12 use std::io::prelude::*;
13
14 use rustc_parse::lexer;
15 use rustc_span::source_map::SourceMap;
16 use rustc_span::symbol::{kw, sym};
17 use rustc_span::{FileName, Span};
18 use syntax::sess::ParseSess;
19 use syntax::token::{self, Token};
20
21 /// Highlights `src`, returning the HTML output.
22 pub fn render_with_highlighting(
23     src: &str,
24     class: Option<&str>,
25     extension: Option<&str>,
26     tooltip: Option<(&str, &str)>,
27 ) -> String {
28     debug!("highlighting: ================\n{}\n==============", src);
29     let mut out = Vec::new();
30     if let Some((tooltip, class)) = tooltip {
31         write!(
32             out,
33             "<div class='information'><div class='tooltip {}'>ⓘ<span \
34                      class='tooltiptext'>{}</span></div></div>",
35             class, tooltip
36         )
37         .unwrap();
38     }
39
40     let sess = ParseSess::with_silent_emitter();
41     let fm = sess
42         .source_map()
43         .new_source_file(FileName::Custom(String::from("rustdoc-highlighting")), src.to_owned());
44     let highlight_result = rustc_driver::catch_fatal_errors(|| {
45         let lexer = lexer::StringReader::new(&sess, fm, None);
46         let mut classifier = Classifier::new(lexer, sess.source_map());
47
48         let mut highlighted_source = vec![];
49         if classifier.write_source(&mut highlighted_source).is_err() {
50             Err(())
51         } else {
52             Ok(String::from_utf8_lossy(&highlighted_source).into_owned())
53         }
54     })
55     .unwrap_or(Err(()));
56
57     match highlight_result {
58         Ok(highlighted_source) => {
59             write_header(class, &mut out).unwrap();
60             write!(out, "{}", highlighted_source).unwrap();
61             if let Some(extension) = extension {
62                 write!(out, "{}", extension).unwrap();
63             }
64             write_footer(&mut out).unwrap();
65         }
66         Err(()) => {
67             // If errors are encountered while trying to highlight, just emit
68             // the unhighlighted source.
69             write!(out, "<pre><code>{}</code></pre>", Escape(src)).unwrap();
70         }
71     }
72
73     String::from_utf8_lossy(&out[..]).into_owned()
74 }
75
76 /// Processes a program (nested in the internal `lexer`), classifying strings of
77 /// text by highlighting category (`Class`). Calls out to a `Writer` to write
78 /// each span of text in sequence.
79 struct Classifier<'a> {
80     lexer: lexer::StringReader<'a>,
81     peek_token: Option<Token>,
82     source_map: &'a SourceMap,
83
84     // State of the classifier.
85     in_attribute: bool,
86     in_macro: bool,
87     in_macro_nonterminal: bool,
88 }
89
90 /// How a span of text is classified. Mostly corresponds to token kinds.
91 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
92 enum Class {
93     None,
94     Comment,
95     DocComment,
96     Attribute,
97     KeyWord,
98     // Keywords that do pointer/reference stuff.
99     RefKeyWord,
100     Self_,
101     Op,
102     Macro,
103     MacroNonTerminal,
104     String,
105     Number,
106     Bool,
107     Ident,
108     Lifetime,
109     PreludeTy,
110     PreludeVal,
111     QuestionMark,
112 }
113
114 /// Trait that controls writing the output of syntax highlighting. Users should
115 /// implement this trait to customize writing output.
116 ///
117 /// The classifier will call into the `Writer` implementation as it finds spans
118 /// of text to highlight. Exactly how that text should be highlighted is up to
119 /// the implementation.
120 trait Writer {
121     /// Called when we start processing a span of text that should be highlighted.
122     /// The `Class` argument specifies how it should be highlighted.
123     fn enter_span(&mut self, _: Class) -> io::Result<()>;
124
125     /// Called at the end of a span of highlighted text.
126     fn exit_span(&mut self) -> io::Result<()>;
127
128     /// Called for a span of text. If the text should be highlighted differently from the
129     /// surrounding text, then the `Class` argument will be a value other than `None`.
130     ///
131     /// The following sequences of callbacks are equivalent:
132     /// ```plain
133     ///     enter_span(Foo), string("text", None), exit_span()
134     ///     string("text", Foo)
135     /// ```
136     /// The latter can be thought of as a shorthand for the former, which is
137     /// more flexible.
138     fn string<T: Display>(&mut self, text: T, klass: Class) -> io::Result<()>;
139 }
140
141 // Implement `Writer` for anthing that can be written to, this just implements
142 // the default rustdoc behaviour.
143 impl<U: Write> Writer for U {
144     fn string<T: Display>(&mut self, text: T, klass: Class) -> io::Result<()> {
145         match klass {
146             Class::None => write!(self, "{}", text),
147             klass => write!(self, "<span class=\"{}\">{}</span>", klass.rustdoc_class(), text),
148         }
149     }
150
151     fn enter_span(&mut self, klass: Class) -> io::Result<()> {
152         write!(self, "<span class=\"{}\">", klass.rustdoc_class())
153     }
154
155     fn exit_span(&mut self) -> io::Result<()> {
156         write!(self, "</span>")
157     }
158 }
159
160 enum HighlightError {
161     LexError,
162     IoError(io::Error),
163 }
164
165 impl From<io::Error> for HighlightError {
166     fn from(err: io::Error) -> Self {
167         HighlightError::IoError(err)
168     }
169 }
170
171 impl<'a> Classifier<'a> {
172     fn new(lexer: lexer::StringReader<'a>, source_map: &'a SourceMap) -> Classifier<'a> {
173         Classifier {
174             lexer,
175             peek_token: None,
176             source_map,
177             in_attribute: false,
178             in_macro: false,
179             in_macro_nonterminal: false,
180         }
181     }
182
183     /// Gets the next token out of the lexer.
184     fn try_next_token(&mut self) -> Result<Token, HighlightError> {
185         if let Some(token) = self.peek_token.take() {
186             return Ok(token);
187         }
188         let token = self.lexer.next_token();
189         if let token::Unknown(..) = &token.kind {
190             return Err(HighlightError::LexError);
191         }
192         Ok(token)
193     }
194
195     fn peek(&mut self) -> Result<&Token, HighlightError> {
196         if self.peek_token.is_none() {
197             let token = self.lexer.next_token();
198             if let token::Unknown(..) = &token.kind {
199                 return Err(HighlightError::LexError);
200             }
201             self.peek_token = Some(token);
202         }
203         Ok(self.peek_token.as_ref().unwrap())
204     }
205
206     /// Exhausts the `lexer` writing the output into `out`.
207     ///
208     /// The general structure for this method is to iterate over each token,
209     /// possibly giving it an HTML span with a class specifying what flavor of token
210     /// is used. All source code emission is done as slices from the source map,
211     /// not from the tokens themselves, in order to stay true to the original
212     /// source.
213     fn write_source<W: Writer>(&mut self, out: &mut W) -> Result<(), HighlightError> {
214         loop {
215             let next = self.try_next_token()?;
216             if next == token::Eof {
217                 break;
218             }
219
220             self.write_token(out, next)?;
221         }
222
223         Ok(())
224     }
225
226     // Handles an individual token from the lexer.
227     fn write_token<W: Writer>(&mut self, out: &mut W, token: Token) -> Result<(), HighlightError> {
228         let klass = match token.kind {
229             token::Shebang(s) => {
230                 out.string(Escape(&s.as_str()), Class::None)?;
231                 return Ok(());
232             }
233
234             token::Whitespace | token::Unknown(..) => Class::None,
235             token::Comment => Class::Comment,
236             token::DocComment(..) => Class::DocComment,
237
238             // If this '&' or '*' token is followed by a non-whitespace token, assume that it's the
239             // reference or dereference operator or a reference or pointer type, instead of the
240             // bit-and or multiplication operator.
241             token::BinOp(token::And) | token::BinOp(token::Star)
242                 if self.peek()? != &token::Whitespace =>
243             {
244                 Class::RefKeyWord
245             }
246
247             // Consider this as part of a macro invocation if there was a
248             // leading identifier.
249             token::Not if self.in_macro => {
250                 self.in_macro = false;
251                 Class::Macro
252             }
253
254             // Operators.
255             token::Eq
256             | token::Lt
257             | token::Le
258             | token::EqEq
259             | token::Ne
260             | token::Ge
261             | token::Gt
262             | token::AndAnd
263             | token::OrOr
264             | token::Not
265             | token::BinOp(..)
266             | token::RArrow
267             | token::BinOpEq(..)
268             | token::FatArrow => Class::Op,
269
270             // Miscellaneous, no highlighting.
271             token::Dot
272             | token::DotDot
273             | token::DotDotDot
274             | token::DotDotEq
275             | token::Comma
276             | token::Semi
277             | token::Colon
278             | token::ModSep
279             | token::LArrow
280             | token::OpenDelim(_)
281             | token::CloseDelim(token::Brace)
282             | token::CloseDelim(token::Paren)
283             | token::CloseDelim(token::NoDelim) => Class::None,
284
285             token::Question => Class::QuestionMark,
286
287             token::Dollar => {
288                 if self.peek()?.is_ident() {
289                     self.in_macro_nonterminal = true;
290                     Class::MacroNonTerminal
291                 } else {
292                     Class::None
293                 }
294             }
295
296             // This might be the start of an attribute. We're going to want to
297             // continue highlighting it as an attribute until the ending ']' is
298             // seen, so skip out early. Down below we terminate the attribute
299             // span when we see the ']'.
300             token::Pound => {
301                 // We can't be sure that our # begins an attribute (it could
302                 // just be appearing in a macro) until we read either `#![` or
303                 // `#[` from the input stream.
304                 //
305                 // We don't want to start highlighting as an attribute until
306                 // we're confident there is going to be a ] coming up, as
307                 // otherwise # tokens in macros highlight the rest of the input
308                 // as an attribute.
309
310                 // Case 1: #![inner_attribute]
311                 if self.peek()? == &token::Not {
312                     self.try_next_token()?; // NOTE: consumes `!` token!
313                     if self.peek()? == &token::OpenDelim(token::Bracket) {
314                         self.in_attribute = true;
315                         out.enter_span(Class::Attribute)?;
316                     }
317                     out.string("#", Class::None)?;
318                     out.string("!", Class::None)?;
319                     return Ok(());
320                 }
321
322                 // Case 2: #[outer_attribute]
323                 if self.peek()? == &token::OpenDelim(token::Bracket) {
324                     self.in_attribute = true;
325                     out.enter_span(Class::Attribute)?;
326                 }
327                 out.string("#", Class::None)?;
328                 return Ok(());
329             }
330             token::CloseDelim(token::Bracket) => {
331                 if self.in_attribute {
332                     self.in_attribute = false;
333                     out.string("]", Class::None)?;
334                     out.exit_span()?;
335                     return Ok(());
336                 } else {
337                     Class::None
338                 }
339             }
340
341             token::Literal(lit) => {
342                 match lit.kind {
343                     // Text literals.
344                     token::Byte
345                     | token::Char
346                     | token::Err
347                     | token::ByteStr
348                     | token::ByteStrRaw(..)
349                     | token::Str
350                     | token::StrRaw(..) => Class::String,
351
352                     // Number literals.
353                     token::Integer | token::Float => Class::Number,
354
355                     token::Bool => panic!("literal token contains `Lit::Bool`"),
356                 }
357             }
358
359             // Keywords are also included in the identifier set.
360             token::Ident(name, is_raw) => match name {
361                 kw::Ref | kw::Mut if !is_raw => Class::RefKeyWord,
362
363                 kw::SelfLower | kw::SelfUpper => Class::Self_,
364                 kw::False | kw::True if !is_raw => Class::Bool,
365
366                 sym::Option | sym::Result => Class::PreludeTy,
367                 sym::Some | sym::None | sym::Ok | sym::Err => Class::PreludeVal,
368
369                 _ if token.is_reserved_ident() => Class::KeyWord,
370
371                 _ => {
372                     if self.in_macro_nonterminal {
373                         self.in_macro_nonterminal = false;
374                         Class::MacroNonTerminal
375                     } else if self.peek()? == &token::Not {
376                         self.in_macro = true;
377                         Class::Macro
378                     } else {
379                         Class::Ident
380                     }
381                 }
382             },
383
384             token::Lifetime(..) => Class::Lifetime,
385
386             token::Eof
387             | token::Interpolated(..)
388             | token::Tilde
389             | token::At
390             | token::SingleQuote => Class::None,
391         };
392
393         // Anything that didn't return above is the simple case where we the
394         // class just spans a single token, so we can use the `string` method.
395         out.string(Escape(&self.snip(token.span)), klass)?;
396
397         Ok(())
398     }
399
400     // Helper function to get a snippet from the source_map.
401     fn snip(&self, sp: Span) -> String {
402         self.source_map.span_to_snippet(sp).unwrap()
403     }
404 }
405
406 impl Class {
407     /// Returns the css class expected by rustdoc for each `Class`.
408     fn rustdoc_class(self) -> &'static str {
409         match self {
410             Class::None => "",
411             Class::Comment => "comment",
412             Class::DocComment => "doccomment",
413             Class::Attribute => "attribute",
414             Class::KeyWord => "kw",
415             Class::RefKeyWord => "kw-2",
416             Class::Self_ => "self",
417             Class::Op => "op",
418             Class::Macro => "macro",
419             Class::MacroNonTerminal => "macro-nonterminal",
420             Class::String => "string",
421             Class::Number => "number",
422             Class::Bool => "bool-val",
423             Class::Ident => "ident",
424             Class::Lifetime => "lifetime",
425             Class::PreludeTy => "prelude-ty",
426             Class::PreludeVal => "prelude-val",
427             Class::QuestionMark => "question-mark",
428         }
429     }
430 }
431
432 fn write_header(class: Option<&str>, out: &mut dyn Write) -> io::Result<()> {
433     write!(out, "<div class=\"example-wrap\"><pre class=\"rust {}\">\n", class.unwrap_or(""))
434 }
435
436 fn write_footer(out: &mut dyn Write) -> io::Result<()> {
437     write!(out, "</pre></div>\n")
438 }