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.
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.
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"]
17 #![feature(globs, struct_variant, managed_boxes, macro_rules, phase)]
19 extern crate collections;
23 #[phase(syntax, link)]
26 extern crate serialize;
29 extern crate testing = "test";
33 use std::io::{File, MemWriter};
35 use serialize::{json, Decodable, Encodable};
37 // reexported from `clean` so it can be easily updated with the mod itself
38 pub use clean::SCHEMA_VERSION;
61 type Pass = (&'static str, // name
62 fn(clean::Crate) -> plugins::PluginResult, // fn
63 &'static str); // description
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"),
76 static DEFAULT_PASSES: &'static [&'static str] = &[
83 local_data_key!(pub ctxtkey: @core::DocContext)
84 local_data_key!(pub analysiskey: core::CrateAnalysis)
86 type Output = (clean::Crate, Vec<plugins::PluginJson> );
89 std::os::set_exit_status(main_args(std::os::args().iter()
90 .map(|x| x.to_string())
95 pub fn opts() -> Vec<getopts::OptGroup> {
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",
102 optopt("w", "output-format", "the output type to write",
104 optopt("o", "output", "where to place the output", "PATH"),
105 optmulti("L", "library-path", "directory to add to crate search path",
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",
112 optmulti("", "plugins", "space separated list of plugins to also load",
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",
118 optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
120 optmulti("", "markdown-in-header",
121 "files to include inline in the <head> section of a rendered Markdown file",
123 optmulti("", "markdown-before-content",
124 "files to include inline between <body> and the content of a rendered \
127 optmulti("", "markdown-after-content",
128 "files to include inline between the content and </body> of a rendered \
134 pub fn usage(argv0: &str) {
136 getopts::usage(format!("{} [options] <input>", argv0).as_slice(),
140 pub fn main_args(args: &[String]) -> int {
141 let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
144 println!("{}", err.to_err_msg());
148 if matches.opt_present("h") || matches.opt_present("help") {
149 usage(args[0].as_slice());
151 } else if matches.opt_present("version") {
152 rustc::driver::version("rustdoc");
156 if matches.free.len() == 0 {
157 println!("expected an input file to act on");
159 } if matches.free.len() > 1 {
160 println!("only one input file may be specified");
163 let input = matches.free.get(0).as_slice();
165 let libs = matches.opt_strs("L").iter().map(|s| Path::new(s.as_slice())).collect();
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())
173 let should_test = matches.opt_present("test");
174 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
176 let output = matches.opt_str("o").map(|s| Path::new(s));
177 let cfgs = matches.opt_strs("cfg");
179 match (should_test, markdown_input) {
181 return markdown::test(input,
183 test_args.move_iter().collect())
186 return test::run(input,
188 .map(|x| x.to_string())
193 (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
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);
203 println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
204 for &name in DEFAULT_PASSES.iter() {
205 println!("{:>20s}", name);
210 let (krate, res) = match acquire_input(input, &matches) {
213 println!("input error: {}", s);
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"))) {
224 Err(e) => fail!("failed to generate documentation: {}", e),
228 match json_output(krate, res, output.unwrap_or(Path::new("doc.json"))) {
230 Err(e) => fail!("failed to write json: {}", e),
234 println!("unknown output format: {}", s);
238 let ended = time::precise_time_ns();
239 info!("Took {:.03f}s", (ended as f64 - started as f64) / 1e9f64);
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)),
253 if input.ends_with(".json") {
256 Ok(rust_input(input, matches))
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.
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")
272 .map(|x| x.to_string())
273 .collect::<Vec<_>>();
275 // First, parse the crate and extract all relevant information.
276 let libs: Vec<Path> = matches.opt_strs("L")
278 .map(|s| Path::new(s.as_slice()))
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() {
285 core::run_core(libs.move_iter().map(|x| x.clone()).collect(),
286 cfgs.move_iter().map(|x| x.to_string()).collect(),
288 }).map_err(|boxed_any|format!("{:?}", boxed_any)).unwrap();
289 info!("finished with rustc");
290 analysiskey.replace(Some(analysis));
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() {
296 for inner in nested.iter() {
299 if "no_default_passes" == x.as_slice() => {
300 default_passes = false;
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());
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());
321 for name in DEFAULT_PASSES.iter().rev() {
322 passes.unshift(name.to_string());
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, _, _)| {
335 Some(i) => PASSES[i].val1(),
337 error!("unknown pass {}, skipping", *pass);
341 pm.add_plugin(plugin);
343 info!("loading plugins...");
344 for pname in plugins.move_iter() {
345 pm.load_plugin(pname);
349 info!("Executing passes/plugins");
350 return pm.run_plugins(krate);
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)) {
359 return Err(format_strbuf!("couldn't open {}: {}", input, e))
362 match json::from_reader(&mut input) {
363 Err(s) => Err(s.to_str().to_string()),
364 Ok(json::Object(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 {}",
375 Some(..) => return Err("malformed json".to_string()),
376 None => return Err("expected a schema version".to_string()),
378 let krate = match obj.pop(&"crate".to_string()) {
380 let mut d = json::Decoder::new(json);
381 Decodable::decode(&mut d).unwrap()
383 None => return Err("malformed json".to_string()),
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))
391 Err("malformed json input: expected an object at the \
397 /// Outputs the crate/plugin json as a giant json blob at the specified
399 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
400 dst: Path) -> io::IoResult<()> {
402 // "schema": version,
403 // "crate": { parsed crate ... },
404 // "plugins": { output of plugins ... }
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()
413 Some((string, json)) => {
414 Some((string.to_string(), json))
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();
424 let mut encoder = json::Encoder::new(&mut w as &mut io::Writer);
425 krate.encode(&mut encoder).unwrap();
427 str::from_utf8(w.unwrap().as_slice()).unwrap().to_string()
429 let crate_json = match json::from_str(crate_json_str.as_slice()) {
431 Err(e) => fail!("Rust generated JSON is invalid: {:?}", e)
434 json.insert("crate".to_string(), crate_json);
435 json.insert("plugins".to_string(), json::Object(plugins_json));
437 let mut file = try!(File::create(&dst));
438 try!(json::Object(json).to_writer(&mut file));