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.
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.
11 //! Basic syntax highlighting functionality.
13 //! This module uses libsyntax's lexer to provide token-based highlighting for
14 //! the HTML documentation generated by rustdoc.
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
23 use html::escape::Escape;
25 use std::fmt::Display;
27 use std::io::prelude::*;
29 use syntax::codemap::{CodeMap, FilePathMapping};
30 use syntax::parse::lexer::{self, TokenAndSpan};
31 use syntax::parse::token;
33 use syntax_pos::{Span, FileName};
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>,
38 tooltip: Option<(&str, &str)>) -> String {
39 debug!("highlighting: ================\n{}\n==============", src);
40 let sess = parse::ParseSess::new(FilePathMapping::empty());
41 let fm = sess.codemap().new_filemap(FileName::Custom("stdin".to_string()), src.to_string());
43 let mut out = Vec::new();
44 if let Some((tooltip, class)) = tooltip {
45 write!(out, "<div class='information'><div class='tooltip {}'>ⓘ<span \
46 class='tooltiptext'>{}</span></div></div>",
47 class, tooltip).unwrap();
49 write_header(class, id, &mut out).unwrap();
51 let mut classifier = Classifier::new(lexer::StringReader::new(&sess, fm, None), sess.codemap());
52 if let Err(_) = classifier.write_source(&mut out) {
53 return format!("<pre>{}</pre>", src);
56 if let Some(extension) = extension {
57 write!(out, "{}", extension).unwrap();
59 write_footer(&mut out).unwrap();
60 String::from_utf8_lossy(&out[..]).into_owned()
63 /// Processes a program (nested in the internal `lexer`), classifying strings of
64 /// text by highlighting category (`Class`). Calls out to a `Writer` to write
65 /// each span of text in sequence.
66 pub struct Classifier<'a> {
67 lexer: lexer::StringReader<'a>,
70 // State of the classifier.
73 in_macro_nonterminal: bool,
76 /// How a span of text is classified. Mostly corresponds to token kinds.
77 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
84 // Keywords that do pointer/reference stuff.
100 /// Trait that controls writing the output of syntax highlighting. Users should
101 /// implement this trait to customize writing output.
103 /// The classifier will call into the `Writer` implementation as it finds spans
104 /// of text to highlight. Exactly how that text should be highlighted is up to
105 /// the implementation.
107 /// Called when we start processing a span of text that should be highlighted.
108 /// The `Class` argument specifies how it should be highlighted.
109 fn enter_span(&mut self, _: Class) -> io::Result<()>;
111 /// Called at the end of a span of highlighted text.
112 fn exit_span(&mut self) -> io::Result<()>;
114 /// Called for a span of text, usually, but not always, a single token. If
115 /// the string of text (`T`) does correspond to a token, then the token will
116 /// also be passed. If the text should be highlighted differently from the
117 /// surrounding text, then the `Class` argument will be a value other than
119 /// The following sequences of callbacks are equivalent:
121 /// enter_span(Foo), string("text", None), exit_span()
122 /// string("text", Foo)
124 /// The latter can be thought of as a shorthand for the former, which is
126 fn string<T: Display>(&mut self,
129 tok: Option<&TokenAndSpan>)
133 // Implement `Writer` for anthing that can be written to, this just implements
134 // the default rustdoc behaviour.
135 impl<U: Write> Writer for U {
136 fn string<T: Display>(&mut self,
139 _tas: Option<&TokenAndSpan>)
142 Class::None => write!(self, "{}", text),
143 klass => write!(self, "<span class=\"{}\">{}</span>", klass.rustdoc_class(), text),
147 fn enter_span(&mut self, klass: Class) -> io::Result<()> {
148 write!(self, "<span class=\"{}\">", klass.rustdoc_class())
151 fn exit_span(&mut self) -> io::Result<()> {
152 write!(self, "</span>")
156 impl<'a> Classifier<'a> {
157 pub fn new(lexer: lexer::StringReader<'a>, codemap: &'a CodeMap) -> Classifier<'a> {
163 in_macro_nonterminal: false,
167 /// Gets the next token out of the lexer, emitting fatal errors if lexing fails.
168 fn try_next_token(&mut self) -> io::Result<TokenAndSpan> {
169 match self.lexer.try_next_token() {
172 self.lexer.emit_fatal_errors();
173 self.lexer.sess.span_diagnostic
174 .struct_warn("Backing out of syntax highlighting")
175 .note("You probably did not intend to render this as a rust code-block")
177 Err(io::Error::new(io::ErrorKind::Other, ""))
182 /// Exhausts the `lexer` writing the output into `out`.
184 /// The general structure for this method is to iterate over each token,
185 /// possibly giving it an HTML span with a class specifying what flavor of token
186 /// is used. All source code emission is done as slices from the source map,
187 /// not from the tokens themselves, in order to stay true to the original
189 pub fn write_source<W: Writer>(&mut self,
193 let next = self.try_next_token()?;
194 if next.tok == token::Eof {
198 self.write_token(out, next)?;
204 // Handles an individual token from the lexer.
205 fn write_token<W: Writer>(&mut self,
209 let klass = match tas.tok {
210 token::Shebang(s) => {
211 out.string(Escape(&s.as_str()), Class::None, Some(&tas))?;
215 token::Whitespace => Class::None,
216 token::Comment => Class::Comment,
217 token::DocComment(..) => Class::DocComment,
219 // If this '&' or '*' token is followed by a non-whitespace token, assume that it's the
220 // reference or dereference operator or a reference or pointer type, instead of the
221 // bit-and or multiplication operator.
222 token::BinOp(token::And) | token::BinOp(token::Star)
223 if self.lexer.peek().tok != token::Whitespace => Class::RefKeyWord,
225 // Consider this as part of a macro invocation if there was a
226 // leading identifier.
227 token::Not if self.in_macro => {
228 self.in_macro = false;
233 token::Eq | token::Lt | token::Le | token::EqEq | token::Ne | token::Ge | token::Gt |
234 token::AndAnd | token::OrOr | token::Not | token::BinOp(..) | token::RArrow |
235 token::BinOpEq(..) | token::FatArrow => Class::Op,
237 // Miscellaneous, no highlighting.
238 token::Dot | token::DotDot | token::DotDotDot | token::DotDotEq | token::Comma |
239 token::Semi | token::Colon | token::ModSep | token::LArrow | token::OpenDelim(_) |
240 token::CloseDelim(token::Brace) | token::CloseDelim(token::Paren) |
241 token::CloseDelim(token::NoDelim) => Class::None,
243 token::Question => Class::QuestionMark,
246 if self.lexer.peek().tok.is_ident() {
247 self.in_macro_nonterminal = true;
248 Class::MacroNonTerminal
254 // This might be the start of an attribute. We're going to want to
255 // continue highlighting it as an attribute until the ending ']' is
256 // seen, so skip out early. Down below we terminate the attribute
257 // span when we see the ']'.
259 // We can't be sure that our # begins an attribute (it could
260 // just be appearing in a macro) until we read either `#![` or
261 // `#[` from the input stream.
263 // We don't want to start highlighting as an attribute until
264 // we're confident there is going to be a ] coming up, as
265 // otherwise # tokens in macros highlight the rest of the input
268 // Case 1: #![inner_attribute]
269 if self.lexer.peek().tok == token::Not {
270 self.try_next_token()?; // NOTE: consumes `!` token!
271 if self.lexer.peek().tok == token::OpenDelim(token::Bracket) {
272 self.in_attribute = true;
273 out.enter_span(Class::Attribute)?;
275 out.string("#", Class::None, None)?;
276 out.string("!", Class::None, None)?;
280 // Case 2: #[outer_attribute]
281 if self.lexer.peek().tok == token::OpenDelim(token::Bracket) {
282 self.in_attribute = true;
283 out.enter_span(Class::Attribute)?;
285 out.string("#", Class::None, None)?;
288 token::CloseDelim(token::Bracket) => {
289 if self.in_attribute {
290 self.in_attribute = false;
291 out.string("]", Class::None, None)?;
299 token::Literal(lit, _suf) => {
302 token::Byte(..) | token::Char(..) |
303 token::ByteStr(..) | token::ByteStrRaw(..) |
304 token::Str_(..) | token::StrRaw(..) => Class::String,
307 token::Integer(..) | token::Float(..) => Class::Number,
311 // Keywords are also included in the identifier set.
312 token::Ident(ident, is_raw) => {
313 match &*ident.as_str() {
314 "ref" | "mut" if !is_raw => Class::RefKeyWord,
316 "self" | "Self" => Class::Self_,
317 "false" | "true" if !is_raw => Class::Bool,
319 "Option" | "Result" => Class::PreludeTy,
320 "Some" | "None" | "Ok" | "Err" => Class::PreludeVal,
322 "$crate" => Class::KeyWord,
323 _ if tas.tok.is_reserved_ident() => Class::KeyWord,
326 if self.in_macro_nonterminal {
327 self.in_macro_nonterminal = false;
328 Class::MacroNonTerminal
329 } else if self.lexer.peek().tok == token::Not {
330 self.in_macro = true;
339 token::Lifetime(..) => Class::Lifetime,
341 token::Eof | token::Interpolated(..) |
342 token::Tilde | token::At | token::DotEq | token::SingleQuote => Class::None,
345 // Anything that didn't return above is the simple case where we the
346 // class just spans a single token, so we can use the `string` method.
347 out.string(Escape(&self.snip(tas.sp)), klass, Some(&tas))
350 // Helper function to get a snippet from the codemap.
351 fn snip(&self, sp: Span) -> String {
352 self.codemap.span_to_snippet(sp).unwrap()
357 /// Returns the css class expected by rustdoc for each `Class`.
358 pub fn rustdoc_class(self) -> &'static str {
361 Class::Comment => "comment",
362 Class::DocComment => "doccomment",
363 Class::Attribute => "attribute",
364 Class::KeyWord => "kw",
365 Class::RefKeyWord => "kw-2",
366 Class::Self_ => "self",
368 Class::Macro => "macro",
369 Class::MacroNonTerminal => "macro-nonterminal",
370 Class::String => "string",
371 Class::Number => "number",
372 Class::Bool => "bool-val",
373 Class::Ident => "ident",
374 Class::Lifetime => "lifetime",
375 Class::PreludeTy => "prelude-ty",
376 Class::PreludeVal => "prelude-val",
377 Class::QuestionMark => "question-mark"
382 fn write_header(class: Option<&str>,
386 write!(out, "<pre ")?;
387 if let Some(id) = id {
388 write!(out, "id='{}' ", id)?;
390 write!(out, "class=\"rust {}\">\n", class.unwrap_or(""))
393 fn write_footer(out: &mut dyn Write) -> io::Result<()> {
394 write!(out, "</pre>\n")