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;
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());
42 let mut out = Vec::new();
43 write_header(class, id, &mut out).unwrap();
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);
50 if let Some(extension) = extension {
51 write!(out, "{}", extension).unwrap();
53 write_footer(&mut out).unwrap();
54 String::from_utf8_lossy(&out[..]).into_owned()
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());
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)?;
68 Ok(String::from_utf8_lossy(&out).into_owned())
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>,
78 // State of the classifier.
81 in_macro_nonterminal: bool,
84 /// How a span of text is classified. Mostly corresponds to token kinds.
85 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
92 // Keywords that do pointer/reference stuff.
108 /// Trait that controls writing the output of syntax highlighting. Users should
109 /// implement this trait to customize writing output.
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.
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<()>;
119 /// Called at the end of a span of highlighted text.
120 fn exit_span(&mut self) -> io::Result<()>;
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
127 /// The following sequences of callbacks are equivalent:
129 /// enter_span(Foo), string("text", None), exit_span()
130 /// string("text", Foo)
132 /// The latter can be thought of as a shorthand for the former, which is
134 fn string<T: Display>(&mut self,
137 tok: Option<&TokenAndSpan>)
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,
147 _tas: Option<&TokenAndSpan>)
150 Class::None => write!(self, "{}", text),
151 klass => write!(self, "<span class=\"{}\">{}</span>", klass.rustdoc_class(), text),
155 fn enter_span(&mut self, klass: Class) -> io::Result<()> {
156 write!(self, "<span class=\"{}\">", klass.rustdoc_class())
159 fn exit_span(&mut self) -> io::Result<()> {
160 write!(self, "</span>")
164 impl<'a> Classifier<'a> {
165 pub fn new(lexer: lexer::StringReader<'a>, codemap: &'a CodeMap) -> Classifier<'a> {
171 in_macro_nonterminal: false,
175 /// Exhausts the `lexer` writing the output into `out`.
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
182 pub fn write_source<W: Writer>(&mut self,
186 let next = match self.lexer.try_next_token() {
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")
194 return Err(io::Error::new(io::ErrorKind::Other, ""));
198 if next.tok == token::Eof {
202 self.write_token(out, next)?;
208 // Handles an individual token from the lexer.
209 fn write_token<W: Writer>(&mut self,
213 let klass = match tas.tok {
214 token::Shebang(s) => {
215 out.string(Escape(&s.as_str()), Class::None, Some(&tas))?;
219 token::Whitespace => Class::None,
220 token::Comment => Class::Comment,
221 token::DocComment(..) => Class::DocComment,
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,
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;
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,
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,
247 token::Question => Class::QuestionMark,
250 if self.lexer.peek().tok.is_ident() {
251 self.in_macro_nonterminal = true;
252 Class::MacroNonTerminal
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 ']'.
263 self.in_attribute = true;
264 out.enter_span(Class::Attribute)?;
265 out.string("#", Class::None, None)?;
268 token::CloseDelim(token::Bracket) => {
269 if self.in_attribute {
270 self.in_attribute = false;
271 out.string("]", Class::None, None)?;
279 token::Literal(lit, _suf) => {
282 token::Byte(..) | token::Char(..) |
283 token::ByteStr(..) | token::ByteStrRaw(..) |
284 token::Str_(..) | token::StrRaw(..) => Class::String,
287 token::Integer(..) | token::Float(..) => Class::Number,
291 // Keywords are also included in the identifier set.
292 token::Ident(ident) => {
293 match &*ident.name.as_str() {
294 "ref" | "mut" => Class::RefKeyWord,
296 "self" |"Self" => Class::Self_,
297 "false" | "true" => Class::Bool,
299 "Option" | "Result" => Class::PreludeTy,
300 "Some" | "None" | "Ok" | "Err" => Class::PreludeVal,
302 "$crate" => Class::KeyWord,
303 _ if tas.tok.is_reserved_ident() => Class::KeyWord,
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;
319 token::Lifetime(..) => Class::Lifetime,
321 token::Underscore | token::Eof | token::Interpolated(..) |
322 token::Tilde | token::At => Class::None,
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))
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()
337 /// Returns the css class expected by rustdoc for each `Class`.
338 pub fn rustdoc_class(self) -> &'static str {
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",
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"
362 fn write_header(class: Option<&str>,
366 write!(out, "<pre ")?;
367 if let Some(id) = id {
368 write!(out, "id='{}' ", id)?;
370 write!(out, "class=\"rust {}\">\n", class.unwrap_or(""))
373 fn write_footer(out: &mut Write) -> io::Result<()> {
374 write!(out, "</pre>\n")