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(
34 extension: Option<&str>,
35 tooltip: Option<(&str, &str)>,
37 debug!("highlighting: ================\n{}\n==============", src);
38 let sess = parse::ParseSess::new(FilePathMapping::empty());
39 let fm = sess.source_map().new_source_file(FileName::Custom("stdin".to_string()),
42 let mut out = Vec::new();
43 if let Some((tooltip, class)) = tooltip {
44 write!(out, "<div class='information'><div class='tooltip {}'>ⓘ<span \
45 class='tooltiptext'>{}</span></div></div>",
46 class, tooltip).unwrap();
48 write_header(class, &mut out).unwrap();
50 let lexer = match lexer::StringReader::new_without_err(&sess, fm, None, "Output from rustc:") {
53 let first_line = src.lines().next().unwrap_or_else(|| "");
54 let mut err = sess.span_diagnostic
55 .struct_warn(&format!("Invalid doc comment starting with: `{}`\n\
56 (Ignoring this codeblock)",
62 let mut classifier = Classifier::new(lexer, sess.source_map());
63 if classifier.write_source(&mut out).is_err() {
64 classifier.lexer.emit_fatal_errors();
65 return format!("<pre>{}</pre>", src);
68 if let Some(extension) = extension {
69 write!(out, "{}", extension).unwrap();
71 write_footer(&mut out).unwrap();
72 String::from_utf8_lossy(&out[..]).into_owned()
75 /// Processes a program (nested in the internal `lexer`), classifying strings of
76 /// text by highlighting category (`Class`). Calls out to a `Writer` to write
77 /// each span of text in sequence.
78 struct Classifier<'a> {
79 lexer: lexer::StringReader<'a>,
80 source_map: &'a SourceMap,
82 // State of the classifier.
85 in_macro_nonterminal: bool,
88 /// How a span of text is classified. Mostly corresponds to token kinds.
89 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
96 // Keywords that do pointer/reference stuff.
112 /// Trait that controls writing the output of syntax highlighting. Users should
113 /// implement this trait to customize writing output.
115 /// The classifier will call into the `Writer` implementation as it finds spans
116 /// of text to highlight. Exactly how that text should be highlighted is up to
117 /// the implementation.
119 /// Called when we start processing a span of text that should be highlighted.
120 /// The `Class` argument specifies how it should be highlighted.
121 fn enter_span(&mut self, _: Class) -> io::Result<()>;
123 /// Called at the end of a span of highlighted text.
124 fn exit_span(&mut self) -> io::Result<()>;
126 /// Called for a span of text. If the text should be highlighted differently from the
127 /// surrounding text, then the `Class` argument will be a value other than `None`.
129 /// The following sequences of callbacks are equivalent:
131 /// enter_span(Foo), string("text", None), exit_span()
132 /// string("text", Foo)
134 /// The latter can be thought of as a shorthand for the former, which is
136 fn string<T: Display>(&mut self,
142 // Implement `Writer` for anthing that can be written to, this just implements
143 // the default rustdoc behaviour.
144 impl<U: Write> Writer for U {
145 fn string<T: Display>(&mut self,
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 fn new(lexer: lexer::StringReader<'a>, source_map: &'a SourceMap) -> Classifier<'a> {
171 in_macro_nonterminal: false,
175 /// Gets the next token out of the lexer, emitting fatal errors if lexing fails.
176 fn try_next_token(&mut self) -> io::Result<TokenAndSpan> {
177 match self.lexer.try_next_token() {
180 let mut err = self.lexer.sess.span_diagnostic
181 .struct_warn("Backing out of syntax highlighting");
182 err.note("You probably did not intend to render this as a rust code-block");
184 Err(io::Error::new(io::ErrorKind::Other, ""))
189 /// Exhausts the `lexer` writing the output into `out`.
191 /// The general structure for this method is to iterate over each token,
192 /// possibly giving it an HTML span with a class specifying what flavor of token
193 /// is used. All source code emission is done as slices from the source map,
194 /// not from the tokens themselves, in order to stay true to the original
196 fn write_source<W: Writer>(&mut self,
200 let next = self.try_next_token()?;
201 if next.tok == token::Eof {
205 self.write_token(out, next)?;
211 // Handles an individual token from the lexer.
212 fn write_token<W: Writer>(&mut self,
216 let klass = match tas.tok {
217 token::Shebang(s) => {
218 out.string(Escape(&s.as_str()), Class::None)?;
222 token::Whitespace => Class::None,
223 token::Comment => Class::Comment,
224 token::DocComment(..) => Class::DocComment,
226 // If this '&' or '*' token is followed by a non-whitespace token, assume that it's the
227 // reference or dereference operator or a reference or pointer type, instead of the
228 // bit-and or multiplication operator.
229 token::BinOp(token::And) | token::BinOp(token::Star)
230 if self.lexer.peek().tok != token::Whitespace => Class::RefKeyWord,
232 // Consider this as part of a macro invocation if there was a
233 // leading identifier.
234 token::Not if self.in_macro => {
235 self.in_macro = false;
240 token::Eq | token::Lt | token::Le | token::EqEq | token::Ne | token::Ge | token::Gt |
241 token::AndAnd | token::OrOr | token::Not | token::BinOp(..) | token::RArrow |
242 token::BinOpEq(..) | token::FatArrow => Class::Op,
244 // Miscellaneous, no highlighting.
245 token::Dot | token::DotDot | token::DotDotDot | token::DotDotEq | token::Comma |
246 token::Semi | token::Colon | token::ModSep | token::LArrow | token::OpenDelim(_) |
247 token::CloseDelim(token::Brace) | token::CloseDelim(token::Paren) |
248 token::CloseDelim(token::NoDelim) => Class::None,
250 token::Question => Class::QuestionMark,
253 if self.lexer.peek().tok.is_ident() {
254 self.in_macro_nonterminal = true;
255 Class::MacroNonTerminal
261 // This might be the start of an attribute. We're going to want to
262 // continue highlighting it as an attribute until the ending ']' is
263 // seen, so skip out early. Down below we terminate the attribute
264 // span when we see the ']'.
266 // We can't be sure that our # begins an attribute (it could
267 // just be appearing in a macro) until we read either `#![` or
268 // `#[` from the input stream.
270 // We don't want to start highlighting as an attribute until
271 // we're confident there is going to be a ] coming up, as
272 // otherwise # tokens in macros highlight the rest of the input
275 // Case 1: #![inner_attribute]
276 if self.lexer.peek().tok == token::Not {
277 self.try_next_token()?; // NOTE: consumes `!` token!
278 if self.lexer.peek().tok == token::OpenDelim(token::Bracket) {
279 self.in_attribute = true;
280 out.enter_span(Class::Attribute)?;
282 out.string("#", Class::None)?;
283 out.string("!", Class::None)?;
287 // Case 2: #[outer_attribute]
288 if self.lexer.peek().tok == token::OpenDelim(token::Bracket) {
289 self.in_attribute = true;
290 out.enter_span(Class::Attribute)?;
292 out.string("#", Class::None)?;
295 token::CloseDelim(token::Bracket) => {
296 if self.in_attribute {
297 self.in_attribute = false;
298 out.string("]", Class::None)?;
306 token::Literal(lit, _suf) => {
309 token::Byte(..) | token::Char(..) |
310 token::ByteStr(..) | token::ByteStrRaw(..) |
311 token::Str_(..) | token::StrRaw(..) => Class::String,
314 token::Integer(..) | token::Float(..) => Class::Number,
318 // Keywords are also included in the identifier set.
319 token::Ident(ident, is_raw) => {
320 match &*ident.as_str() {
321 "ref" | "mut" if !is_raw => Class::RefKeyWord,
323 "self" | "Self" => Class::Self_,
324 "false" | "true" if !is_raw => Class::Bool,
326 "Option" | "Result" => Class::PreludeTy,
327 "Some" | "None" | "Ok" | "Err" => Class::PreludeVal,
329 "$crate" => Class::KeyWord,
330 _ if tas.tok.is_reserved_ident() => Class::KeyWord,
333 if self.in_macro_nonterminal {
334 self.in_macro_nonterminal = false;
335 Class::MacroNonTerminal
336 } else if self.lexer.peek().tok == token::Not {
337 self.in_macro = true;
346 token::Lifetime(..) => Class::Lifetime,
348 token::Eof | token::Interpolated(..) |
349 token::Tilde | token::At| token::SingleQuote => Class::None,
352 // Anything that didn't return above is the simple case where we the
353 // class just spans a single token, so we can use the `string` method.
354 out.string(Escape(&self.snip(tas.sp)), klass)
357 // Helper function to get a snippet from the source_map.
358 fn snip(&self, sp: Span) -> String {
359 self.source_map.span_to_snippet(sp).unwrap()
364 /// Returns the css class expected by rustdoc for each `Class`.
365 fn rustdoc_class(self) -> &'static str {
368 Class::Comment => "comment",
369 Class::DocComment => "doccomment",
370 Class::Attribute => "attribute",
371 Class::KeyWord => "kw",
372 Class::RefKeyWord => "kw-2",
373 Class::Self_ => "self",
375 Class::Macro => "macro",
376 Class::MacroNonTerminal => "macro-nonterminal",
377 Class::String => "string",
378 Class::Number => "number",
379 Class::Bool => "bool-val",
380 Class::Ident => "ident",
381 Class::Lifetime => "lifetime",
382 Class::PreludeTy => "prelude-ty",
383 Class::PreludeVal => "prelude-val",
384 Class::QuestionMark => "question-mark"
389 fn write_header(class: Option<&str>, out: &mut dyn Write) -> io::Result<()> {
390 write!(out, "<div class=\"example-wrap\"><pre class=\"rust {}\">\n", class.unwrap_or(""))
393 fn write_footer(out: &mut dyn Write) -> io::Result<()> {
394 write!(out, "</pre></div>\n")