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 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
12 #![cfg_attr(stage0, feature(custom_attribute))]
13 #![crate_name = "rustdoc"]
14 #![unstable(feature = "rustdoc")]
16 #![crate_type = "dylib"]
17 #![crate_type = "rlib"]
18 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
19 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
20 html_root_url = "http://doc.rust-lang.org/nightly/",
21 html_playground_url = "http://play.rust-lang.org/")]
23 #![feature(box_patterns)]
24 #![feature(box_syntax)]
25 #![feature(collections)]
27 #![feature(exit_status)]
29 #![feature(set_stdio)]
32 #![feature(rustc_private)]
33 #![feature(staged_api)]
37 #![feature(str_words)]
38 #![feature(file_path)]
40 #![feature(path_relative_from)]
47 extern crate rustc_trans;
48 extern crate rustc_driver;
49 extern crate rustc_resolve;
50 extern crate rustc_lint;
51 extern crate rustc_back;
52 extern crate serialize;
54 extern crate test as testing;
56 #[macro_use] extern crate log;
58 extern crate serialize as rustc_serialize; // used by deriving
60 use std::cell::RefCell;
61 use std::collections::HashMap;
64 use std::io::{self, Read, Write};
65 use std::path::PathBuf;
67 use std::sync::mpsc::channel;
69 #[allow(deprecated)] use std::old_path::Path;
71 use externalfiles::ExternalHtml;
72 use serialize::Decodable;
73 use serialize::json::{self, Json};
74 use rustc::session::search_paths::SearchPaths;
76 // reexported from `clean` so it can be easily updated with the mod itself
77 pub use clean::SCHEMA_VERSION;
80 pub mod externalfiles;
99 pub mod stability_summary;
104 type Pass = (&'static str, // name
105 fn(clean::Crate) -> plugins::PluginResult, // fn
106 &'static str); // description
108 const PASSES: &'static [Pass] = &[
109 ("strip-hidden", passes::strip_hidden,
110 "strips all doc(hidden) items from the output"),
111 ("unindent-comments", passes::unindent_comments,
112 "removes excess indentation on comments in order for markdown to like it"),
113 ("collapse-docs", passes::collapse_docs,
114 "concatenates all document attributes into one document attribute"),
115 ("strip-private", passes::strip_private,
116 "strips all private items from a crate which cannot be seen externally"),
119 const DEFAULT_PASSES: &'static [&'static str] = &[
126 thread_local!(pub static ANALYSISKEY: Rc<RefCell<Option<core::CrateAnalysis>>> = {
127 Rc::new(RefCell::new(None))
132 json_plugins: Vec<plugins::PluginJson>,
137 const STACK_SIZE: usize = 32000000; // 32MB
138 let res = std::thread::Builder::new().stack_size(STACK_SIZE).scoped(move || {
139 let s = env::args().collect::<Vec<_>>();
142 env::set_exit_status(res as i32);
145 pub fn opts() -> Vec<getopts::OptGroup> {
148 optflag("h", "help", "show this help message"),
149 optflag("V", "version", "print rustdoc's version"),
150 optflag("v", "verbose", "use verbose output"),
151 optopt("r", "input-format", "the input type of the specified file",
153 optopt("w", "output-format", "the output type to write",
155 optopt("o", "output", "where to place the output", "PATH"),
156 optopt("", "crate-name", "specify the name of this crate", "NAME"),
157 optmulti("L", "library-path", "directory to add to crate search path",
159 optmulti("", "cfg", "pass a --cfg to rustc", ""),
160 optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH"),
161 optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
162 optmulti("", "passes", "space separated list of passes to also run, a \
163 value of `list` will print available passes",
165 optmulti("", "plugins", "space separated list of plugins to also load",
167 optflag("", "no-defaults", "don't run the default passes"),
168 optflag("", "test", "run code examples as tests"),
169 optmulti("", "test-args", "arguments to pass to the test runner",
171 optopt("", "target", "target triple to document", "TRIPLE"),
172 optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
174 optmulti("", "html-in-header",
175 "files to include inline in the <head> section of a rendered Markdown file \
176 or generated documentation",
178 optmulti("", "html-before-content",
179 "files to include inline between <body> and the content of a rendered \
180 Markdown file or generated documentation",
182 optmulti("", "html-after-content",
183 "files to include inline between the content and </body> of a rendered \
184 Markdown file or generated documentation",
186 optopt("", "markdown-playground-url",
187 "URL to send code snippets to", "URL"),
188 optflag("", "markdown-no-toc", "don't include table of contents")
192 pub fn usage(argv0: &str) {
194 getopts::usage(&format!("{} [options] <input>", argv0),
198 pub fn main_args(args: &[String]) -> int {
199 let matches = match getopts::getopts(args.tail(), &opts()) {
206 if matches.opt_present("h") || matches.opt_present("help") {
209 } else if matches.opt_present("version") {
210 rustc_driver::version("rustdoc", &matches);
214 if matches.opt_strs("passes") == ["list"] {
215 println!("Available passes for running rustdoc:");
216 for &(name, _, description) in PASSES {
217 println!("{:>20} - {}", name, description);
219 println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
220 for &name in DEFAULT_PASSES {
221 println!("{:>20}", name);
226 if matches.free.len() == 0 {
227 println!("expected an input file to act on");
229 } if matches.free.len() > 1 {
230 println!("only one input file may be specified");
233 let input = &matches.free[0];
235 let mut libs = SearchPaths::new();
236 for s in &matches.opt_strs("L") {
239 let externs = match parse_externs(&matches) {
247 let test_args = matches.opt_strs("test-args");
248 let test_args: Vec<String> = test_args.iter()
249 .flat_map(|s| s.words())
250 .map(|s| s.to_string())
253 let should_test = matches.opt_present("test");
254 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
256 let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
257 let cfgs = matches.opt_strs("cfg");
259 let external_html = match ExternalHtml::load(
260 &matches.opt_strs("html-in-header"),
261 &matches.opt_strs("html-before-content"),
262 &matches.opt_strs("html-after-content")) {
266 let crate_name = matches.opt_str("crate-name");
268 match (should_test, markdown_input) {
270 return markdown::test(input, libs, externs, test_args)
273 return test::run(input, cfgs, libs, externs, test_args, crate_name)
275 (false, true) => return markdown::render(input,
276 output.unwrap_or(PathBuf::from("doc")),
277 &matches, &external_html,
278 !matches.opt_present("markdown-no-toc")),
282 let out = match acquire_input(input, externs, &matches) {
285 println!("input error: {}", s);
289 let Output { krate, json_plugins, passes, } = out;
290 info!("going to format");
291 match matches.opt_str("w").as_ref().map(|s| &**s) {
292 Some("html") | None => {
293 match html::render::run(krate, &external_html,
294 output.unwrap_or(PathBuf::from("doc")),
295 passes.into_iter().collect()) {
297 Err(e) => panic!("failed to generate documentation: {}", e),
301 match json_output(krate, json_plugins,
302 output.unwrap_or(PathBuf::from("doc.json"))) {
304 Err(e) => panic!("failed to write json: {}", e),
308 println!("unknown output format: {}", s);
316 /// Looks inside the command line arguments to extract the relevant input format
317 /// and files and then generates the necessary rustdoc output for formatting.
318 fn acquire_input(input: &str,
319 externs: core::Externs,
320 matches: &getopts::Matches) -> Result<Output, String> {
321 match matches.opt_str("r").as_ref().map(|s| &**s) {
322 Some("rust") => Ok(rust_input(input, externs, matches)),
323 Some("json") => json_input(input),
324 Some(s) => Err(format!("unknown input format: {}", s)),
326 if input.ends_with(".json") {
329 Ok(rust_input(input, externs, matches))
335 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
336 /// returns a `HashMap` mapping crate names to their paths or else an
338 fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
339 let mut externs = HashMap::new();
340 for arg in &matches.opt_strs("extern") {
341 let mut parts = arg.splitn(1, '=');
342 let name = match parts.next() {
345 return Err("--extern value must not be empty".to_string());
348 let location = match parts.next() {
351 return Err("--extern value must be of the format `foo=bar`".to_string());
354 let name = name.to_string();
355 externs.entry(name).or_insert(vec![]).push(location.to_string());
360 /// Interprets the input file as a rust source file, passing it through the
361 /// compiler all the way through the analysis passes. The rustdoc output is then
362 /// generated from the cleaned AST of the crate.
364 /// This form of input will run all of the plug/cleaning passes
365 #[allow(deprecated)] // for old Path in plugin manager
366 fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matches) -> Output {
367 let mut default_passes = !matches.opt_present("no-defaults");
368 let mut passes = matches.opt_strs("passes");
369 let mut plugins = matches.opt_strs("plugins");
371 // First, parse the crate and extract all relevant information.
372 let mut paths = SearchPaths::new();
373 for s in &matches.opt_strs("L") {
376 let cfgs = matches.opt_strs("cfg");
377 let triple = matches.opt_str("target");
379 let cr = PathBuf::from(cratefile);
380 info!("starting to run rustc");
382 let (tx, rx) = channel();
383 std::thread::spawn(move || {
384 use rustc::session::config::Input;
386 tx.send(core::run_core(paths, cfgs, externs, Input::File(cr),
388 }).join().map_err(|_| "rustc failed").unwrap();
389 let (mut krate, analysis) = rx.recv().unwrap();
390 info!("finished with rustc");
391 let mut analysis = Some(analysis);
392 ANALYSISKEY.with(|s| {
393 *s.borrow_mut() = analysis.take();
396 match matches.opt_str("crate-name") {
397 Some(name) => krate.name = name,
401 // Process all of the crate attributes, extracting plugin metadata along
402 // with the passes which we are supposed to run.
403 match krate.module.as_ref().unwrap().doc_list() {
405 for inner in nested {
408 if "no_default_passes" == *x => {
409 default_passes = false;
411 clean::NameValue(ref x, ref value)
412 if "passes" == *x => {
413 for pass in value.words() {
414 passes.push(pass.to_string());
417 clean::NameValue(ref x, ref value)
418 if "plugins" == *x => {
419 for p in value.words() {
420 plugins.push(p.to_string());
430 for name in DEFAULT_PASSES.iter().rev() {
431 passes.insert(0, name.to_string());
435 // Load all plugins/passes into a PluginManager
436 let path = matches.opt_str("plugin-path")
437 .unwrap_or("/tmp/rustdoc/plugins".to_string());
438 let mut pm = plugins::PluginManager::new(Path::new(path));
439 for pass in &passes {
440 let plugin = match PASSES.iter()
441 .position(|&(p, _, _)| {
444 Some(i) => PASSES[i].1,
446 error!("unknown pass {}, skipping", *pass);
450 pm.add_plugin(plugin);
452 info!("loading plugins...");
453 for pname in plugins {
454 pm.load_plugin(pname);
458 info!("Executing passes/plugins");
459 let (krate, json) = pm.run_plugins(krate);
460 return Output { krate: krate, json_plugins: json, passes: passes, };
463 /// This input format purely deserializes the json output file. No passes are
464 /// run over the deserialized output.
465 fn json_input(input: &str) -> Result<Output, String> {
466 let mut bytes = Vec::new();
467 match File::open(input).and_then(|mut f| f.read_to_end(&mut bytes)) {
469 Err(e) => return Err(format!("couldn't open {}: {}", input, e)),
471 match json::from_reader(&mut &bytes[..]) {
472 Err(s) => Err(format!("{:?}", s)),
473 Ok(Json::Object(obj)) => {
475 // Make sure the schema is what we expect
476 match obj.remove(&"schema".to_string()) {
477 Some(Json::String(version)) => {
478 if version != SCHEMA_VERSION {
480 "sorry, but I only understand version {}",
484 Some(..) => return Err("malformed json".to_string()),
485 None => return Err("expected a schema version".to_string()),
487 let krate = match obj.remove(&"crate".to_string()) {
489 let mut d = json::Decoder::new(json);
490 Decodable::decode(&mut d).unwrap()
492 None => return Err("malformed json".to_string()),
494 // FIXME: this should read from the "plugins" field, but currently
495 // Json doesn't implement decodable...
496 let plugin_output = Vec::new();
497 Ok(Output { krate: krate, json_plugins: plugin_output, passes: Vec::new(), })
500 Err("malformed json input: expected an object at the \
506 /// Outputs the crate/plugin json as a giant json blob at the specified
508 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
509 dst: PathBuf) -> io::Result<()> {
511 // "schema": version,
512 // "crate": { parsed crate ... },
513 // "plugins": { output of plugins ... }
515 let mut json = std::collections::BTreeMap::new();
516 json.insert("schema".to_string(), Json::String(SCHEMA_VERSION.to_string()));
517 let plugins_json = res.into_iter()
521 Some((string, json)) => {
522 Some((string.to_string(), json))
527 // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
528 // straight to the Rust JSON representation.
529 let crate_json_str = format!("{}", json::as_json(&krate));
530 let crate_json = match json::from_str(&crate_json_str) {
532 Err(e) => panic!("Rust generated JSON is invalid: {:?}", e)
535 json.insert("crate".to_string(), crate_json);
536 json.insert("plugins".to_string(), Json::Object(plugins_json));
538 let mut file = try!(File::create(&dst));
539 write!(&mut file, "{}", Json::Object(json))