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::source_map::{SourceMap, 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.source_map().new_source_file(FileName::Custom("stdin".to_string()),
39 let mut out = Vec::new();
40 if let Some((tooltip, class)) = tooltip {
41 write!(out, "<div class='information'><div class='tooltip {}'>ⓘ<span \
42 class='tooltiptext'>{}</span></div></div>",
43 class, tooltip).unwrap();
45 write_header(class, &mut out).unwrap();
47 let mut classifier = Classifier::new(lexer::StringReader::new(&sess, fm, None),
49 if classifier.write_source(&mut out).is_err() {
50 return format!("<pre>{}</pre>", src);
53 if let Some(extension) = extension {
54 write!(out, "{}", extension).unwrap();
56 write_footer(&mut out).unwrap();
57 String::from_utf8_lossy(&out[..]).into_owned()
60 /// Processes a program (nested in the internal `lexer`), classifying strings of
61 /// text by highlighting category (`Class`). Calls out to a `Writer` to write
62 /// each span of text in sequence.
63 struct Classifier<'a> {
64 lexer: lexer::StringReader<'a>,
65 source_map: &'a SourceMap,
67 // State of the classifier.
70 in_macro_nonterminal: bool,
73 /// How a span of text is classified. Mostly corresponds to token kinds.
74 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
81 // Keywords that do pointer/reference stuff.
97 /// Trait that controls writing the output of syntax highlighting. Users should
98 /// implement this trait to customize writing output.
100 /// The classifier will call into the `Writer` implementation as it finds spans
101 /// of text to highlight. Exactly how that text should be highlighted is up to
102 /// the implementation.
104 /// Called when we start processing a span of text that should be highlighted.
105 /// The `Class` argument specifies how it should be highlighted.
106 fn enter_span(&mut self, _: Class) -> io::Result<()>;
108 /// Called at the end of a span of highlighted text.
109 fn exit_span(&mut self) -> io::Result<()>;
111 /// Called for a span of text. If the text should be highlighted differently from the
112 /// surrounding text, then the `Class` argument will be a value other than `None`.
114 /// The following sequences of callbacks are equivalent:
116 /// enter_span(Foo), string("text", None), exit_span()
117 /// string("text", Foo)
119 /// The latter can be thought of as a shorthand for the former, which is
121 fn string<T: Display>(&mut self,
127 // Implement `Writer` for anthing that can be written to, this just implements
128 // the default rustdoc behaviour.
129 impl<U: Write> Writer for U {
130 fn string<T: Display>(&mut self,
135 Class::None => write!(self, "{}", text),
136 klass => write!(self, "<span class=\"{}\">{}</span>", klass.rustdoc_class(), text),
140 fn enter_span(&mut self, klass: Class) -> io::Result<()> {
141 write!(self, "<span class=\"{}\">", klass.rustdoc_class())
144 fn exit_span(&mut self) -> io::Result<()> {
145 write!(self, "</span>")
149 impl<'a> Classifier<'a> {
150 fn new(lexer: lexer::StringReader<'a>, source_map: &'a SourceMap) -> Classifier<'a> {
156 in_macro_nonterminal: false,
160 /// Gets the next token out of the lexer, emitting fatal errors if lexing fails.
161 fn try_next_token(&mut self) -> io::Result<TokenAndSpan> {
162 match self.lexer.try_next_token() {
165 self.lexer.emit_fatal_errors();
166 self.lexer.sess.span_diagnostic
167 .struct_warn("Backing out of syntax highlighting")
168 .note("You probably did not intend to render this as a rust code-block")
170 Err(io::Error::new(io::ErrorKind::Other, ""))
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 fn write_source<W: Writer>(&mut self,
186 let next = self.try_next_token()?;
187 if next.tok == token::Eof {
191 self.write_token(out, next)?;
197 // Handles an individual token from the lexer.
198 fn write_token<W: Writer>(&mut self,
202 let klass = match tas.tok {
203 token::Shebang(s) => {
204 out.string(Escape(&s.as_str()), Class::None)?;
208 token::Whitespace => Class::None,
209 token::Comment => Class::Comment,
210 token::DocComment(..) => Class::DocComment,
212 // If this '&' or '*' token is followed by a non-whitespace token, assume that it's the
213 // reference or dereference operator or a reference or pointer type, instead of the
214 // bit-and or multiplication operator.
215 token::BinOp(token::And) | token::BinOp(token::Star)
216 if self.lexer.peek().tok != token::Whitespace => Class::RefKeyWord,
218 // Consider this as part of a macro invocation if there was a
219 // leading identifier.
220 token::Not if self.in_macro => {
221 self.in_macro = false;
226 token::Eq | token::Lt | token::Le | token::EqEq | token::Ne | token::Ge | token::Gt |
227 token::AndAnd | token::OrOr | token::Not | token::BinOp(..) | token::RArrow |
228 token::BinOpEq(..) | token::FatArrow => Class::Op,
230 // Miscellaneous, no highlighting.
231 token::Dot | token::DotDot | token::DotDotDot | token::DotDotEq | token::Comma |
232 token::Semi | token::Colon | token::ModSep | token::LArrow | token::OpenDelim(_) |
233 token::CloseDelim(token::Brace) | token::CloseDelim(token::Paren) |
234 token::CloseDelim(token::NoDelim) => Class::None,
236 token::Question => Class::QuestionMark,
239 if self.lexer.peek().tok.is_ident() {
240 self.in_macro_nonterminal = true;
241 Class::MacroNonTerminal
247 // This might be the start of an attribute. We're going to want to
248 // continue highlighting it as an attribute until the ending ']' is
249 // seen, so skip out early. Down below we terminate the attribute
250 // span when we see the ']'.
252 // We can't be sure that our # begins an attribute (it could
253 // just be appearing in a macro) until we read either `#![` or
254 // `#[` from the input stream.
256 // We don't want to start highlighting as an attribute until
257 // we're confident there is going to be a ] coming up, as
258 // otherwise # tokens in macros highlight the rest of the input
261 // Case 1: #![inner_attribute]
262 if self.lexer.peek().tok == token::Not {
263 self.try_next_token()?; // NOTE: consumes `!` token!
264 if self.lexer.peek().tok == token::OpenDelim(token::Bracket) {
265 self.in_attribute = true;
266 out.enter_span(Class::Attribute)?;
268 out.string("#", Class::None)?;
269 out.string("!", Class::None)?;
273 // Case 2: #[outer_attribute]
274 if self.lexer.peek().tok == token::OpenDelim(token::Bracket) {
275 self.in_attribute = true;
276 out.enter_span(Class::Attribute)?;
278 out.string("#", Class::None)?;
281 token::CloseDelim(token::Bracket) => {
282 if self.in_attribute {
283 self.in_attribute = false;
284 out.string("]", Class::None)?;
292 token::Literal(lit, _suf) => {
295 token::Byte(..) | token::Char(..) |
296 token::ByteStr(..) | token::ByteStrRaw(..) |
297 token::Str_(..) | token::StrRaw(..) => Class::String,
300 token::Integer(..) | token::Float(..) => Class::Number,
304 // Keywords are also included in the identifier set.
305 token::Ident(ident, is_raw) => {
306 match &*ident.as_str() {
307 "ref" | "mut" if !is_raw => Class::RefKeyWord,
309 "self" | "Self" => Class::Self_,
310 "false" | "true" if !is_raw => Class::Bool,
312 "Option" | "Result" => Class::PreludeTy,
313 "Some" | "None" | "Ok" | "Err" => Class::PreludeVal,
315 "$crate" => Class::KeyWord,
316 _ if tas.tok.is_reserved_ident() => Class::KeyWord,
319 if self.in_macro_nonterminal {
320 self.in_macro_nonterminal = false;
321 Class::MacroNonTerminal
322 } else if self.lexer.peek().tok == token::Not {
323 self.in_macro = true;
332 token::Lifetime(..) => Class::Lifetime,
334 token::Eof | token::Interpolated(..) |
335 token::Tilde | token::At | token::DotEq | token::SingleQuote => Class::None,
338 // Anything that didn't return above is the simple case where we the
339 // class just spans a single token, so we can use the `string` method.
340 out.string(Escape(&self.snip(tas.sp)), klass)
343 // Helper function to get a snippet from the source_map.
344 fn snip(&self, sp: Span) -> String {
345 self.source_map.span_to_snippet(sp).unwrap()
350 /// Returns the css class expected by rustdoc for each `Class`.
351 fn rustdoc_class(self) -> &'static str {
354 Class::Comment => "comment",
355 Class::DocComment => "doccomment",
356 Class::Attribute => "attribute",
357 Class::KeyWord => "kw",
358 Class::RefKeyWord => "kw-2",
359 Class::Self_ => "self",
361 Class::Macro => "macro",
362 Class::MacroNonTerminal => "macro-nonterminal",
363 Class::String => "string",
364 Class::Number => "number",
365 Class::Bool => "bool-val",
366 Class::Ident => "ident",
367 Class::Lifetime => "lifetime",
368 Class::PreludeTy => "prelude-ty",
369 Class::PreludeVal => "prelude-val",
370 Class::QuestionMark => "question-mark"
375 fn write_header(class: Option<&str>, out: &mut dyn Write) -> io::Result<()> {
376 write!(out, "<pre class=\"rust {}\">\n", class.unwrap_or(""))
379 fn write_footer(out: &mut dyn Write) -> io::Result<()> {
380 write!(out, "</pre>\n")