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 //! Use the `render_with_highlighting` to highlight some rust code.
18 use html::escape::Escape;
20 use std::fmt::Display;
22 use std::io::prelude::*;
24 use syntax::codemap::{CodeMap, FilePathMapping};
25 use syntax::parse::lexer::{self, TokenAndSpan};
26 use syntax::parse::token;
28 use syntax_pos::{Span, FileName};
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());
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();
44 write_header(class, &mut out).unwrap();
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);
51 if let Some(extension) = extension {
52 write!(out, "{}", extension).unwrap();
54 write_footer(&mut out).unwrap();
55 String::from_utf8_lossy(&out[..]).into_owned()
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>,
65 // State of the classifier.
68 in_macro_nonterminal: bool,
71 /// How a span of text is classified. Mostly corresponds to token kinds.
72 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
79 // Keywords that do pointer/reference stuff.
95 /// Trait that controls writing the output of syntax highlighting. Users should
96 /// implement this trait to customize writing output.
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.
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<()>;
106 /// Called at the end of a span of highlighted text.
107 fn exit_span(&mut self) -> io::Result<()>;
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`.
112 /// The following sequences of callbacks are equivalent:
114 /// enter_span(Foo), string("text", None), exit_span()
115 /// string("text", Foo)
117 /// The latter can be thought of as a shorthand for the former, which is
119 fn string<T: Display>(&mut self,
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,
133 Class::None => write!(self, "{}", text),
134 klass => write!(self, "<span class=\"{}\">{}</span>", klass.rustdoc_class(), text),
138 fn enter_span(&mut self, klass: Class) -> io::Result<()> {
139 write!(self, "<span class=\"{}\">", klass.rustdoc_class())
142 fn exit_span(&mut self) -> io::Result<()> {
143 write!(self, "</span>")
147 impl<'a> Classifier<'a> {
148 fn new(lexer: lexer::StringReader<'a>, codemap: &'a CodeMap) -> Classifier<'a> {
154 in_macro_nonterminal: false,
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() {
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")
168 Err(io::Error::new(io::ErrorKind::Other, ""))
173 /// Exhausts the `lexer` writing the output into `out`.
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
180 fn write_source<W: Writer>(&mut self,
184 let next = self.try_next_token()?;
185 if next.tok == token::Eof {
189 self.write_token(out, next)?;
195 // Handles an individual token from the lexer.
196 fn write_token<W: Writer>(&mut self,
200 let klass = match tas.tok {
201 token::Shebang(s) => {
202 out.string(Escape(&s.as_str()), Class::None)?;
206 token::Whitespace => Class::None,
207 token::Comment => Class::Comment,
208 token::DocComment(..) => Class::DocComment,
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,
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;
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,
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,
234 token::Question => Class::QuestionMark,
237 if self.lexer.peek().tok.is_ident() {
238 self.in_macro_nonterminal = true;
239 Class::MacroNonTerminal
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 ']'.
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.
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
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)?;
266 out.string("#", Class::None)?;
267 out.string("!", Class::None)?;
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)?;
276 out.string("#", Class::None)?;
279 token::CloseDelim(token::Bracket) => {
280 if self.in_attribute {
281 self.in_attribute = false;
282 out.string("]", Class::None)?;
290 token::Literal(lit, _suf) => {
293 token::Byte(..) | token::Char(..) |
294 token::ByteStr(..) | token::ByteStrRaw(..) |
295 token::Str_(..) | token::StrRaw(..) => Class::String,
298 token::Integer(..) | token::Float(..) => Class::Number,
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,
307 "self" | "Self" => Class::Self_,
308 "false" | "true" if !is_raw => Class::Bool,
310 "Option" | "Result" => Class::PreludeTy,
311 "Some" | "None" | "Ok" | "Err" => Class::PreludeVal,
313 "$crate" => Class::KeyWord,
314 _ if tas.tok.is_reserved_ident() => Class::KeyWord,
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;
330 token::Lifetime(..) => Class::Lifetime,
332 token::Eof | token::Interpolated(..) |
333 token::Tilde | token::At | token::DotEq | token::SingleQuote => Class::None,
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)
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()
348 /// Returns the css class expected by rustdoc for each `Class`.
349 fn rustdoc_class(self) -> &'static str {
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",
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"
373 fn write_header(class: Option<&str>, out: &mut dyn Write) -> io::Result<()> {
374 write!(out, "<pre class=\"rust {}\">\n", class.unwrap_or(""))
377 fn write_footer(out: &mut dyn Write) -> io::Result<()> {
378 write!(out, "</pre>\n")