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