1 //! Basic syntax highlighting functionality.
3 //! This module uses libsyntax's lexer to provide token-based highlighting for
4 //! the HTML documentation generated by rustdoc.
6 //! Use the `render_with_highlighting` to highlight some rust code.
8 use crate::html::escape::Escape;
10 use std::fmt::Display;
12 use std::io::prelude::*;
14 use rustc_parse::lexer;
15 use rustc_span::source_map::SourceMap;
16 use rustc_span::symbol::{kw, sym};
17 use rustc_span::{FileName, Span};
18 use syntax::sess::ParseSess;
19 use syntax::token::{self, Token};
21 /// Highlights `src`, returning the HTML output.
22 pub fn render_with_highlighting(
25 extension: Option<&str>,
26 tooltip: Option<(&str, &str)>,
28 debug!("highlighting: ================\n{}\n==============", src);
29 let mut out = Vec::new();
30 if let Some((tooltip, class)) = tooltip {
33 "<div class='information'><div class='tooltip {}'>ⓘ<span \
34 class='tooltiptext'>{}</span></div></div>",
40 let sess = ParseSess::with_silent_emitter();
43 .new_source_file(FileName::Custom(String::from("rustdoc-highlighting")), src.to_owned());
44 let highlight_result = rustc_driver::catch_fatal_errors(|| {
45 let lexer = lexer::StringReader::new(&sess, fm, None);
46 let mut classifier = Classifier::new(lexer, sess.source_map());
48 let mut highlighted_source = vec![];
49 if classifier.write_source(&mut highlighted_source).is_err() {
52 Ok(String::from_utf8_lossy(&highlighted_source).into_owned())
57 match highlight_result {
58 Ok(highlighted_source) => {
59 write_header(class, &mut out).unwrap();
60 write!(out, "{}", highlighted_source).unwrap();
61 if let Some(extension) = extension {
62 write!(out, "{}", extension).unwrap();
64 write_footer(&mut out).unwrap();
67 // If errors are encountered while trying to highlight, just emit
68 // the unhighlighted source.
69 write!(out, "<pre><code>{}</code></pre>", Escape(src)).unwrap();
73 String::from_utf8_lossy(&out[..]).into_owned()
76 /// Processes a program (nested in the internal `lexer`), classifying strings of
77 /// text by highlighting category (`Class`). Calls out to a `Writer` to write
78 /// each span of text in sequence.
79 struct Classifier<'a> {
80 lexer: lexer::StringReader<'a>,
81 peek_token: Option<Token>,
82 source_map: &'a SourceMap,
84 // State of the classifier.
87 in_macro_nonterminal: bool,
90 /// How a span of text is classified. Mostly corresponds to token kinds.
91 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
98 // Keywords that do pointer/reference stuff.
114 /// Trait that controls writing the output of syntax highlighting. Users should
115 /// implement this trait to customize writing output.
117 /// The classifier will call into the `Writer` implementation as it finds spans
118 /// of text to highlight. Exactly how that text should be highlighted is up to
119 /// the implementation.
121 /// Called when we start processing a span of text that should be highlighted.
122 /// The `Class` argument specifies how it should be highlighted.
123 fn enter_span(&mut self, _: Class) -> io::Result<()>;
125 /// Called at the end of a span of highlighted text.
126 fn exit_span(&mut self) -> io::Result<()>;
128 /// Called for a span of text. If the text should be highlighted differently from the
129 /// surrounding text, then the `Class` argument will be a value other than `None`.
131 /// The following sequences of callbacks are equivalent:
133 /// enter_span(Foo), string("text", None), exit_span()
134 /// string("text", Foo)
136 /// The latter can be thought of as a shorthand for the former, which is
138 fn string<T: Display>(&mut self, text: T, klass: Class) -> io::Result<()>;
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, text: T, klass: Class) -> io::Result<()> {
146 Class::None => write!(self, "{}", text),
147 klass => write!(self, "<span class=\"{}\">{}</span>", klass.rustdoc_class(), text),
151 fn enter_span(&mut self, klass: Class) -> io::Result<()> {
152 write!(self, "<span class=\"{}\">", klass.rustdoc_class())
155 fn exit_span(&mut self) -> io::Result<()> {
156 write!(self, "</span>")
160 enum HighlightError {
165 impl From<io::Error> for HighlightError {
166 fn from(err: io::Error) -> Self {
167 HighlightError::IoError(err)
171 impl<'a> Classifier<'a> {
172 fn new(lexer: lexer::StringReader<'a>, source_map: &'a SourceMap) -> Classifier<'a> {
179 in_macro_nonterminal: false,
183 /// Gets the next token out of the lexer.
184 fn try_next_token(&mut self) -> Result<Token, HighlightError> {
185 if let Some(token) = self.peek_token.take() {
188 let token = self.lexer.next_token();
189 if let token::Unknown(..) = &token.kind {
190 return Err(HighlightError::LexError);
195 fn peek(&mut self) -> Result<&Token, HighlightError> {
196 if self.peek_token.is_none() {
197 let token = self.lexer.next_token();
198 if let token::Unknown(..) = &token.kind {
199 return Err(HighlightError::LexError);
201 self.peek_token = Some(token);
203 Ok(self.peek_token.as_ref().unwrap())
206 /// Exhausts the `lexer` writing the output into `out`.
208 /// The general structure for this method is to iterate over each token,
209 /// possibly giving it an HTML span with a class specifying what flavor of token
210 /// is used. All source code emission is done as slices from the source map,
211 /// not from the tokens themselves, in order to stay true to the original
213 fn write_source<W: Writer>(&mut self, out: &mut W) -> Result<(), HighlightError> {
215 let next = self.try_next_token()?;
216 if next == token::Eof {
220 self.write_token(out, next)?;
226 // Handles an individual token from the lexer.
227 fn write_token<W: Writer>(&mut self, out: &mut W, token: Token) -> Result<(), HighlightError> {
228 let klass = match token.kind {
229 token::Shebang(s) => {
230 out.string(Escape(&s.as_str()), Class::None)?;
234 token::Whitespace | token::Unknown(..) => Class::None,
235 token::Comment => Class::Comment,
236 token::DocComment(..) => Class::DocComment,
238 // If this '&' or '*' token is followed by a non-whitespace token, assume that it's the
239 // reference or dereference operator or a reference or pointer type, instead of the
240 // bit-and or multiplication operator.
241 token::BinOp(token::And) | token::BinOp(token::Star)
242 if self.peek()? != &token::Whitespace =>
247 // Consider this as part of a macro invocation if there was a
248 // leading identifier.
249 token::Not if self.in_macro => {
250 self.in_macro = false;
268 | token::FatArrow => Class::Op,
270 // Miscellaneous, no highlighting.
280 | token::OpenDelim(_)
281 | token::CloseDelim(token::Brace)
282 | token::CloseDelim(token::Paren)
283 | token::CloseDelim(token::NoDelim) => Class::None,
285 token::Question => Class::QuestionMark,
288 if self.peek()?.is_ident() {
289 self.in_macro_nonterminal = true;
290 Class::MacroNonTerminal
296 // This might be the start of an attribute. We're going to want to
297 // continue highlighting it as an attribute until the ending ']' is
298 // seen, so skip out early. Down below we terminate the attribute
299 // span when we see the ']'.
301 // We can't be sure that our # begins an attribute (it could
302 // just be appearing in a macro) until we read either `#![` or
303 // `#[` from the input stream.
305 // We don't want to start highlighting as an attribute until
306 // we're confident there is going to be a ] coming up, as
307 // otherwise # tokens in macros highlight the rest of the input
310 // Case 1: #![inner_attribute]
311 if self.peek()? == &token::Not {
312 self.try_next_token()?; // NOTE: consumes `!` token!
313 if self.peek()? == &token::OpenDelim(token::Bracket) {
314 self.in_attribute = true;
315 out.enter_span(Class::Attribute)?;
317 out.string("#", Class::None)?;
318 out.string("!", Class::None)?;
322 // Case 2: #[outer_attribute]
323 if self.peek()? == &token::OpenDelim(token::Bracket) {
324 self.in_attribute = true;
325 out.enter_span(Class::Attribute)?;
327 out.string("#", Class::None)?;
330 token::CloseDelim(token::Bracket) => {
331 if self.in_attribute {
332 self.in_attribute = false;
333 out.string("]", Class::None)?;
341 token::Literal(lit) => {
348 | token::ByteStrRaw(..)
350 | token::StrRaw(..) => Class::String,
353 token::Integer | token::Float => Class::Number,
355 token::Bool => panic!("literal token contains `Lit::Bool`"),
359 // Keywords are also included in the identifier set.
360 token::Ident(name, is_raw) => match name {
361 kw::Ref | kw::Mut if !is_raw => Class::RefKeyWord,
363 kw::SelfLower | kw::SelfUpper => Class::Self_,
364 kw::False | kw::True if !is_raw => Class::Bool,
366 sym::Option | sym::Result => Class::PreludeTy,
367 sym::Some | sym::None | sym::Ok | sym::Err => Class::PreludeVal,
369 _ if token.is_reserved_ident() => Class::KeyWord,
372 if self.in_macro_nonterminal {
373 self.in_macro_nonterminal = false;
374 Class::MacroNonTerminal
375 } else if self.peek()? == &token::Not {
376 self.in_macro = true;
384 token::Lifetime(..) => Class::Lifetime,
387 | token::Interpolated(..)
390 | token::SingleQuote => Class::None,
393 // Anything that didn't return above is the simple case where we the
394 // class just spans a single token, so we can use the `string` method.
395 out.string(Escape(&self.snip(token.span)), klass)?;
400 // Helper function to get a snippet from the source_map.
401 fn snip(&self, sp: Span) -> String {
402 self.source_map.span_to_snippet(sp).unwrap()
407 /// Returns the css class expected by rustdoc for each `Class`.
408 fn rustdoc_class(self) -> &'static str {
411 Class::Comment => "comment",
412 Class::DocComment => "doccomment",
413 Class::Attribute => "attribute",
414 Class::KeyWord => "kw",
415 Class::RefKeyWord => "kw-2",
416 Class::Self_ => "self",
418 Class::Macro => "macro",
419 Class::MacroNonTerminal => "macro-nonterminal",
420 Class::String => "string",
421 Class::Number => "number",
422 Class::Bool => "bool-val",
423 Class::Ident => "ident",
424 Class::Lifetime => "lifetime",
425 Class::PreludeTy => "prelude-ty",
426 Class::PreludeVal => "prelude-val",
427 Class::QuestionMark => "question-mark",
432 fn write_header(class: Option<&str>, out: &mut dyn Write) -> io::Result<()> {
433 write!(out, "<div class=\"example-wrap\"><pre class=\"rust {}\">\n", class.unwrap_or(""))
436 fn write_footer(out: &mut dyn Write) -> io::Result<()> {
437 write!(out, "</pre></div>\n")