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_name = "rustdoc"]
13 #![desc = "rustdoc, the Rust documentation extractor"]
14 #![license = "MIT/ASL2"]
15 #![crate_type = "dylib"]
16 #![crate_type = "rlib"]
18 #![feature(globs, struct_variant, managed_boxes, macro_rules, phase)]
24 extern crate serialize;
26 extern crate testing = "test";
28 #[phase(plugin, link)] extern crate log;
31 use std::io::{File, MemWriter};
33 use std::collections::HashMap;
34 use serialize::{json, Decodable, Encodable};
35 use externalfiles::ExternalHtml;
37 // reexported from `clean` so it can be easily updated with the mod itself
38 pub use clean::SCHEMA_VERSION;
44 pub mod externalfiles;
59 pub mod stability_summary;
64 type Pass = (&'static str, // name
65 fn(clean::Crate) -> plugins::PluginResult, // fn
66 &'static str); // description
68 static PASSES: &'static [Pass] = &[
69 ("strip-hidden", passes::strip_hidden,
70 "strips all doc(hidden) items from the output"),
71 ("unindent-comments", passes::unindent_comments,
72 "removes excess indentation on comments in order for markdown to like it"),
73 ("collapse-docs", passes::collapse_docs,
74 "concatenates all document attributes into one document attribute"),
75 ("strip-private", passes::strip_private,
76 "strips all private items from a crate which cannot be seen externally"),
79 static DEFAULT_PASSES: &'static [&'static str] = &[
86 local_data_key!(pub ctxtkey: Gc<core::DocContext>)
87 local_data_key!(pub analysiskey: core::CrateAnalysis)
89 type Output = (clean::Crate, Vec<plugins::PluginJson> );
92 // Why run rustdoc in a separate task? That's a good question!
94 // We first begin our adventure at the ancient commit of e7c4fb69. In this
95 // commit it was discovered that the stack limit frobbing on windows ended
96 // up causing some syscalls to fail. This was worked around manually in the
99 // Our journey now continues with #13259 where it was discovered that this
100 // stack limit frobbing has the ability to affect nearly any syscall. Note
101 // that the key idea here is that there is currently no knowledge as to why
102 // this is happening or how to preserve it, fun times!
104 // Now we continue along to #16275 where it was discovered that --test on
105 // windows didn't work at all! Yet curiously rustdoc worked without --test.
106 // The exact reason that #16275 cropped up is that during the expansion
107 // phase the compiler attempted to open libstd to read out its macros. This
108 // invoked the LLVMRustOpenArchive shim which in turned went to LLVM to go
109 // open a file and read it. Lo and behold this function returned an error!
110 // It was then discovered that when the same fix mentioned in #13259 was
111 // applied, the error went away. The plot thickens!
113 // Remember that rustdoc works without --test, which raises the question of
114 // how because the --test and non --test paths are almost identical. The
115 // first thing both paths do is parse and expand a crate! It turns out that
116 // the difference is that --test runs on the *main task* while the normal
117 // path runs in subtask. It turns out that running --test in a sub task also
118 // fixes the problem!
120 // So, in summary, it is unknown why this is necessary, what it is
121 // preventing, or what the actual bug is. In the meantime, this allows
122 // --test to work on windows, which seems good, right? Fun times.
123 let (tx, rx) = channel();
125 std::os::set_exit_status(main_args(std::os::args().as_slice()));
129 // If the task failed, set an error'd exit status
130 if rx.recv_opt().is_err() {
131 std::os::set_exit_status(std::rt::DEFAULT_ERROR_CODE);
135 pub fn opts() -> Vec<getopts::OptGroup> {
138 optflag("h", "help", "show this help message"),
139 optflagopt("", "version", "print rustdoc's version", "verbose"),
140 optopt("r", "input-format", "the input type of the specified file",
142 optopt("w", "output-format", "the output type to write",
144 optopt("o", "output", "where to place the output", "PATH"),
145 optopt("", "crate-name", "specify the name of this crate", "NAME"),
146 optmulti("L", "library-path", "directory to add to crate search path",
148 optmulti("", "cfg", "pass a --cfg to rustc", ""),
149 optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH"),
150 optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
151 optmulti("", "passes", "space separated list of passes to also run, a \
152 value of `list` will print available passes",
154 optmulti("", "plugins", "space separated list of plugins to also load",
156 optflag("", "no-defaults", "don't run the default passes"),
157 optflag("", "test", "run code examples as tests"),
158 optmulti("", "test-args", "arguments to pass to the test runner",
160 optopt("", "target", "target triple to document", "TRIPLE"),
161 optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
163 optmulti("", "html-in-header",
164 "files to include inline in the <head> section of a rendered Markdown file \
165 or generated documentation",
167 optmulti("", "html-before-content",
168 "files to include inline between <body> and the content of a rendered \
169 Markdown file or generated documentation",
171 optmulti("", "html-after-content",
172 "files to include inline between the content and </body> of a rendered \
173 Markdown file or generated documentation",
175 optopt("", "markdown-playground-url",
176 "URL to send code snippets to", "URL"),
177 optflag("", "markdown-no-toc", "don't include table of contents")
181 pub fn usage(argv0: &str) {
183 getopts::usage(format!("{} [options] <input>", argv0).as_slice(),
187 pub fn main_args(args: &[String]) -> int {
188 let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
195 if matches.opt_present("h") || matches.opt_present("help") {
196 usage(args[0].as_slice());
198 } else if matches.opt_present("version") {
199 match rustc::driver::version("rustdoc", &matches) {
208 if matches.opt_strs("passes").as_slice() == &["list".to_string()] {
209 println!("Available passes for running rustdoc:");
210 for &(name, _, description) in PASSES.iter() {
211 println!("{:>20s} - {}", name, description);
213 println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
214 for &name in DEFAULT_PASSES.iter() {
215 println!("{:>20s}", name);
220 if matches.free.len() == 0 {
221 println!("expected an input file to act on");
223 } if matches.free.len() > 1 {
224 println!("only one input file may be specified");
227 let input = matches.free[0].as_slice();
229 let libs = matches.opt_strs("L").iter().map(|s| Path::new(s.as_slice())).collect();
230 let externs = match parse_externs(&matches) {
238 let test_args = matches.opt_strs("test-args");
239 let test_args: Vec<String> = test_args.iter()
240 .flat_map(|s| s.as_slice().words())
241 .map(|s| s.to_string())
244 let should_test = matches.opt_present("test");
245 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
247 let output = matches.opt_str("o").map(|s| Path::new(s));
248 let cfgs = matches.opt_strs("cfg");
250 let external_html = match ExternalHtml::load(
251 matches.opt_strs("html-in-header").as_slice(),
252 matches.opt_strs("html-before-content").as_slice(),
253 matches.opt_strs("html-after-content").as_slice()) {
257 let crate_name = matches.opt_str("crate-name");
259 match (should_test, markdown_input) {
261 return markdown::test(input, libs, externs, test_args)
264 return test::run(input, cfgs, libs, externs, test_args, crate_name)
266 (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
267 &matches, &external_html,
268 !matches.opt_present("markdown-no-toc")),
272 let (krate, res) = match acquire_input(input, externs, &matches) {
275 println!("input error: {}", s);
280 info!("going to format");
281 let started = time::precise_time_ns();
282 match matches.opt_str("w").as_ref().map(|s| s.as_slice()) {
283 Some("html") | None => {
284 match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc"))) {
286 Err(e) => fail!("failed to generate documentation: {}", e),
290 match json_output(krate, res, output.unwrap_or(Path::new("doc.json"))) {
292 Err(e) => fail!("failed to write json: {}", e),
296 println!("unknown output format: {}", s);
300 let ended = time::precise_time_ns();
301 info!("Took {:.03f}s", (ended as f64 - started as f64) / 1e9f64);
306 /// Looks inside the command line arguments to extract the relevant input format
307 /// and files and then generates the necessary rustdoc output for formatting.
308 fn acquire_input(input: &str,
309 externs: core::Externs,
310 matches: &getopts::Matches) -> Result<Output, String> {
311 match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
312 Some("rust") => Ok(rust_input(input, externs, matches)),
313 Some("json") => json_input(input),
314 Some(s) => Err(format!("unknown input format: {}", s)),
316 if input.ends_with(".json") {
319 Ok(rust_input(input, externs, matches))
325 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
326 /// returns a `HashMap` mapping crate names to their paths or else an
328 fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
329 let mut externs = HashMap::new();
330 for arg in matches.opt_strs("extern").iter() {
331 let mut parts = arg.as_slice().splitn(1, '=');
332 let name = match parts.next() {
335 return Err("--extern value must not be empty".to_string());
338 let location = match parts.next() {
341 return Err("--extern value must be of the format `foo=bar`".to_string());
344 let locs = externs.find_or_insert(name.to_string(), Vec::new());
345 locs.push(location.to_string());
350 /// Interprets the input file as a rust source file, passing it through the
351 /// compiler all the way through the analysis passes. The rustdoc output is then
352 /// generated from the cleaned AST of the crate.
354 /// This form of input will run all of the plug/cleaning passes
355 fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matches) -> Output {
356 let mut default_passes = !matches.opt_present("no-defaults");
357 let mut passes = matches.opt_strs("passes");
358 let mut plugins = matches.opt_strs("plugins");
360 // First, parse the crate and extract all relevant information.
361 let libs: Vec<Path> = matches.opt_strs("L")
363 .map(|s| Path::new(s.as_slice()))
365 let cfgs = matches.opt_strs("cfg");
366 let triple = matches.opt_str("target");
368 let cr = Path::new(cratefile);
369 info!("starting to run rustc");
370 let (mut krate, analysis) = std::task::try(proc() {
372 core::run_core(libs.move_iter().collect(),
377 }).map_err(|boxed_any|format!("{:?}", boxed_any)).unwrap();
378 info!("finished with rustc");
379 analysiskey.replace(Some(analysis));
381 match matches.opt_str("crate-name") {
382 Some(name) => krate.name = name,
386 // Process all of the crate attributes, extracting plugin metadata along
387 // with the passes which we are supposed to run.
388 match krate.module.as_ref().unwrap().doc_list() {
390 for inner in nested.iter() {
393 if "no_default_passes" == x.as_slice() => {
394 default_passes = false;
396 clean::NameValue(ref x, ref value)
397 if "passes" == x.as_slice() => {
398 for pass in value.as_slice().words() {
399 passes.push(pass.to_string());
402 clean::NameValue(ref x, ref value)
403 if "plugins" == x.as_slice() => {
404 for p in value.as_slice().words() {
405 plugins.push(p.to_string());
415 for name in DEFAULT_PASSES.iter().rev() {
416 passes.insert(0, name.to_string());
420 // Load all plugins/passes into a PluginManager
421 let path = matches.opt_str("plugin-path")
422 .unwrap_or("/tmp/rustdoc/plugins".to_string());
423 let mut pm = plugins::PluginManager::new(Path::new(path));
424 for pass in passes.iter() {
425 let plugin = match PASSES.iter()
426 .position(|&(p, _, _)| {
429 Some(i) => PASSES[i].val1(),
431 error!("unknown pass {}, skipping", *pass);
435 pm.add_plugin(plugin);
437 info!("loading plugins...");
438 for pname in plugins.move_iter() {
439 pm.load_plugin(pname);
443 info!("Executing passes/plugins");
444 return pm.run_plugins(krate);
447 /// This input format purely deserializes the json output file. No passes are
448 /// run over the deserialized output.
449 fn json_input(input: &str) -> Result<Output, String> {
450 let mut input = match File::open(&Path::new(input)) {
453 return Err(format!("couldn't open {}: {}", input, e))
456 match json::from_reader(&mut input) {
457 Err(s) => Err(s.to_string()),
458 Ok(json::Object(obj)) => {
460 // Make sure the schema is what we expect
461 match obj.pop(&"schema".to_string()) {
462 Some(json::String(version)) => {
463 if version.as_slice() != SCHEMA_VERSION {
465 "sorry, but I only understand version {}",
469 Some(..) => return Err("malformed json".to_string()),
470 None => return Err("expected a schema version".to_string()),
472 let krate = match obj.pop(&"crate".to_string()) {
474 let mut d = json::Decoder::new(json);
475 Decodable::decode(&mut d).unwrap()
477 None => return Err("malformed json".to_string()),
479 // FIXME: this should read from the "plugins" field, but currently
480 // Json doesn't implement decodable...
481 let plugin_output = Vec::new();
482 Ok((krate, plugin_output))
485 Err("malformed json input: expected an object at the \
491 /// Outputs the crate/plugin json as a giant json blob at the specified
493 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
494 dst: Path) -> io::IoResult<()> {
496 // "schema": version,
497 // "crate": { parsed crate ... },
498 // "plugins": { output of plugins ... }
500 let mut json = std::collections::TreeMap::new();
501 json.insert("schema".to_string(), json::String(SCHEMA_VERSION.to_string()));
502 let plugins_json = res.move_iter()
506 Some((string, json)) => {
507 Some((string.to_string(), json))
512 // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
513 // straight to the Rust JSON representation.
514 let crate_json_str = {
515 let mut w = MemWriter::new();
517 let mut encoder = json::Encoder::new(&mut w as &mut io::Writer);
518 krate.encode(&mut encoder).unwrap();
520 String::from_utf8(w.unwrap()).unwrap()
522 let crate_json = match json::from_str(crate_json_str.as_slice()) {
524 Err(e) => fail!("Rust generated JSON is invalid: {:?}", e)
527 json.insert("crate".to_string(), crate_json);
528 json.insert("plugins".to_string(), json::Object(plugins_json));
530 let mut file = try!(File::create(&dst));
531 json::Object(json).to_writer(&mut file)