]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Merge remote-tracking branch 'origin/master' into 0.11.0-release
[rust.git] / src / librustdoc / lib.rs
1 // Copyright 2012-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 #![crate_id = "rustdoc#0.11.0"]
12 #![experimental]
13 #![desc = "rustdoc, the Rust documentation extractor"]
14 #![license = "MIT/ASL2"]
15 #![crate_type = "dylib"]
16 #![crate_type = "rlib"]
17
18 #![feature(globs, struct_variant, managed_boxes, macro_rules, phase)]
19
20 extern crate debug;
21 extern crate getopts;
22 extern crate libc;
23 extern crate rustc;
24 extern crate serialize;
25 extern crate syntax;
26 extern crate testing = "test";
27 extern crate time;
28 #[phase(plugin, link)] extern crate log;
29
30 use std::io;
31 use std::io::{File, MemWriter};
32 use std::str;
33 use std::gc::Gc;
34 use serialize::{json, Decodable, Encodable};
35 use externalfiles::ExternalHtml;
36
37 // reexported from `clean` so it can be easily updated with the mod itself
38 pub use clean::SCHEMA_VERSION;
39
40 pub mod clean;
41 pub mod core;
42 pub mod doctree;
43 #[macro_escape]
44 pub mod externalfiles;
45 pub mod fold;
46 pub mod html {
47     pub mod highlight;
48     pub mod escape;
49     pub mod item_type;
50     pub mod format;
51     pub mod layout;
52     pub mod markdown;
53     pub mod render;
54     pub mod toc;
55 }
56 pub mod markdown;
57 pub mod passes;
58 pub mod plugins;
59 pub mod visit_ast;
60 pub mod test;
61 mod flock;
62
63 type Pass = (&'static str,                                      // name
64              fn(clean::Crate) -> plugins::PluginResult,         // fn
65              &'static str);                                     // description
66
67 static PASSES: &'static [Pass] = &[
68     ("strip-hidden", passes::strip_hidden,
69      "strips all doc(hidden) items from the output"),
70     ("unindent-comments", passes::unindent_comments,
71      "removes excess indentation on comments in order for markdown to like it"),
72     ("collapse-docs", passes::collapse_docs,
73      "concatenates all document attributes into one document attribute"),
74     ("strip-private", passes::strip_private,
75      "strips all private items from a crate which cannot be seen externally"),
76 ];
77
78 static DEFAULT_PASSES: &'static [&'static str] = &[
79     "strip-hidden",
80     "strip-private",
81     "collapse-docs",
82     "unindent-comments",
83 ];
84
85 local_data_key!(pub ctxtkey: Gc<core::DocContext>)
86 local_data_key!(pub analysiskey: core::CrateAnalysis)
87
88 type Output = (clean::Crate, Vec<plugins::PluginJson> );
89
90 pub fn main() {
91     std::os::set_exit_status(main_args(std::os::args().as_slice()));
92 }
93
94 pub fn opts() -> Vec<getopts::OptGroup> {
95     use getopts::*;
96     vec!(
97         optflag("h", "help", "show this help message"),
98         optflagopt("", "version", "print rustdoc's version", "verbose"),
99         optopt("r", "input-format", "the input type of the specified file",
100                "[rust|json]"),
101         optopt("w", "output-format", "the output type to write",
102                "[html|json]"),
103         optopt("o", "output", "where to place the output", "PATH"),
104         optmulti("L", "library-path", "directory to add to crate search path",
105                  "DIR"),
106         optmulti("", "cfg", "pass a --cfg to rustc", ""),
107         optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
108         optmulti("", "passes", "space separated list of passes to also run, a \
109                                 value of `list` will print available passes",
110                  "PASSES"),
111         optmulti("", "plugins", "space separated list of plugins to also load",
112                  "PLUGINS"),
113         optflag("", "no-defaults", "don't run the default passes"),
114         optflag("", "test", "run code examples as tests"),
115         optmulti("", "test-args", "arguments to pass to the test runner",
116                  "ARGS"),
117         optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
118                  "FILES"),
119         optmulti("", "html-in-header",
120                  "files to include inline in the <head> section of a rendered Markdown file \
121                  or generated documentation",
122                  "FILES"),
123         optmulti("", "html-before-content",
124                  "files to include inline between <body> and the content of a rendered \
125                  Markdown file or generated documentation",
126                  "FILES"),
127         optmulti("", "html-after-content",
128                  "files to include inline between the content and </body> of a rendered \
129                  Markdown file or generated documentation",
130                  "FILES"),
131         optopt("", "markdown-playground-url",
132                "URL to send code snippets to", "URL")
133     )
134 }
135
136 pub fn usage(argv0: &str) {
137     println!("{}",
138              getopts::usage(format!("{} [options] <input>", argv0).as_slice(),
139                             opts().as_slice()));
140 }
141
142 pub fn main_args(args: &[String]) -> int {
143     let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
144         Ok(m) => m,
145         Err(err) => {
146             println!("{}", err);
147             return 1;
148         }
149     };
150     if matches.opt_present("h") || matches.opt_present("help") {
151         usage(args[0].as_slice());
152         return 0;
153     } else if matches.opt_present("version") {
154         match rustc::driver::version("rustdoc", &matches) {
155             Some(err) => {
156                 println!("{}", err);
157                 return 1
158             },
159             None => return 0
160         }
161     }
162
163     if matches.free.len() == 0 {
164         println!("expected an input file to act on");
165         return 1;
166     } if matches.free.len() > 1 {
167         println!("only one input file may be specified");
168         return 1;
169     }
170     let input = matches.free.get(0).as_slice();
171
172     let libs = matches.opt_strs("L").iter().map(|s| Path::new(s.as_slice())).collect();
173
174     let test_args = matches.opt_strs("test-args");
175     let test_args: Vec<String> = test_args.iter()
176                                           .flat_map(|s| s.as_slice().words())
177                                           .map(|s| s.to_string())
178                                           .collect();
179
180     let should_test = matches.opt_present("test");
181     let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
182
183     let output = matches.opt_str("o").map(|s| Path::new(s));
184     let cfgs = matches.opt_strs("cfg");
185
186     let external_html = match ExternalHtml::load(
187             matches.opt_strs("html-in-header").as_slice(),
188             matches.opt_strs("html-before-content").as_slice(),
189             matches.opt_strs("html-after-content").as_slice()) {
190         Some(eh) => eh,
191         None => return 3
192     };
193
194     match (should_test, markdown_input) {
195         (true, true) => {
196             return markdown::test(input, libs, test_args)
197         }
198         (true, false) => {
199             return test::run(input, cfgs, libs, test_args)
200         }
201         (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
202                                                  &matches, &external_html),
203         (false, false) => {}
204     }
205
206     if matches.opt_strs("passes").as_slice() == &["list".to_string()] {
207         println!("Available passes for running rustdoc:");
208         for &(name, _, description) in PASSES.iter() {
209             println!("{:>20s} - {}", name, description);
210         }
211         println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
212         for &name in DEFAULT_PASSES.iter() {
213             println!("{:>20s}", name);
214         }
215         return 0;
216     }
217
218     let (krate, res) = match acquire_input(input, &matches) {
219         Ok(pair) => pair,
220         Err(s) => {
221             println!("input error: {}", s);
222             return 1;
223         }
224     };
225
226     info!("going to format");
227     let started = time::precise_time_ns();
228     match matches.opt_str("w").as_ref().map(|s| s.as_slice()) {
229         Some("html") | None => {
230             match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc"))) {
231                 Ok(()) => {}
232                 Err(e) => fail!("failed to generate documentation: {}", e),
233             }
234         }
235         Some("json") => {
236             match json_output(krate, res, output.unwrap_or(Path::new("doc.json"))) {
237                 Ok(()) => {}
238                 Err(e) => fail!("failed to write json: {}", e),
239             }
240         }
241         Some(s) => {
242             println!("unknown output format: {}", s);
243             return 1;
244         }
245     }
246     let ended = time::precise_time_ns();
247     info!("Took {:.03f}s", (ended as f64 - started as f64) / 1e9f64);
248
249     return 0;
250 }
251
252 /// Looks inside the command line arguments to extract the relevant input format
253 /// and files and then generates the necessary rustdoc output for formatting.
254 fn acquire_input(input: &str,
255                  matches: &getopts::Matches) -> Result<Output, String> {
256     match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
257         Some("rust") => Ok(rust_input(input, matches)),
258         Some("json") => json_input(input),
259         Some(s) => Err(format!("unknown input format: {}", s)),
260         None => {
261             if input.ends_with(".json") {
262                 json_input(input)
263             } else {
264                 Ok(rust_input(input, matches))
265             }
266         }
267     }
268 }
269
270 /// Interprets the input file as a rust source file, passing it through the
271 /// compiler all the way through the analysis passes. The rustdoc output is then
272 /// generated from the cleaned AST of the crate.
273 ///
274 /// This form of input will run all of the plug/cleaning passes
275 fn rust_input(cratefile: &str, matches: &getopts::Matches) -> Output {
276     let mut default_passes = !matches.opt_present("no-defaults");
277     let mut passes = matches.opt_strs("passes");
278     let mut plugins = matches.opt_strs("plugins");
279
280     // First, parse the crate and extract all relevant information.
281     let libs: Vec<Path> = matches.opt_strs("L")
282                                  .iter()
283                                  .map(|s| Path::new(s.as_slice()))
284                                  .collect();
285     let cfgs = matches.opt_strs("cfg");
286     let cr = Path::new(cratefile);
287     info!("starting to run rustc");
288     let (krate, analysis) = std::task::try(proc() {
289         let cr = cr;
290         core::run_core(libs.move_iter().map(|x| x.clone()).collect(),
291                        cfgs,
292                        &cr)
293     }).map_err(|boxed_any|format!("{:?}", boxed_any)).unwrap();
294     info!("finished with rustc");
295     analysiskey.replace(Some(analysis));
296
297     // Process all of the crate attributes, extracting plugin metadata along
298     // with the passes which we are supposed to run.
299     match krate.module.get_ref().doc_list() {
300         Some(nested) => {
301             for inner in nested.iter() {
302                 match *inner {
303                     clean::Word(ref x)
304                             if "no_default_passes" == x.as_slice() => {
305                         default_passes = false;
306                     }
307                     clean::NameValue(ref x, ref value)
308                             if "passes" == x.as_slice() => {
309                         for pass in value.as_slice().words() {
310                             passes.push(pass.to_string());
311                         }
312                     }
313                     clean::NameValue(ref x, ref value)
314                             if "plugins" == x.as_slice() => {
315                         for p in value.as_slice().words() {
316                             plugins.push(p.to_string());
317                         }
318                     }
319                     _ => {}
320                 }
321             }
322         }
323         None => {}
324     }
325     if default_passes {
326         for name in DEFAULT_PASSES.iter().rev() {
327             passes.unshift(name.to_string());
328         }
329     }
330
331     // Load all plugins/passes into a PluginManager
332     let path = matches.opt_str("plugin-path")
333                       .unwrap_or("/tmp/rustdoc/plugins".to_string());
334     let mut pm = plugins::PluginManager::new(Path::new(path));
335     for pass in passes.iter() {
336         let plugin = match PASSES.iter()
337                                  .position(|&(p, _, _)| {
338                                      p == pass.as_slice()
339                                  }) {
340             Some(i) => PASSES[i].val1(),
341             None => {
342                 error!("unknown pass {}, skipping", *pass);
343                 continue
344             },
345         };
346         pm.add_plugin(plugin);
347     }
348     info!("loading plugins...");
349     for pname in plugins.move_iter() {
350         pm.load_plugin(pname);
351     }
352
353     // Run everything!
354     info!("Executing passes/plugins");
355     return pm.run_plugins(krate);
356 }
357
358 /// This input format purely deserializes the json output file. No passes are
359 /// run over the deserialized output.
360 fn json_input(input: &str) -> Result<Output, String> {
361     let mut input = match File::open(&Path::new(input)) {
362         Ok(f) => f,
363         Err(e) => {
364             return Err(format!("couldn't open {}: {}", input, e))
365         }
366     };
367     match json::from_reader(&mut input) {
368         Err(s) => Err(s.to_str()),
369         Ok(json::Object(obj)) => {
370             let mut obj = obj;
371             // Make sure the schema is what we expect
372             match obj.pop(&"schema".to_string()) {
373                 Some(json::String(version)) => {
374                     if version.as_slice() != SCHEMA_VERSION {
375                         return Err(format!(
376                                 "sorry, but I only understand version {}",
377                                 SCHEMA_VERSION))
378                     }
379                 }
380                 Some(..) => return Err("malformed json".to_string()),
381                 None => return Err("expected a schema version".to_string()),
382             }
383             let krate = match obj.pop(&"crate".to_string()) {
384                 Some(json) => {
385                     let mut d = json::Decoder::new(json);
386                     Decodable::decode(&mut d).unwrap()
387                 }
388                 None => return Err("malformed json".to_string()),
389             };
390             // FIXME: this should read from the "plugins" field, but currently
391             //      Json doesn't implement decodable...
392             let plugin_output = Vec::new();
393             Ok((krate, plugin_output))
394         }
395         Ok(..) => {
396             Err("malformed json input: expected an object at the \
397                  top".to_string())
398         }
399     }
400 }
401
402 /// Outputs the crate/plugin json as a giant json blob at the specified
403 /// destination.
404 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
405                dst: Path) -> io::IoResult<()> {
406     // {
407     //   "schema": version,
408     //   "crate": { parsed crate ... },
409     //   "plugins": { output of plugins ... }
410     // }
411     let mut json = std::collections::TreeMap::new();
412     json.insert("schema".to_string(), json::String(SCHEMA_VERSION.to_string()));
413     let plugins_json = res.move_iter()
414                           .filter_map(|opt| {
415                               match opt {
416                                   None => None,
417                                   Some((string, json)) => {
418                                       Some((string.to_string(), json))
419                                   }
420                               }
421                           }).collect();
422
423     // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
424     // straight to the Rust JSON representation.
425     let crate_json_str = {
426         let mut w = MemWriter::new();
427         {
428             let mut encoder = json::Encoder::new(&mut w as &mut io::Writer);
429             krate.encode(&mut encoder).unwrap();
430         }
431         str::from_utf8_owned(w.unwrap()).unwrap()
432     };
433     let crate_json = match json::from_str(crate_json_str.as_slice()) {
434         Ok(j) => j,
435         Err(e) => fail!("Rust generated JSON is invalid: {:?}", e)
436     };
437
438     json.insert("crate".to_string(), crate_json);
439     json.insert("plugins".to_string(), json::Object(plugins_json));
440
441     let mut file = try!(File::create(&dst));
442     json::Object(json).to_writer(&mut file)
443 }