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