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