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)]
25 extern crate serialize;
27 extern crate "test" as testing;
29 #[phase(plugin, link)] extern crate log;
32 use std::io::{File, MemWriter};
33 use std::collections::HashMap;
34 use std::collections::hashmap::{Occupied, Vacant};
35 use serialize::{json, Decodable, Encodable};
36 use externalfiles::ExternalHtml;
38 // reexported from `clean` so it can be easily updated with the mod itself
39 pub use clean::SCHEMA_VERSION;
45 pub mod externalfiles;
60 pub mod stability_summary;
65 type Pass = (&'static str, // name
66 fn(clean::Crate) -> plugins::PluginResult, // fn
67 &'static str); // description
69 static PASSES: &'static [Pass] = &[
70 ("strip-hidden", passes::strip_hidden,
71 "strips all doc(hidden) items from the output"),
72 ("unindent-comments", passes::unindent_comments,
73 "removes excess indentation on comments in order for markdown to like it"),
74 ("collapse-docs", passes::collapse_docs,
75 "concatenates all document attributes into one document attribute"),
76 ("strip-private", passes::strip_private,
77 "strips all private items from a crate which cannot be seen externally"),
80 static DEFAULT_PASSES: &'static [&'static str] = &[
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 = match externs.entry(name.to_string()) {
345 Vacant(entry) => entry.set(Vec::with_capacity(1)),
346 Occupied(entry) => entry.into_mut(),
348 locs.push(location.to_string());
353 /// Interprets the input file as a rust source file, passing it through the
354 /// compiler all the way through the analysis passes. The rustdoc output is then
355 /// generated from the cleaned AST of the crate.
357 /// This form of input will run all of the plug/cleaning passes
358 fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matches) -> Output {
359 let mut default_passes = !matches.opt_present("no-defaults");
360 let mut passes = matches.opt_strs("passes");
361 let mut plugins = matches.opt_strs("plugins");
363 // First, parse the crate and extract all relevant information.
364 let libs: Vec<Path> = matches.opt_strs("L")
366 .map(|s| Path::new(s.as_slice()))
368 let cfgs = matches.opt_strs("cfg");
369 let triple = matches.opt_str("target");
371 let cr = Path::new(cratefile);
372 info!("starting to run rustc");
373 let (mut krate, analysis) = std::task::try(proc() {
375 core::run_core(libs, cfgs, externs, &cr, triple)
376 }).map_err(|boxed_any|format!("{:?}", boxed_any)).unwrap();
377 info!("finished with rustc");
378 analysiskey.replace(Some(analysis));
380 match matches.opt_str("crate-name") {
381 Some(name) => krate.name = name,
385 // Process all of the crate attributes, extracting plugin metadata along
386 // with the passes which we are supposed to run.
387 match krate.module.as_ref().unwrap().doc_list() {
389 for inner in nested.iter() {
392 if "no_default_passes" == x.as_slice() => {
393 default_passes = false;
395 clean::NameValue(ref x, ref value)
396 if "passes" == x.as_slice() => {
397 for pass in value.as_slice().words() {
398 passes.push(pass.to_string());
401 clean::NameValue(ref x, ref value)
402 if "plugins" == x.as_slice() => {
403 for p in value.as_slice().words() {
404 plugins.push(p.to_string());
414 for name in DEFAULT_PASSES.iter().rev() {
415 passes.insert(0, name.to_string());
419 // Load all plugins/passes into a PluginManager
420 let path = matches.opt_str("plugin-path")
421 .unwrap_or("/tmp/rustdoc/plugins".to_string());
422 let mut pm = plugins::PluginManager::new(Path::new(path));
423 for pass in passes.iter() {
424 let plugin = match PASSES.iter()
425 .position(|&(p, _, _)| {
428 Some(i) => PASSES[i].val1(),
430 error!("unknown pass {}, skipping", *pass);
434 pm.add_plugin(plugin);
436 info!("loading plugins...");
437 for pname in plugins.into_iter() {
438 pm.load_plugin(pname);
442 info!("Executing passes/plugins");
443 return pm.run_plugins(krate);
446 /// This input format purely deserializes the json output file. No passes are
447 /// run over the deserialized output.
448 fn json_input(input: &str) -> Result<Output, String> {
449 let mut input = match File::open(&Path::new(input)) {
452 return Err(format!("couldn't open {}: {}", input, e))
455 match json::from_reader(&mut input) {
456 Err(s) => Err(s.to_string()),
457 Ok(json::Object(obj)) => {
459 // Make sure the schema is what we expect
460 match obj.pop(&"schema".to_string()) {
461 Some(json::String(version)) => {
462 if version.as_slice() != SCHEMA_VERSION {
464 "sorry, but I only understand version {}",
468 Some(..) => return Err("malformed json".to_string()),
469 None => return Err("expected a schema version".to_string()),
471 let krate = match obj.pop(&"crate".to_string()) {
473 let mut d = json::Decoder::new(json);
474 Decodable::decode(&mut d).unwrap()
476 None => return Err("malformed json".to_string()),
478 // FIXME: this should read from the "plugins" field, but currently
479 // Json doesn't implement decodable...
480 let plugin_output = Vec::new();
481 Ok((krate, plugin_output))
484 Err("malformed json input: expected an object at the \
490 /// Outputs the crate/plugin json as a giant json blob at the specified
492 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
493 dst: Path) -> io::IoResult<()> {
495 // "schema": version,
496 // "crate": { parsed crate ... },
497 // "plugins": { output of plugins ... }
499 let mut json = std::collections::TreeMap::new();
500 json.insert("schema".to_string(), json::String(SCHEMA_VERSION.to_string()));
501 let plugins_json = res.into_iter()
505 Some((string, json)) => {
506 Some((string.to_string(), json))
511 // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
512 // straight to the Rust JSON representation.
513 let crate_json_str = {
514 let mut w = MemWriter::new();
516 let mut encoder = json::Encoder::new(&mut w as &mut io::Writer);
517 krate.encode(&mut encoder).unwrap();
519 String::from_utf8(w.unwrap()).unwrap()
521 let crate_json = match json::from_str(crate_json_str.as_slice()) {
523 Err(e) => fail!("Rust generated JSON is invalid: {:?}", e)
526 json.insert("crate".to_string(), crate_json);
527 json.insert("plugins".to_string(), json::Object(plugins_json));
529 let mut file = try!(File::create(&dst));
530 json::Object(json).to_writer(&mut file)