]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/highlight.rs
065778d8d0725f5a49c5b84db2413d7b25e4c58a
[rust.git] / src / librustdoc / html / highlight.rs
1 // Copyright 2014-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Basic syntax highlighting functionality.
12 //!
13 //! This module uses libsyntax's lexer to provide token-based highlighting for
14 //! the HTML documentation generated by rustdoc.
15 //!
16 //! If you just want to syntax highlighting for a Rust program, then you can use
17 //! the `render_inner_with_highlighting` or `render_with_highlighting`
18 //! functions. For more advanced use cases (if you want to supply your own css
19 //! classes or control how the HTML is generated, or even generate something
20 //! other then HTML), then you should implement the `Writer` trait and use a
21 //! `Classifier`.
22
23 use html::escape::Escape;
24
25 use std::fmt::Display;
26 use std::io;
27 use std::io::prelude::*;
28
29 use syntax::codemap::{CodeMap, FilePathMapping};
30 use syntax::parse::lexer::{self, TokenAndSpan};
31 use syntax::parse::token;
32 use syntax::parse;
33 use syntax_pos::{Span, FileName};
34
35 /// Highlights `src`, returning the HTML output.
36 pub fn render_with_highlighting(src: &str, class: Option<&str>, id: Option<&str>,
37                                 extension: Option<&str>,
38                                 tooltip: Option<(&str, &str)>) -> String {
39     debug!("highlighting: ================\n{}\n==============", src);
40     let sess = parse::ParseSess::new(FilePathMapping::empty());
41     let fm = sess.codemap().new_filemap(FileName::Custom("stdin".to_string()), src.to_string());
42
43     let mut out = Vec::new();
44     if let Some((tooltip, class)) = tooltip {
45         write!(out, "<div class='information'><div class='tooltip {}'>ⓘ<span \
46                      class='tooltiptext'>{}</span></div></div>",
47                class, tooltip).unwrap();
48     }
49     write_header(class, id, &mut out).unwrap();
50
51     let mut classifier = Classifier::new(lexer::StringReader::new(&sess, fm, None), sess.codemap());
52     if let Err(_) = classifier.write_source(&mut out) {
53         return format!("<pre>{}</pre>", src);
54     }
55
56     if let Some(extension) = extension {
57         write!(out, "{}", extension).unwrap();
58     }
59     write_footer(&mut out).unwrap();
60     String::from_utf8_lossy(&out[..]).into_owned()
61 }
62
63 /// Processes a program (nested in the internal `lexer`), classifying strings of
64 /// text by highlighting category (`Class`). Calls out to a `Writer` to write
65 /// each span of text in sequence.
66 pub struct Classifier<'a> {
67     lexer: lexer::StringReader<'a>,
68     codemap: &'a CodeMap,
69
70     // State of the classifier.
71     in_attribute: bool,
72     in_macro: bool,
73     in_macro_nonterminal: bool,
74 }
75
76 /// How a span of text is classified. Mostly corresponds to token kinds.
77 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
78 pub enum Class {
79     None,
80     Comment,
81     DocComment,
82     Attribute,
83     KeyWord,
84     // Keywords that do pointer/reference stuff.
85     RefKeyWord,
86     Self_,
87     Op,
88     Macro,
89     MacroNonTerminal,
90     String,
91     Number,
92     Bool,
93     Ident,
94     Lifetime,
95     PreludeTy,
96     PreludeVal,
97     QuestionMark,
98 }
99
100 /// Trait that controls writing the output of syntax highlighting. Users should
101 /// implement this trait to customize writing output.
102 ///
103 /// The classifier will call into the `Writer` implementation as it finds spans
104 /// of text to highlight. Exactly how that text should be highlighted is up to
105 /// the implementation.
106 pub trait Writer {
107     /// Called when we start processing a span of text that should be highlighted.
108     /// The `Class` argument specifies how it should be highlighted.
109     fn enter_span(&mut self, _: Class) -> io::Result<()>;
110
111     /// Called at the end of a span of highlighted text.
112     fn exit_span(&mut self) -> io::Result<()>;
113
114     /// Called for a span of text, usually, but not always, a single token. If
115     /// the string of text (`T`) does correspond to a token, then the token will
116     /// also be passed. If the text should be highlighted differently from the
117     /// surrounding text, then the `Class` argument will be a value other than
118     /// `None`.
119     /// The following sequences of callbacks are equivalent:
120     /// ```plain
121     ///     enter_span(Foo), string("text", None), exit_span()
122     ///     string("text", Foo)
123     /// ```
124     /// The latter can be thought of as a shorthand for the former, which is
125     /// more flexible.
126     fn string<T: Display>(&mut self,
127                           text: T,
128                           klass: Class,
129                           tok: Option<&TokenAndSpan>)
130                           -> io::Result<()>;
131 }
132
133 // Implement `Writer` for anthing that can be written to, this just implements
134 // the default rustdoc behaviour.
135 impl<U: Write> Writer for U {
136     fn string<T: Display>(&mut self,
137                           text: T,
138                           klass: Class,
139                           _tas: Option<&TokenAndSpan>)
140                           -> io::Result<()> {
141         match klass {
142             Class::None => write!(self, "{}", text),
143             klass => write!(self, "<span class=\"{}\">{}</span>", klass.rustdoc_class(), text),
144         }
145     }
146
147     fn enter_span(&mut self, klass: Class) -> io::Result<()> {
148         write!(self, "<span class=\"{}\">", klass.rustdoc_class())
149     }
150
151     fn exit_span(&mut self) -> io::Result<()> {
152         write!(self, "</span>")
153     }
154 }
155
156 impl<'a> Classifier<'a> {
157     pub fn new(lexer: lexer::StringReader<'a>, codemap: &'a CodeMap) -> Classifier<'a> {
158         Classifier {
159             lexer,
160             codemap,
161             in_attribute: false,
162             in_macro: false,
163             in_macro_nonterminal: false,
164         }
165     }
166
167     /// Gets the next token out of the lexer, emitting fatal errors if lexing fails.
168     fn try_next_token(&mut self) -> io::Result<TokenAndSpan> {
169         match self.lexer.try_next_token() {
170             Ok(tas) => Ok(tas),
171             Err(_) => {
172                 self.lexer.emit_fatal_errors();
173                 self.lexer.sess.span_diagnostic
174                     .struct_warn("Backing out of syntax highlighting")
175                     .note("You probably did not intend to render this as a rust code-block")
176                     .emit();
177                 Err(io::Error::new(io::ErrorKind::Other, ""))
178             }
179         }
180     }
181
182     /// Exhausts the `lexer` writing the output into `out`.
183     ///
184     /// The general structure for this method is to iterate over each token,
185     /// possibly giving it an HTML span with a class specifying what flavor of token
186     /// is used. All source code emission is done as slices from the source map,
187     /// not from the tokens themselves, in order to stay true to the original
188     /// source.
189     pub fn write_source<W: Writer>(&mut self,
190                                    out: &mut W)
191                                    -> io::Result<()> {
192         loop {
193             let next = self.try_next_token()?;
194             if next.tok == token::Eof {
195                 break;
196             }
197
198             self.write_token(out, next)?;
199         }
200
201         Ok(())
202     }
203
204     // Handles an individual token from the lexer.
205     fn write_token<W: Writer>(&mut self,
206                               out: &mut W,
207                               tas: TokenAndSpan)
208                               -> io::Result<()> {
209         let klass = match tas.tok {
210             token::Shebang(s) => {
211                 out.string(Escape(&s.as_str()), Class::None, Some(&tas))?;
212                 return Ok(());
213             },
214
215             token::Whitespace => Class::None,
216             token::Comment => Class::Comment,
217             token::DocComment(..) => Class::DocComment,
218
219             // If this '&' or '*' token is followed by a non-whitespace token, assume that it's the
220             // reference or dereference operator or a reference or pointer type, instead of the
221             // bit-and or multiplication operator.
222             token::BinOp(token::And) | token::BinOp(token::Star)
223                 if self.lexer.peek().tok != token::Whitespace => Class::RefKeyWord,
224
225             // Consider this as part of a macro invocation if there was a
226             // leading identifier.
227             token::Not if self.in_macro => {
228                 self.in_macro = false;
229                 Class::Macro
230             }
231
232             // Operators.
233             token::Eq | token::Lt | token::Le | token::EqEq | token::Ne | token::Ge | token::Gt |
234                 token::AndAnd | token::OrOr | token::Not | token::BinOp(..) | token::RArrow |
235                 token::BinOpEq(..) | token::FatArrow => Class::Op,
236
237             // Miscellaneous, no highlighting.
238             token::Dot | token::DotDot | token::DotDotDot | token::DotDotEq | token::Comma |
239                 token::Semi | token::Colon | token::ModSep | token::LArrow | token::OpenDelim(_) |
240                 token::CloseDelim(token::Brace) | token::CloseDelim(token::Paren) |
241                 token::CloseDelim(token::NoDelim) => Class::None,
242
243             token::Question => Class::QuestionMark,
244
245             token::Dollar => {
246                 if self.lexer.peek().tok.is_ident() {
247                     self.in_macro_nonterminal = true;
248                     Class::MacroNonTerminal
249                 } else {
250                     Class::None
251                 }
252             }
253
254             // This might be the start of an attribute. We're going to want to
255             // continue highlighting it as an attribute until the ending ']' is
256             // seen, so skip out early. Down below we terminate the attribute
257             // span when we see the ']'.
258             token::Pound => {
259                 // We can't be sure that our # begins an attribute (it could
260                 // just be appearing in a macro) until we read either `#![` or
261                 // `#[` from the input stream.
262                 //
263                 // We don't want to start highlighting as an attribute until
264                 // we're confident there is going to be a ] coming up, as
265                 // otherwise # tokens in macros highlight the rest of the input
266                 // as an attribute.
267
268                 // Case 1: #![inner_attribute]
269                 if self.lexer.peek().tok == token::Not {
270                     self.try_next_token()?; // NOTE: consumes `!` token!
271                     if self.lexer.peek().tok == token::OpenDelim(token::Bracket) {
272                         self.in_attribute = true;
273                         out.enter_span(Class::Attribute)?;
274                     }
275                     out.string("#", Class::None, None)?;
276                     out.string("!", Class::None, None)?;
277                     return Ok(());
278                 }
279
280                 // Case 2: #[outer_attribute]
281                 if self.lexer.peek().tok == token::OpenDelim(token::Bracket) {
282                     self.in_attribute = true;
283                     out.enter_span(Class::Attribute)?;
284                 }
285                 out.string("#", Class::None, None)?;
286                 return Ok(());
287             }
288             token::CloseDelim(token::Bracket) => {
289                 if self.in_attribute {
290                     self.in_attribute = false;
291                     out.string("]", Class::None, None)?;
292                     out.exit_span()?;
293                     return Ok(());
294                 } else {
295                     Class::None
296                 }
297             }
298
299             token::Literal(lit, _suf) => {
300                 match lit {
301                     // Text literals.
302                     token::Byte(..) | token::Char(..) |
303                         token::ByteStr(..) | token::ByteStrRaw(..) |
304                         token::Str_(..) | token::StrRaw(..) => Class::String,
305
306                     // Number literals.
307                     token::Integer(..) | token::Float(..) => Class::Number,
308                 }
309             }
310
311             // Keywords are also included in the identifier set.
312             token::Ident(ident, is_raw) => {
313                 match &*ident.as_str() {
314                     "ref" | "mut" if !is_raw => Class::RefKeyWord,
315
316                     "self" | "Self" => Class::Self_,
317                     "false" | "true" if !is_raw => Class::Bool,
318
319                     "Option" | "Result" => Class::PreludeTy,
320                     "Some" | "None" | "Ok" | "Err" => Class::PreludeVal,
321
322                     "$crate" => Class::KeyWord,
323                     _ if tas.tok.is_reserved_ident() => Class::KeyWord,
324
325                     _ => {
326                         if self.in_macro_nonterminal {
327                             self.in_macro_nonterminal = false;
328                             Class::MacroNonTerminal
329                         } else if self.lexer.peek().tok == token::Not {
330                             self.in_macro = true;
331                             Class::Macro
332                         } else {
333                             Class::Ident
334                         }
335                     }
336                 }
337             }
338
339             token::Lifetime(..) => Class::Lifetime,
340
341             token::Eof | token::Interpolated(..) |
342             token::Tilde | token::At | token::DotEq | token::SingleQuote => Class::None,
343         };
344
345         // Anything that didn't return above is the simple case where we the
346         // class just spans a single token, so we can use the `string` method.
347         out.string(Escape(&self.snip(tas.sp)), klass, Some(&tas))
348     }
349
350     // Helper function to get a snippet from the codemap.
351     fn snip(&self, sp: Span) -> String {
352         self.codemap.span_to_snippet(sp).unwrap()
353     }
354 }
355
356 impl Class {
357     /// Returns the css class expected by rustdoc for each `Class`.
358     pub fn rustdoc_class(self) -> &'static str {
359         match self {
360             Class::None => "",
361             Class::Comment => "comment",
362             Class::DocComment => "doccomment",
363             Class::Attribute => "attribute",
364             Class::KeyWord => "kw",
365             Class::RefKeyWord => "kw-2",
366             Class::Self_ => "self",
367             Class::Op => "op",
368             Class::Macro => "macro",
369             Class::MacroNonTerminal => "macro-nonterminal",
370             Class::String => "string",
371             Class::Number => "number",
372             Class::Bool => "bool-val",
373             Class::Ident => "ident",
374             Class::Lifetime => "lifetime",
375             Class::PreludeTy => "prelude-ty",
376             Class::PreludeVal => "prelude-val",
377             Class::QuestionMark => "question-mark"
378         }
379     }
380 }
381
382 fn write_header(class: Option<&str>,
383                 id: Option<&str>,
384                 out: &mut dyn Write)
385                 -> io::Result<()> {
386     write!(out, "<pre ")?;
387     if let Some(id) = id {
388         write!(out, "id='{}' ", id)?;
389     }
390     write!(out, "class=\"rust {}\">\n", class.unwrap_or(""))
391 }
392
393 fn write_footer(out: &mut dyn Write) -> io::Result<()> {
394     write!(out, "</pre>\n")
395 }