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