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)]
28 #![feature(set_stdio)]
30 #![feature(rustc_private)]
31 #![feature(staged_api)]
35 #![feature(str_words)]
36 #![feature(file_path)]
38 #![feature(path_relative_from)]
39 #![feature(slice_patterns)]
45 extern crate rustc_trans;
46 extern crate rustc_driver;
47 extern crate rustc_resolve;
48 extern crate rustc_lint;
49 extern crate rustc_back;
50 extern crate serialize;
52 extern crate test as testing;
54 #[macro_use] extern crate log;
56 extern crate serialize as rustc_serialize; // used by deriving
58 use std::cell::RefCell;
59 use std::collections::HashMap;
62 use std::io::{self, Read, Write};
63 use std::path::PathBuf;
65 use std::sync::mpsc::channel;
67 use externalfiles::ExternalHtml;
68 use serialize::Decodable;
69 use serialize::json::{self, Json};
70 use rustc::session::search_paths::SearchPaths;
72 // reexported from `clean` so it can be easily updated with the mod itself
73 pub use clean::SCHEMA_VERSION;
76 pub mod externalfiles;
95 pub mod stability_summary;
100 type Pass = (&'static str, // name
101 fn(clean::Crate) -> plugins::PluginResult, // fn
102 &'static str); // description
104 const PASSES: &'static [Pass] = &[
105 ("strip-hidden", passes::strip_hidden,
106 "strips all doc(hidden) items from the output"),
107 ("unindent-comments", passes::unindent_comments,
108 "removes excess indentation on comments in order for markdown to like it"),
109 ("collapse-docs", passes::collapse_docs,
110 "concatenates all document attributes into one document attribute"),
111 ("strip-private", passes::strip_private,
112 "strips all private items from a crate which cannot be seen externally"),
115 const DEFAULT_PASSES: &'static [&'static str] = &[
122 thread_local!(pub static ANALYSISKEY: Rc<RefCell<Option<core::CrateAnalysis>>> = {
123 Rc::new(RefCell::new(None))
128 json_plugins: Vec<plugins::PluginJson>,
133 const STACK_SIZE: usize = 32000000; // 32MB
134 let res = std::thread::Builder::new().stack_size(STACK_SIZE).scoped(move || {
135 let s = env::args().collect::<Vec<_>>();
138 env::set_exit_status(res as i32);
141 pub fn opts() -> Vec<getopts::OptGroup> {
144 optflag("h", "help", "show this help message"),
145 optflag("V", "version", "print rustdoc's version"),
146 optflag("v", "verbose", "use verbose output"),
147 optopt("r", "input-format", "the input type of the specified file",
149 optopt("w", "output-format", "the output type to write",
151 optopt("o", "output", "where to place the output", "PATH"),
152 optopt("", "crate-name", "specify the name of this crate", "NAME"),
153 optmulti("L", "library-path", "directory to add to crate search path",
155 optmulti("", "cfg", "pass a --cfg to rustc", ""),
156 optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH"),
157 optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
158 optmulti("", "passes", "space separated list of passes to also run, a \
159 value of `list` will print available passes",
161 optmulti("", "plugins", "space separated list of plugins to also load",
163 optflag("", "no-defaults", "don't run the default passes"),
164 optflag("", "test", "run code examples as tests"),
165 optmulti("", "test-args", "arguments to pass to the test runner",
167 optopt("", "target", "target triple to document", "TRIPLE"),
168 optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
170 optmulti("", "html-in-header",
171 "files to include inline in the <head> section of a rendered Markdown file \
172 or generated documentation",
174 optmulti("", "html-before-content",
175 "files to include inline between <body> and the content of a rendered \
176 Markdown file or generated documentation",
178 optmulti("", "html-after-content",
179 "files to include inline between the content and </body> of a rendered \
180 Markdown file or generated documentation",
182 optopt("", "markdown-playground-url",
183 "URL to send code snippets to", "URL"),
184 optflag("", "markdown-no-toc", "don't include table of contents")
188 pub fn usage(argv0: &str) {
190 getopts::usage(&format!("{} [options] <input>", argv0),
194 pub fn main_args(args: &[String]) -> isize {
195 let matches = match getopts::getopts(args.tail(), &opts()) {
202 if matches.opt_present("h") || matches.opt_present("help") {
205 } else if matches.opt_present("version") {
206 rustc_driver::version("rustdoc", &matches);
210 if matches.opt_strs("passes") == ["list"] {
211 println!("Available passes for running rustdoc:");
212 for &(name, _, description) in PASSES {
213 println!("{:>20} - {}", name, description);
215 println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
216 for &name in DEFAULT_PASSES {
217 println!("{:>20}", name);
222 if matches.free.len() == 0 {
223 println!("expected an input file to act on");
225 } if matches.free.len() > 1 {
226 println!("only one input file may be specified");
229 let input = &matches.free[0];
231 let mut libs = SearchPaths::new();
232 for s in &matches.opt_strs("L") {
235 let externs = match parse_externs(&matches) {
243 let test_args = matches.opt_strs("test-args");
244 let test_args: Vec<String> = test_args.iter()
245 .flat_map(|s| s.words())
246 .map(|s| s.to_string())
249 let should_test = matches.opt_present("test");
250 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
252 let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
253 let cfgs = matches.opt_strs("cfg");
255 let external_html = match ExternalHtml::load(
256 &matches.opt_strs("html-in-header"),
257 &matches.opt_strs("html-before-content"),
258 &matches.opt_strs("html-after-content")) {
262 let crate_name = matches.opt_str("crate-name");
264 match (should_test, markdown_input) {
266 return markdown::test(input, libs, externs, test_args)
269 return test::run(input, cfgs, libs, externs, test_args, crate_name)
271 (false, true) => return markdown::render(input,
272 output.unwrap_or(PathBuf::from("doc")),
273 &matches, &external_html,
274 !matches.opt_present("markdown-no-toc")),
278 let out = match acquire_input(input, externs, &matches) {
281 println!("input error: {}", s);
285 let Output { krate, json_plugins, passes, } = out;
286 info!("going to format");
287 match matches.opt_str("w").as_ref().map(|s| &**s) {
288 Some("html") | None => {
289 match html::render::run(krate, &external_html,
290 output.unwrap_or(PathBuf::from("doc")),
291 passes.into_iter().collect()) {
293 Err(e) => panic!("failed to generate documentation: {}", e),
297 match json_output(krate, json_plugins,
298 output.unwrap_or(PathBuf::from("doc.json"))) {
300 Err(e) => panic!("failed to write json: {}", e),
304 println!("unknown output format: {}", s);
312 /// Looks inside the command line arguments to extract the relevant input format
313 /// and files and then generates the necessary rustdoc output for formatting.
314 fn acquire_input(input: &str,
315 externs: core::Externs,
316 matches: &getopts::Matches) -> Result<Output, String> {
317 match matches.opt_str("r").as_ref().map(|s| &**s) {
318 Some("rust") => Ok(rust_input(input, externs, matches)),
319 Some("json") => json_input(input),
320 Some(s) => Err(format!("unknown input format: {}", s)),
322 if input.ends_with(".json") {
325 Ok(rust_input(input, externs, matches))
331 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
332 /// returns a `HashMap` mapping crate names to their paths or else an
334 fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
335 let mut externs = HashMap::new();
336 for arg in &matches.opt_strs("extern") {
337 let mut parts = arg.splitn(1, '=');
338 let name = match parts.next() {
341 return Err("--extern value must not be empty".to_string());
344 let location = match parts.next() {
347 return Err("--extern value must be of the format `foo=bar`".to_string());
350 let name = name.to_string();
351 externs.entry(name).or_insert(vec![]).push(location.to_string());
356 /// Interprets the input file as a rust source file, passing it through the
357 /// compiler all the way through the analysis passes. The rustdoc output is then
358 /// generated from the cleaned AST of the crate.
360 /// This form of input will run all of the plug/cleaning passes
361 #[allow(deprecated)] // for old Path in plugin manager
362 fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matches) -> Output {
363 let mut default_passes = !matches.opt_present("no-defaults");
364 let mut passes = matches.opt_strs("passes");
365 let mut plugins = matches.opt_strs("plugins");
367 // First, parse the crate and extract all relevant information.
368 let mut paths = SearchPaths::new();
369 for s in &matches.opt_strs("L") {
372 let cfgs = matches.opt_strs("cfg");
373 let triple = matches.opt_str("target");
375 let cr = PathBuf::from(cratefile);
376 info!("starting to run rustc");
378 let (tx, rx) = channel();
379 std::thread::spawn(move || {
380 use rustc::session::config::Input;
382 tx.send(core::run_core(paths, cfgs, externs, Input::File(cr),
384 }).join().map_err(|_| "rustc failed").unwrap();
385 let (mut krate, analysis) = rx.recv().unwrap();
386 info!("finished with rustc");
387 let mut analysis = Some(analysis);
388 ANALYSISKEY.with(|s| {
389 *s.borrow_mut() = analysis.take();
392 match matches.opt_str("crate-name") {
393 Some(name) => krate.name = name,
397 // Process all of the crate attributes, extracting plugin metadata along
398 // with the passes which we are supposed to run.
399 match krate.module.as_ref().unwrap().doc_list() {
401 for inner in nested {
404 if "no_default_passes" == *x => {
405 default_passes = false;
407 clean::NameValue(ref x, ref value)
408 if "passes" == *x => {
409 for pass in value.words() {
410 passes.push(pass.to_string());
413 clean::NameValue(ref x, ref value)
414 if "plugins" == *x => {
415 for p in value.words() {
416 plugins.push(p.to_string());
426 for name in DEFAULT_PASSES.iter().rev() {
427 passes.insert(0, name.to_string());
431 // Load all plugins/passes into a PluginManager
432 let path = matches.opt_str("plugin-path")
433 .unwrap_or("/tmp/rustdoc/plugins".to_string());
434 let mut pm = plugins::PluginManager::new(PathBuf::from(path));
435 for pass in &passes {
436 let plugin = match PASSES.iter()
437 .position(|&(p, _, _)| {
440 Some(i) => PASSES[i].1,
442 error!("unknown pass {}, skipping", *pass);
446 pm.add_plugin(plugin);
448 info!("loading plugins...");
449 for pname in plugins {
450 pm.load_plugin(pname);
454 info!("Executing passes/plugins");
455 let (krate, json) = pm.run_plugins(krate);
456 return Output { krate: krate, json_plugins: json, passes: passes, };
459 /// This input format purely deserializes the json output file. No passes are
460 /// run over the deserialized output.
461 fn json_input(input: &str) -> Result<Output, String> {
462 let mut bytes = Vec::new();
463 match File::open(input).and_then(|mut f| f.read_to_end(&mut bytes)) {
465 Err(e) => return Err(format!("couldn't open {}: {}", input, e)),
467 match json::from_reader(&mut &bytes[..]) {
468 Err(s) => Err(format!("{:?}", s)),
469 Ok(Json::Object(obj)) => {
471 // Make sure the schema is what we expect
472 match obj.remove(&"schema".to_string()) {
473 Some(Json::String(version)) => {
474 if version != SCHEMA_VERSION {
476 "sorry, but I only understand version {}",
480 Some(..) => return Err("malformed json".to_string()),
481 None => return Err("expected a schema version".to_string()),
483 let krate = match obj.remove(&"crate".to_string()) {
485 let mut d = json::Decoder::new(json);
486 Decodable::decode(&mut d).unwrap()
488 None => return Err("malformed json".to_string()),
490 // FIXME: this should read from the "plugins" field, but currently
491 // Json doesn't implement decodable...
492 let plugin_output = Vec::new();
493 Ok(Output { krate: krate, json_plugins: plugin_output, passes: Vec::new(), })
496 Err("malformed json input: expected an object at the \
502 /// Outputs the crate/plugin json as a giant json blob at the specified
504 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
505 dst: PathBuf) -> io::Result<()> {
507 // "schema": version,
508 // "crate": { parsed crate ... },
509 // "plugins": { output of plugins ... }
511 let mut json = std::collections::BTreeMap::new();
512 json.insert("schema".to_string(), Json::String(SCHEMA_VERSION.to_string()));
513 let plugins_json = res.into_iter()
517 Some((string, json)) => {
518 Some((string.to_string(), json))
523 // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
524 // straight to the Rust JSON representation.
525 let crate_json_str = format!("{}", json::as_json(&krate));
526 let crate_json = match json::from_str(&crate_json_str) {
528 Err(e) => panic!("Rust generated JSON is invalid: {:?}", e)
531 json.insert("crate".to_string(), crate_json);
532 json.insert("plugins".to_string(), Json::Object(plugins_json));
534 let mut file = try!(File::create(&dst));
535 write!(&mut file, "{}", Json::Object(json))