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