]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/highlight.rs
auto merge of #13600 : brandonw/rust/master, r=brson
[rust.git] / src / librustdoc / html / highlight.rs
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.
4 //
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.
10
11 //! Basic html highlighting functionality
12 //!
13 //! This module uses libsyntax's lexer to provide token-based highlighting for
14 //! the HTML documentation generated by rustdoc.
15
16 use std::str;
17 use std::io;
18
19 use syntax::parse;
20 use syntax::parse::lexer;
21 use syntax::codemap::{BytePos, Span};
22
23 use html::escape::Escape;
24
25 use t = syntax::parse::token;
26
27 /// Highlights some source code, returning the HTML output.
28 pub fn highlight(src: &str, class: Option<&str>) -> ~str {
29     let sess = parse::new_parse_sess();
30     let fm = parse::string_to_filemap(&sess, src.to_owned(), ~"<stdin>");
31
32     let mut out = io::MemWriter::new();
33     doit(&sess,
34          lexer::new_string_reader(&sess.span_diagnostic, fm),
35          class,
36          &mut out).unwrap();
37     str::from_utf8_lossy(out.unwrap().as_slice()).into_owned()
38 }
39
40 /// Exhausts the `lexer` writing the output into `out`.
41 ///
42 /// The general structure for this method is to iterate over each token,
43 /// possibly giving it an HTML span with a class specifying what flavor of token
44 /// it's used. All source code emission is done as slices from the source map,
45 /// not from the tokens themselves, in order to stay true to the original
46 /// source.
47 fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader, class: Option<&str>,
48         out: &mut Writer) -> io::IoResult<()> {
49     use syntax::parse::lexer::Reader;
50
51     try!(write!(out, "<pre class='rust {}'>\n", class.unwrap_or("")));
52     let mut last = BytePos(0);
53     let mut is_attribute = false;
54     let mut is_macro = false;
55     let mut is_macro_nonterminal = false;
56     loop {
57         let next = lexer.next_token();
58         let test = if next.tok == t::EOF {lexer.pos} else {next.sp.lo};
59
60         // The lexer consumes all whitespace and non-doc-comments when iterating
61         // between tokens. If this token isn't directly adjacent to our last
62         // token, then we need to emit the whitespace/comment.
63         //
64         // If the gap has any '/' characters then we consider the whole thing a
65         // comment. This will classify some whitespace as a comment, but that
66         // doesn't matter too much for syntax highlighting purposes.
67         if test > last {
68             let snip = sess.span_diagnostic.cm.span_to_snippet(Span {
69                 lo: last,
70                 hi: test,
71                 expn_info: None,
72             }).unwrap();
73             if snip.contains("/") {
74                 try!(write!(out, "<span class='comment'>{}</span>",
75                               Escape(snip)));
76             } else {
77                 try!(write!(out, "{}", Escape(snip)));
78             }
79         }
80         last = next.sp.hi;
81         if next.tok == t::EOF { break }
82
83         let klass = match next.tok {
84             // If this '&' token is directly adjacent to another token, assume
85             // that it's the address-of operator instead of the and-operator.
86             // This allows us to give all pointers their own class (~ and @ are
87             // below).
88             t::BINOP(t::AND) if lexer.peek().sp.lo == next.sp.hi => "kw-2",
89             t::AT | t::TILDE => "kw-2",
90
91             // consider this as part of a macro invocation if there was a
92             // leading identifier
93             t::NOT if is_macro => { is_macro = false; "macro" }
94
95             // operators
96             t::EQ | t::LT | t::LE | t::EQEQ | t::NE | t::GE | t::GT |
97                 t::ANDAND | t::OROR | t::NOT | t::BINOP(..) | t::RARROW |
98                 t::BINOPEQ(..) | t::FAT_ARROW => "op",
99
100             // miscellaneous, no highlighting
101             t::DOT | t::DOTDOT | t::DOTDOTDOT | t::COMMA | t::SEMI |
102                 t::COLON | t::MOD_SEP | t::LARROW | t::DARROW | t::LPAREN |
103                 t::RPAREN | t::LBRACKET | t::LBRACE | t::RBRACE => "",
104             t::DOLLAR => {
105                 if t::is_ident(&lexer.peek().tok) {
106                     is_macro_nonterminal = true;
107                     "macro-nonterminal"
108                 } else {
109                     ""
110                 }
111             }
112
113             // This is the start of an attribute. We're going to want to
114             // continue highlighting it as an attribute until the ending ']' is
115             // seen, so skip out early. Down below we terminate the attribute
116             // span when we see the ']'.
117             t::POUND => {
118                 is_attribute = true;
119                 try!(write!(out, r"<span class='attribute'>\#"));
120                 continue
121             }
122             t::RBRACKET => {
123                 if is_attribute {
124                     is_attribute = false;
125                     try!(write!(out, "]</span>"));
126                     continue
127                 } else {
128                     ""
129                 }
130             }
131
132             // text literals
133             t::LIT_CHAR(..) | t::LIT_STR(..) | t::LIT_STR_RAW(..) => "string",
134
135             // number literals
136             t::LIT_INT(..) | t::LIT_UINT(..) | t::LIT_INT_UNSUFFIXED(..) |
137                 t::LIT_FLOAT(..) | t::LIT_FLOAT_UNSUFFIXED(..) => "number",
138
139             // keywords are also included in the identifier set
140             t::IDENT(ident, _is_mod_sep) => {
141                 match t::get_ident(ident).get() {
142                     "ref" | "mut" => "kw-2",
143
144                     "self" => "self",
145                     "false" | "true" => "boolval",
146
147                     "Option" | "Result" => "prelude-ty",
148                     "Some" | "None" | "Ok" | "Err" => "prelude-val",
149
150                     _ if t::is_any_keyword(&next.tok) => "kw",
151                     _ => {
152                         if is_macro_nonterminal {
153                             is_macro_nonterminal = false;
154                             "macro-nonterminal"
155                         } else if lexer.peek().tok == t::NOT {
156                             is_macro = true;
157                             "macro"
158                         } else {
159                             "ident"
160                         }
161                     }
162                 }
163             }
164
165             t::LIFETIME(..) => "lifetime",
166             t::DOC_COMMENT(..) => "doccomment",
167             t::UNDERSCORE | t::EOF | t::INTERPOLATED(..) => "",
168         };
169
170         // as mentioned above, use the original source code instead of
171         // stringifying this token
172         let snip = sess.span_diagnostic.cm.span_to_snippet(next.sp).unwrap();
173         if klass == "" {
174             try!(write!(out, "{}", Escape(snip)));
175         } else {
176             try!(write!(out, "<span class='{}'>{}</span>", klass,
177                           Escape(snip)));
178         }
179     }
180
181     write!(out, "</pre>\n")
182 }