]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/highlight.rs
932419c78f22c1f03d6d09828e53e51d5e39b966
[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 syntax::source_map::{SourceMap, FilePathMapping};
15 use syntax::parse::lexer::{self, TokenAndSpan};
16 use syntax::parse::token;
17 use syntax::parse;
18 use syntax::symbol::{kw, sym};
19 use syntax_pos::{Span, FileName};
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!(out, "<div class='information'><div class='tooltip {}'>ⓘ<span \
32                      class='tooltiptext'>{}</span></div></div>",
33                class, tooltip).unwrap();
34     }
35
36     let sess = parse::ParseSess::new(FilePathMapping::empty());
37     let fm = sess.source_map().new_source_file(
38         FileName::Custom(String::from("rustdoc-highlighting")),
39         src.to_owned(),
40     );
41     let highlight_result =
42         lexer::StringReader::new_or_buffered_errs(&sess, fm, None).and_then(|lexer| {
43             let mut classifier = Classifier::new(lexer, sess.source_map());
44
45             let mut highlighted_source = vec![];
46             if classifier.write_source(&mut highlighted_source).is_err() {
47                 Err(classifier.lexer.buffer_fatal_errors())
48             } else {
49                 Ok(String::from_utf8_lossy(&highlighted_source).into_owned())
50             }
51         });
52
53     match highlight_result {
54         Ok(highlighted_source) => {
55             write_header(class, &mut out).unwrap();
56             write!(out, "{}", highlighted_source).unwrap();
57             if let Some(extension) = extension {
58                 write!(out, "{}", extension).unwrap();
59             }
60             write_footer(&mut out).unwrap();
61         }
62         Err(errors) => {
63             // If errors are encountered while trying to highlight, cancel the errors and just emit
64             // the unhighlighted source. The errors will have already been reported in the
65             // `check-code-block-syntax` pass.
66             for mut error in errors {
67                 error.cancel();
68             }
69
70             write!(out, "<pre><code>{}</code></pre>", src).unwrap();
71         }
72     }
73
74     String::from_utf8_lossy(&out[..]).into_owned()
75 }
76
77 /// Processes a program (nested in the internal `lexer`), classifying strings of
78 /// text by highlighting category (`Class`). Calls out to a `Writer` to write
79 /// each span of text in sequence.
80 struct Classifier<'a> {
81     lexer: lexer::StringReader<'a>,
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,
139                           text: T,
140                           klass: Class)
141                           -> io::Result<()>;
142 }
143
144 // Implement `Writer` for anthing that can be written to, this just implements
145 // the default rustdoc behaviour.
146 impl<U: Write> Writer for U {
147     fn string<T: Display>(&mut self,
148                           text: T,
149                           klass: Class)
150                           -> io::Result<()> {
151         match klass {
152             Class::None => write!(self, "{}", text),
153             klass => write!(self, "<span class=\"{}\">{}</span>", klass.rustdoc_class(), text),
154         }
155     }
156
157     fn enter_span(&mut self, klass: Class) -> io::Result<()> {
158         write!(self, "<span class=\"{}\">", klass.rustdoc_class())
159     }
160
161     fn exit_span(&mut self) -> io::Result<()> {
162         write!(self, "</span>")
163     }
164 }
165
166 enum HighlightError {
167     LexError,
168     IoError(io::Error),
169 }
170
171 impl From<io::Error> for HighlightError {
172     fn from(err: io::Error) -> Self {
173         HighlightError::IoError(err)
174     }
175 }
176
177 impl<'a> Classifier<'a> {
178     fn new(lexer: lexer::StringReader<'a>, source_map: &'a SourceMap) -> Classifier<'a> {
179         Classifier {
180             lexer,
181             source_map,
182             in_attribute: false,
183             in_macro: false,
184             in_macro_nonterminal: false,
185         }
186     }
187
188     /// Gets the next token out of the lexer.
189     fn try_next_token(&mut self) -> Result<TokenAndSpan, HighlightError> {
190         match self.lexer.try_next_token() {
191             Ok(tas) => Ok(tas),
192             Err(_) => Err(HighlightError::LexError),
193         }
194     }
195
196     /// Exhausts the `lexer` writing the output into `out`.
197     ///
198     /// The general structure for this method is to iterate over each token,
199     /// possibly giving it an HTML span with a class specifying what flavor of token
200     /// is used. All source code emission is done as slices from the source map,
201     /// not from the tokens themselves, in order to stay true to the original
202     /// source.
203     fn write_source<W: Writer>(&mut self,
204                                    out: &mut W)
205                                    -> Result<(), HighlightError> {
206         loop {
207             let next = self.try_next_token()?;
208             if next.tok == token::Eof {
209                 break;
210             }
211
212             self.write_token(out, next)?;
213         }
214
215         Ok(())
216     }
217
218     // Handles an individual token from the lexer.
219     fn write_token<W: Writer>(&mut self,
220                               out: &mut W,
221                               tas: TokenAndSpan)
222                               -> Result<(), HighlightError> {
223         let klass = match tas.tok {
224             token::Shebang(s) => {
225                 out.string(Escape(&s.as_str()), Class::None)?;
226                 return Ok(());
227             },
228
229             token::Whitespace => Class::None,
230             token::Comment => Class::Comment,
231             token::DocComment(..) => Class::DocComment,
232
233             // If this '&' or '*' token is followed by a non-whitespace token, assume that it's the
234             // reference or dereference operator or a reference or pointer type, instead of the
235             // bit-and or multiplication operator.
236             token::BinOp(token::And) | token::BinOp(token::Star)
237                 if self.lexer.peek().tok != token::Whitespace => Class::RefKeyWord,
238
239             // Consider this as part of a macro invocation if there was a
240             // leading identifier.
241             token::Not if self.in_macro => {
242                 self.in_macro = false;
243                 Class::Macro
244             }
245
246             // Operators.
247             token::Eq | token::Lt | token::Le | token::EqEq | token::Ne | token::Ge | token::Gt |
248                 token::AndAnd | token::OrOr | token::Not | token::BinOp(..) | token::RArrow |
249                 token::BinOpEq(..) | token::FatArrow => Class::Op,
250
251             // Miscellaneous, no highlighting.
252             token::Dot | token::DotDot | token::DotDotDot | token::DotDotEq | token::Comma |
253                 token::Semi | token::Colon | token::ModSep | token::LArrow | token::OpenDelim(_) |
254                 token::CloseDelim(token::Brace) | token::CloseDelim(token::Paren) |
255                 token::CloseDelim(token::NoDelim) => Class::None,
256
257             token::Question => Class::QuestionMark,
258
259             token::Dollar => {
260                 if self.lexer.peek().tok.is_ident() {
261                     self.in_macro_nonterminal = true;
262                     Class::MacroNonTerminal
263                 } else {
264                     Class::None
265                 }
266             }
267
268             // This might be the start of an attribute. We're going to want to
269             // continue highlighting it as an attribute until the ending ']' is
270             // seen, so skip out early. Down below we terminate the attribute
271             // span when we see the ']'.
272             token::Pound => {
273                 // We can't be sure that our # begins an attribute (it could
274                 // just be appearing in a macro) until we read either `#![` or
275                 // `#[` from the input stream.
276                 //
277                 // We don't want to start highlighting as an attribute until
278                 // we're confident there is going to be a ] coming up, as
279                 // otherwise # tokens in macros highlight the rest of the input
280                 // as an attribute.
281
282                 // Case 1: #![inner_attribute]
283                 if self.lexer.peek().tok == token::Not {
284                     self.try_next_token()?; // NOTE: consumes `!` token!
285                     if self.lexer.peek().tok == token::OpenDelim(token::Bracket) {
286                         self.in_attribute = true;
287                         out.enter_span(Class::Attribute)?;
288                     }
289                     out.string("#", Class::None)?;
290                     out.string("!", Class::None)?;
291                     return Ok(());
292                 }
293
294                 // Case 2: #[outer_attribute]
295                 if self.lexer.peek().tok == token::OpenDelim(token::Bracket) {
296                     self.in_attribute = true;
297                     out.enter_span(Class::Attribute)?;
298                 }
299                 out.string("#", Class::None)?;
300                 return Ok(());
301             }
302             token::CloseDelim(token::Bracket) => {
303                 if self.in_attribute {
304                     self.in_attribute = false;
305                     out.string("]", Class::None)?;
306                     out.exit_span()?;
307                     return Ok(());
308                 } else {
309                     Class::None
310                 }
311             }
312
313             token::Literal(lit) => {
314                 match lit.kind {
315                     // Text literals.
316                     token::Byte | token::Char | token::Err |
317                     token::ByteStr | token::ByteStrRaw(..) |
318                     token::Str | token::StrRaw(..) => Class::String,
319
320                     // Number literals.
321                     token::Integer | token::Float => Class::Number,
322
323                     token::Bool => panic!("literal token contains `Lit::Bool`"),
324                 }
325             }
326
327             // Keywords are also included in the identifier set.
328             token::Ident(ident, is_raw) => {
329                 match ident.name {
330                     kw::Ref | kw::Mut if !is_raw => Class::RefKeyWord,
331
332                     kw::SelfLower | kw::SelfUpper => Class::Self_,
333                     kw::False | kw::True if !is_raw => Class::Bool,
334
335                     sym::Option | sym::Result => Class::PreludeTy,
336                     sym::Some | sym::None | sym::Ok | sym::Err => Class::PreludeVal,
337
338                     _ if tas.tok.is_reserved_ident() => Class::KeyWord,
339
340                     _ => {
341                         if self.in_macro_nonterminal {
342                             self.in_macro_nonterminal = false;
343                             Class::MacroNonTerminal
344                         } else if self.lexer.peek().tok == token::Not {
345                             self.in_macro = true;
346                             Class::Macro
347                         } else {
348                             Class::Ident
349                         }
350                     }
351                 }
352             }
353
354             token::Lifetime(..) => Class::Lifetime,
355
356             token::Eof | token::Interpolated(..) |
357             token::Tilde | token::At| token::SingleQuote => Class::None,
358         };
359
360         // Anything that didn't return above is the simple case where we the
361         // class just spans a single token, so we can use the `string` method.
362         out.string(Escape(&self.snip(tas.sp)), klass)?;
363
364         Ok(())
365     }
366
367     // Helper function to get a snippet from the source_map.
368     fn snip(&self, sp: Span) -> String {
369         self.source_map.span_to_snippet(sp).unwrap()
370     }
371 }
372
373 impl Class {
374     /// Returns the css class expected by rustdoc for each `Class`.
375     fn rustdoc_class(self) -> &'static str {
376         match self {
377             Class::None => "",
378             Class::Comment => "comment",
379             Class::DocComment => "doccomment",
380             Class::Attribute => "attribute",
381             Class::KeyWord => "kw",
382             Class::RefKeyWord => "kw-2",
383             Class::Self_ => "self",
384             Class::Op => "op",
385             Class::Macro => "macro",
386             Class::MacroNonTerminal => "macro-nonterminal",
387             Class::String => "string",
388             Class::Number => "number",
389             Class::Bool => "bool-val",
390             Class::Ident => "ident",
391             Class::Lifetime => "lifetime",
392             Class::PreludeTy => "prelude-ty",
393             Class::PreludeVal => "prelude-val",
394             Class::QuestionMark => "question-mark"
395         }
396     }
397 }
398
399 fn write_header(class: Option<&str>, out: &mut dyn Write) -> io::Result<()> {
400     write!(out, "<div class=\"example-wrap\"><pre class=\"rust {}\">\n", class.unwrap_or(""))
401 }
402
403 fn write_footer(out: &mut dyn Write) -> io::Result<()> {
404     write!(out, "</pre></div>\n")
405 }