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