]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/highlight.rs
auto merge of #15422 : steveklabnik/rust/guide_compound_data_types, 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>, 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,
32                                       src.to_string(),
33                                       "<stdin>".to_string());
34
35     let mut out = io::MemWriter::new();
36     doit(&sess,
37          lexer::StringReader::new(&sess.span_diagnostic, fm),
38          class,
39          id,
40          &mut out).unwrap();
41     str::from_utf8_lossy(out.unwrap().as_slice()).to_string()
42 }
43
44 /// Exhausts the `lexer` writing the output into `out`.
45 ///
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
50 /// source.
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;
55
56     try!(write!(out, "<pre "));
57     match id {
58         Some(id) => try!(write!(out, "id='{}' ", id)),
59         None => {}
60     }
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;
66     loop {
67         let next = lexer.next_token();
68         let test = if next.tok == t::EOF {lexer.pos} else {next.sp.lo};
69
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.
73         //
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.
77         if test > last {
78             let snip = sess.span_diagnostic.cm.span_to_snippet(Span {
79                 lo: last,
80                 hi: test,
81                 expn_info: None,
82             }).unwrap();
83             if snip.as_slice().contains("/") {
84                 try!(write!(out, "<span class='comment'>{}</span>",
85                               Escape(snip.as_slice())));
86             } else {
87                 try!(write!(out, "{}", Escape(snip.as_slice())));
88             }
89         }
90         last = next.sp.hi;
91         if next.tok == t::EOF { break }
92
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
97             // `@` are below).
98             t::BINOP(t::AND) if lexer.peek().sp.lo == next.sp.hi => "kw-2",
99             t::AT | t::TILDE => "kw-2",
100
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" }
104
105             // operators
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",
109
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 | t::QUESTION => "",
114             t::DOLLAR => {
115                 if t::is_ident(&lexer.peek().tok) {
116                     is_macro_nonterminal = true;
117                     "macro-nonterminal"
118                 } else {
119                     ""
120                 }
121             }
122
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 ']'.
127             t::POUND => {
128                 is_attribute = true;
129                 try!(write!(out, r"<span class='attribute'>#"));
130                 continue
131             }
132             t::RBRACKET => {
133                 if is_attribute {
134                     is_attribute = false;
135                     try!(write!(out, "]</span>"));
136                     continue
137                 } else {
138                     ""
139                 }
140             }
141
142             // text literals
143             t::LIT_BYTE(..) | t::LIT_BINARY(..) | t::LIT_BINARY_RAW(..) |
144                 t::LIT_CHAR(..) | t::LIT_STR(..) | t::LIT_STR_RAW(..) => "string",
145
146             // number literals
147             t::LIT_INT(..) | t::LIT_UINT(..) | t::LIT_INT_UNSUFFIXED(..) |
148                 t::LIT_FLOAT(..) | t::LIT_FLOAT_UNSUFFIXED(..) => "number",
149
150             // keywords are also included in the identifier set
151             t::IDENT(ident, _is_mod_sep) => {
152                 match t::get_ident(ident).get() {
153                     "ref" | "mut" => "kw-2",
154
155                     "self" => "self",
156                     "false" | "true" => "boolval",
157
158                     "Option" | "Result" => "prelude-ty",
159                     "Some" | "None" | "Ok" | "Err" => "prelude-val",
160
161                     _ if t::is_any_keyword(&next.tok) => "kw",
162                     _ => {
163                         if is_macro_nonterminal {
164                             is_macro_nonterminal = false;
165                             "macro-nonterminal"
166                         } else if lexer.peek().tok == t::NOT {
167                             is_macro = true;
168                             "macro"
169                         } else {
170                             "ident"
171                         }
172                     }
173                 }
174             }
175
176             t::LIFETIME(..) => "lifetime",
177             t::DOC_COMMENT(..) => "doccomment",
178             t::UNDERSCORE | t::EOF | t::INTERPOLATED(..) => "",
179         };
180
181         // as mentioned above, use the original source code instead of
182         // stringifying this token
183         let snip = sess.span_diagnostic.cm.span_to_snippet(next.sp).unwrap();
184         if klass == "" {
185             try!(write!(out, "{}", Escape(snip.as_slice())));
186         } else {
187             try!(write!(out, "<span class='{}'>{}</span>", klass,
188                           Escape(snip.as_slice())));
189         }
190     }
191
192     write!(out, "</pre>\n")
193 }