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