]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/highlight.rs
Fixes issue #43205: ICE in Rvalue::Len evaluation.
[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     /// 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     pub fn write_source<W: Writer>(&mut self,
183                                    out: &mut W)
184                                    -> io::Result<()> {
185         loop {
186             let next = match self.lexer.try_next_token() {
187                 Ok(tas) => tas,
188                 Err(_) => {
189                     self.lexer.emit_fatal_errors();
190                     self.lexer.sess.span_diagnostic
191                         .struct_warn("Backing out of syntax highlighting")
192                         .note("You probably did not intend to render this as a rust code-block")
193                         .emit();
194                     return Err(io::Error::new(io::ErrorKind::Other, ""));
195                 }
196             };
197
198             if next.tok == token::Eof {
199                 break;
200             }
201
202             self.write_token(out, next)?;
203         }
204
205         Ok(())
206     }
207
208     // Handles an individual token from the lexer.
209     fn write_token<W: Writer>(&mut self,
210                               out: &mut W,
211                               tas: TokenAndSpan)
212                               -> io::Result<()> {
213         let klass = match tas.tok {
214             token::Shebang(s) => {
215                 out.string(Escape(&s.as_str()), Class::None, Some(&tas))?;
216                 return Ok(());
217             },
218
219             token::Whitespace => Class::None,
220             token::Comment => Class::Comment,
221             token::DocComment(..) => Class::DocComment,
222
223             // If this '&' or '*' token is followed by a non-whitespace token, assume that it's the
224             // reference or dereference operator or a reference or pointer type, instead of the
225             // bit-and or multiplication operator.
226             token::BinOp(token::And) | token::BinOp(token::Star)
227                 if self.lexer.peek().tok != token::Whitespace => Class::RefKeyWord,
228
229             // Consider this as part of a macro invocation if there was a
230             // leading identifier.
231             token::Not if self.in_macro => {
232                 self.in_macro = false;
233                 Class::Macro
234             }
235
236             // Operators.
237             token::Eq | token::Lt | token::Le | token::EqEq | token::Ne | token::Ge | token::Gt |
238                 token::AndAnd | token::OrOr | token::Not | token::BinOp(..) | token::RArrow |
239                 token::BinOpEq(..) | token::FatArrow => Class::Op,
240
241             // Miscellaneous, no highlighting.
242             token::Dot | token::DotDot | token::DotDotDot | token::Comma | token::Semi |
243                 token::Colon | token::ModSep | token::LArrow | token::OpenDelim(_) |
244                 token::CloseDelim(token::Brace) | token::CloseDelim(token::Paren) |
245                 token::CloseDelim(token::NoDelim) => Class::None,
246
247             token::Question => Class::QuestionMark,
248
249             token::Dollar => {
250                 if self.lexer.peek().tok.is_ident() {
251                     self.in_macro_nonterminal = true;
252                     Class::MacroNonTerminal
253                 } else {
254                     Class::None
255                 }
256             }
257
258             // This is the start of an attribute. We're going to want to
259             // continue highlighting it as an attribute until the ending ']' is
260             // seen, so skip out early. Down below we terminate the attribute
261             // span when we see the ']'.
262             token::Pound => {
263                 self.in_attribute = true;
264                 out.enter_span(Class::Attribute)?;
265                 out.string("#", Class::None, None)?;
266                 return Ok(());
267             }
268             token::CloseDelim(token::Bracket) => {
269                 if self.in_attribute {
270                     self.in_attribute = false;
271                     out.string("]", Class::None, None)?;
272                     out.exit_span()?;
273                     return Ok(());
274                 } else {
275                     Class::None
276                 }
277             }
278
279             token::Literal(lit, _suf) => {
280                 match lit {
281                     // Text literals.
282                     token::Byte(..) | token::Char(..) |
283                         token::ByteStr(..) | token::ByteStrRaw(..) |
284                         token::Str_(..) | token::StrRaw(..) => Class::String,
285
286                     // Number literals.
287                     token::Integer(..) | token::Float(..) => Class::Number,
288                 }
289             }
290
291             // Keywords are also included in the identifier set.
292             token::Ident(ident) => {
293                 match &*ident.name.as_str() {
294                     "ref" | "mut" => Class::RefKeyWord,
295
296                     "self" |"Self" => Class::Self_,
297                     "false" | "true" => Class::Bool,
298
299                     "Option" | "Result" => Class::PreludeTy,
300                     "Some" | "None" | "Ok" | "Err" => Class::PreludeVal,
301
302                     "$crate" => Class::KeyWord,
303                     _ if tas.tok.is_reserved_ident() => Class::KeyWord,
304
305                     _ => {
306                         if self.in_macro_nonterminal {
307                             self.in_macro_nonterminal = false;
308                             Class::MacroNonTerminal
309                         } else if self.lexer.peek().tok == token::Not {
310                             self.in_macro = true;
311                             Class::Macro
312                         } else {
313                             Class::Ident
314                         }
315                     }
316                 }
317             }
318
319             token::Lifetime(..) => Class::Lifetime,
320
321             token::Underscore | token::Eof | token::Interpolated(..) |
322             token::Tilde | token::At => Class::None,
323         };
324
325         // Anything that didn't return above is the simple case where we the
326         // class just spans a single token, so we can use the `string` method.
327         out.string(Escape(&self.snip(tas.sp)), klass, Some(&tas))
328     }
329
330     // Helper function to get a snippet from the codemap.
331     fn snip(&self, sp: Span) -> String {
332         self.codemap.span_to_snippet(sp).unwrap()
333     }
334 }
335
336 impl Class {
337     /// Returns the css class expected by rustdoc for each `Class`.
338     pub fn rustdoc_class(self) -> &'static str {
339         match self {
340             Class::None => "",
341             Class::Comment => "comment",
342             Class::DocComment => "doccomment",
343             Class::Attribute => "attribute",
344             Class::KeyWord => "kw",
345             Class::RefKeyWord => "kw-2",
346             Class::Self_ => "self",
347             Class::Op => "op",
348             Class::Macro => "macro",
349             Class::MacroNonTerminal => "macro-nonterminal",
350             Class::String => "string",
351             Class::Number => "number",
352             Class::Bool => "bool-val",
353             Class::Ident => "ident",
354             Class::Lifetime => "lifetime",
355             Class::PreludeTy => "prelude-ty",
356             Class::PreludeVal => "prelude-val",
357             Class::QuestionMark => "question-mark"
358         }
359     }
360 }
361
362 fn write_header(class: Option<&str>,
363                 id: Option<&str>,
364                 out: &mut Write)
365                 -> io::Result<()> {
366     write!(out, "<pre ")?;
367     if let Some(id) = id {
368         write!(out, "id='{}' ", id)?;
369     }
370     write!(out, "class=\"rust {}\">\n", class.unwrap_or(""))
371 }
372
373 fn write_footer(out: &mut Write) -> io::Result<()> {
374     write!(out, "</pre>\n")
375 }