1 // Copyright 2014 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 html highlighting functionality
13 //! This module uses libsyntax's lexer to provide token-based highlighting for
14 //! the HTML documentation generated by rustdoc.
20 use syntax::parse::lexer;
21 use syntax::codemap::{BytePos, Span};
23 use html::escape::Escape;
25 use t = syntax::parse::token;
27 /// Highlights some source code, returning the HTML output.
28 pub fn highlight(src: &str, class: Option<&str>, id: Option<&str>) -> String {
29 debug!("highlighting: ================\n{}\n==============", src);
30 let sess = parse::new_parse_sess();
31 let fm = parse::string_to_filemap(&sess,
33 "<stdin>".to_string());
35 let mut out = io::MemWriter::new();
37 lexer::StringReader::new(&sess.span_diagnostic, fm),
41 str::from_utf8_lossy(out.unwrap().as_slice()).to_string()
44 /// Exhausts the `lexer` writing the output into `out`.
46 /// The general structure for this method is to iterate over each token,
47 /// possibly giving it an HTML span with a class specifying what flavor of token
48 /// it's used. All source code emission is done as slices from the source map,
49 /// not from the tokens themselves, in order to stay true to the original
51 fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader,
52 class: Option<&str>, id: Option<&str>,
53 out: &mut Writer) -> io::IoResult<()> {
54 use syntax::parse::lexer::Reader;
56 try!(write!(out, "<pre "));
58 Some(id) => try!(write!(out, "id='{}' ", id)),
61 try!(write!(out, "class='rust {}'>\n", class.unwrap_or("")));
62 let mut last = BytePos(0);
63 let mut is_attribute = false;
64 let mut is_macro = false;
65 let mut is_macro_nonterminal = false;
67 let next = lexer.next_token();
68 let test = if next.tok == t::EOF {lexer.pos} else {next.sp.lo};
70 // The lexer consumes all whitespace and non-doc-comments when iterating
71 // between tokens. If this token isn't directly adjacent to our last
72 // token, then we need to emit the whitespace/comment.
74 // If the gap has any '/' characters then we consider the whole thing a
75 // comment. This will classify some whitespace as a comment, but that
76 // doesn't matter too much for syntax highlighting purposes.
78 let snip = sess.span_diagnostic.cm.span_to_snippet(Span {
83 if snip.as_slice().contains("/") {
84 try!(write!(out, "<span class='comment'>{}</span>",
85 Escape(snip.as_slice())));
87 try!(write!(out, "{}", Escape(snip.as_slice())));
91 if next.tok == t::EOF { break }
93 let klass = match next.tok {
94 // If this '&' token is directly adjacent to another token, assume
95 // that it's the address-of operator instead of the and-operator.
96 // This allows us to give all pointers their own class (`Box` and
98 t::BINOP(t::AND) if lexer.peek().sp.lo == next.sp.hi => "kw-2",
99 t::AT | t::TILDE => "kw-2",
101 // consider this as part of a macro invocation if there was a
102 // leading identifier
103 t::NOT if is_macro => { is_macro = false; "macro" }
106 t::EQ | t::LT | t::LE | t::EQEQ | t::NE | t::GE | t::GT |
107 t::ANDAND | t::OROR | t::NOT | t::BINOP(..) | t::RARROW |
108 t::BINOPEQ(..) | t::FAT_ARROW => "op",
110 // miscellaneous, no highlighting
111 t::DOT | t::DOTDOT | t::DOTDOTDOT | t::COMMA | t::SEMI |
112 t::COLON | t::MOD_SEP | t::LARROW | t::LPAREN |
113 t::RPAREN | t::LBRACKET | t::LBRACE | t::RBRACE => "",
115 if t::is_ident(&lexer.peek().tok) {
116 is_macro_nonterminal = true;
123 // This is the start of an attribute. We're going to want to
124 // continue highlighting it as an attribute until the ending ']' is
125 // seen, so skip out early. Down below we terminate the attribute
126 // span when we see the ']'.
129 try!(write!(out, r"<span class='attribute'>#"));
134 is_attribute = false;
135 try!(write!(out, "]</span>"));
143 t::LIT_CHAR(..) | t::LIT_STR(..) | t::LIT_STR_RAW(..) => "string",
146 t::LIT_INT(..) | t::LIT_UINT(..) | t::LIT_INT_UNSUFFIXED(..) |
147 t::LIT_FLOAT(..) | t::LIT_FLOAT_UNSUFFIXED(..) => "number",
149 // keywords are also included in the identifier set
150 t::IDENT(ident, _is_mod_sep) => {
151 match t::get_ident(ident).get() {
152 "ref" | "mut" => "kw-2",
155 "false" | "true" => "boolval",
157 "Option" | "Result" => "prelude-ty",
158 "Some" | "None" | "Ok" | "Err" => "prelude-val",
160 _ if t::is_any_keyword(&next.tok) => "kw",
162 if is_macro_nonterminal {
163 is_macro_nonterminal = false;
165 } else if lexer.peek().tok == t::NOT {
175 t::LIFETIME(..) => "lifetime",
176 t::DOC_COMMENT(..) => "doccomment",
177 t::UNDERSCORE | t::EOF | t::INTERPOLATED(..) => "",
180 // as mentioned above, use the original source code instead of
181 // stringifying this token
182 let snip = sess.span_diagnostic.cm.span_to_snippet(next.sp).unwrap();
184 try!(write!(out, "{}", Escape(snip.as_slice())));
186 try!(write!(out, "<span class='{}'>{}</span>", klass,
187 Escape(snip.as_slice())));
191 write!(out, "</pre>\n")