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"]
12 #![unstable(feature = "rustdoc")]
14 #![crate_type = "dylib"]
15 #![crate_type = "rlib"]
16 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
17 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
18 html_root_url = "http://doc.rust-lang.org/nightly/",
19 html_playground_url = "http://play.rust-lang.org/")]
21 #![feature(box_patterns)]
22 #![feature(box_syntax)]
23 #![feature(collections)]
31 #![feature(rustc_private)]
32 #![feature(staged_api)]
36 #![feature(str_words)]
42 extern crate rustc_trans;
43 extern crate rustc_driver;
44 extern crate rustc_resolve;
45 extern crate serialize;
47 extern crate "test" as testing;
48 #[macro_use] extern crate log;
50 extern crate "serialize" as rustc_serialize; // used by deriving
52 use std::cell::RefCell;
53 use std::collections::HashMap;
55 use std::old_io::File;
58 use std::sync::mpsc::channel;
59 use externalfiles::ExternalHtml;
60 use serialize::Decodable;
61 use serialize::json::{self, Json};
62 use rustc::session::search_paths::SearchPaths;
64 // reexported from `clean` so it can be easily updated with the mod itself
65 pub use clean::SCHEMA_VERSION;
68 pub mod externalfiles;
87 pub mod stability_summary;
92 type Pass = (&'static str, // name
93 fn(clean::Crate) -> plugins::PluginResult, // fn
94 &'static str); // description
96 static PASSES: &'static [Pass] = &[
97 ("strip-hidden", passes::strip_hidden,
98 "strips all doc(hidden) items from the output"),
99 ("unindent-comments", passes::unindent_comments,
100 "removes excess indentation on comments in order for markdown to like it"),
101 ("collapse-docs", passes::collapse_docs,
102 "concatenates all document attributes into one document attribute"),
103 ("strip-private", passes::strip_private,
104 "strips all private items from a crate which cannot be seen externally"),
107 static DEFAULT_PASSES: &'static [&'static str] = &[
114 thread_local!(pub static ANALYSISKEY: Rc<RefCell<Option<core::CrateAnalysis>>> = {
115 Rc::new(RefCell::new(None))
120 json_plugins: Vec<plugins::PluginJson>,
125 const STACK_SIZE: usize = 32000000; // 32MB
126 let res = std::thread::Builder::new().stack_size(STACK_SIZE).scoped(move || {
127 let s = env::args().collect::<Vec<_>>();
130 env::set_exit_status(res as i32);
133 pub fn opts() -> Vec<getopts::OptGroup> {
136 optflag("h", "help", "show this help message"),
137 optflag("V", "version", "print rustdoc's version"),
138 optflag("v", "verbose", "use verbose output"),
139 optopt("r", "input-format", "the input type of the specified file",
141 optopt("w", "output-format", "the output type to write",
143 optopt("o", "output", "where to place the output", "PATH"),
144 optopt("", "crate-name", "specify the name of this crate", "NAME"),
145 optmulti("L", "library-path", "directory to add to crate search path",
147 optmulti("", "cfg", "pass a --cfg to rustc", ""),
148 optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH"),
149 optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
150 optmulti("", "passes", "space separated list of passes to also run, a \
151 value of `list` will print available passes",
153 optmulti("", "plugins", "space separated list of plugins to also load",
155 optflag("", "no-defaults", "don't run the default passes"),
156 optflag("", "test", "run code examples as tests"),
157 optmulti("", "test-args", "arguments to pass to the test runner",
159 optopt("", "target", "target triple to document", "TRIPLE"),
160 optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
162 optmulti("", "html-in-header",
163 "files to include inline in the <head> section of a rendered Markdown file \
164 or generated documentation",
166 optmulti("", "html-before-content",
167 "files to include inline between <body> and the content of a rendered \
168 Markdown file or generated documentation",
170 optmulti("", "html-after-content",
171 "files to include inline between the content and </body> of a rendered \
172 Markdown file or generated documentation",
174 optopt("", "markdown-playground-url",
175 "URL to send code snippets to", "URL"),
176 optflag("", "markdown-no-toc", "don't include table of contents")
180 pub fn usage(argv0: &str) {
182 getopts::usage(&format!("{} [options] <input>", argv0),
186 pub fn main_args(args: &[String]) -> int {
187 let matches = match getopts::getopts(args.tail(), &opts()) {
194 if matches.opt_present("h") || matches.opt_present("help") {
197 } else if matches.opt_present("version") {
198 rustc_driver::version("rustdoc", &matches);
202 if matches.opt_strs("passes") == ["list"] {
203 println!("Available passes for running rustdoc:");
204 for &(name, _, description) in PASSES {
205 println!("{:>20} - {}", name, description);
207 println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
208 for &name in DEFAULT_PASSES {
209 println!("{:>20}", name);
214 if matches.free.len() == 0 {
215 println!("expected an input file to act on");
217 } if matches.free.len() > 1 {
218 println!("only one input file may be specified");
221 let input = &matches.free[0];
223 let mut libs = SearchPaths::new();
224 for s in &matches.opt_strs("L") {
227 let externs = match parse_externs(&matches) {
235 let test_args = matches.opt_strs("test-args");
236 let test_args: Vec<String> = test_args.iter()
237 .flat_map(|s| s.words())
238 .map(|s| s.to_string())
241 let should_test = matches.opt_present("test");
242 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
244 let output = matches.opt_str("o").map(|s| Path::new(s));
245 let cfgs = matches.opt_strs("cfg");
247 let external_html = match ExternalHtml::load(
248 &matches.opt_strs("html-in-header"),
249 &matches.opt_strs("html-before-content"),
250 &matches.opt_strs("html-after-content")) {
254 let crate_name = matches.opt_str("crate-name");
256 match (should_test, markdown_input) {
258 return markdown::test(input, libs, externs, test_args)
261 return test::run(input, cfgs, libs, externs, test_args, crate_name)
263 (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
264 &matches, &external_html,
265 !matches.opt_present("markdown-no-toc")),
269 let out = match acquire_input(input, externs, &matches) {
272 println!("input error: {}", s);
276 let Output { krate, json_plugins, passes, } = out;
277 info!("going to format");
278 match matches.opt_str("w").as_ref().map(|s| &**s) {
279 Some("html") | None => {
280 match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc")),
281 passes.into_iter().collect()) {
283 Err(e) => panic!("failed to generate documentation: {}", e),
287 match json_output(krate, json_plugins,
288 output.unwrap_or(Path::new("doc.json"))) {
290 Err(e) => panic!("failed to write json: {}", e),
294 println!("unknown output format: {}", s);
302 /// Looks inside the command line arguments to extract the relevant input format
303 /// and files and then generates the necessary rustdoc output for formatting.
304 fn acquire_input(input: &str,
305 externs: core::Externs,
306 matches: &getopts::Matches) -> Result<Output, String> {
307 match matches.opt_str("r").as_ref().map(|s| &**s) {
308 Some("rust") => Ok(rust_input(input, externs, matches)),
309 Some("json") => json_input(input),
310 Some(s) => Err(format!("unknown input format: {}", s)),
312 if input.ends_with(".json") {
315 Ok(rust_input(input, externs, matches))
321 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
322 /// returns a `HashMap` mapping crate names to their paths or else an
324 fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
325 let mut externs = HashMap::new();
326 for arg in &matches.opt_strs("extern") {
327 let mut parts = arg.splitn(1, '=');
328 let name = match parts.next() {
331 return Err("--extern value must not be empty".to_string());
334 let location = match parts.next() {
337 return Err("--extern value must be of the format `foo=bar`".to_string());
340 let name = name.to_string();
341 let locs = externs.entry(name).get().unwrap_or_else(
342 |vacant_entry| vacant_entry.insert(Vec::with_capacity(1)));
343 locs.push(location.to_string());
348 /// Interprets the input file as a rust source file, passing it through the
349 /// compiler all the way through the analysis passes. The rustdoc output is then
350 /// generated from the cleaned AST of the crate.
352 /// This form of input will run all of the plug/cleaning passes
353 fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matches) -> Output {
354 let mut default_passes = !matches.opt_present("no-defaults");
355 let mut passes = matches.opt_strs("passes");
356 let mut plugins = matches.opt_strs("plugins");
358 // First, parse the crate and extract all relevant information.
359 let mut paths = SearchPaths::new();
360 for s in &matches.opt_strs("L") {
363 let cfgs = matches.opt_strs("cfg");
364 let triple = matches.opt_str("target");
366 let cr = Path::new(cratefile);
367 info!("starting to run rustc");
369 let (tx, rx) = channel();
370 std::thread::spawn(move || {
371 use rustc::session::config::Input;
374 tx.send(core::run_core(paths, cfgs, externs, Input::File(cr), triple)).unwrap();
375 }).join().map_err(|_| "rustc failed").unwrap();
376 let (mut krate, analysis) = rx.recv().unwrap();
377 info!("finished with rustc");
378 let mut analysis = Some(analysis);
379 ANALYSISKEY.with(|s| {
380 *s.borrow_mut() = analysis.take();
383 match matches.opt_str("crate-name") {
384 Some(name) => krate.name = name,
388 // Process all of the crate attributes, extracting plugin metadata along
389 // with the passes which we are supposed to run.
390 match krate.module.as_ref().unwrap().doc_list() {
392 for inner in nested {
395 if "no_default_passes" == *x => {
396 default_passes = false;
398 clean::NameValue(ref x, ref value)
399 if "passes" == *x => {
400 for pass in value.words() {
401 passes.push(pass.to_string());
404 clean::NameValue(ref x, ref value)
405 if "plugins" == *x => {
406 for p in value.words() {
407 plugins.push(p.to_string());
417 for name in DEFAULT_PASSES.iter().rev() {
418 passes.insert(0, name.to_string());
422 // Load all plugins/passes into a PluginManager
423 let path = matches.opt_str("plugin-path")
424 .unwrap_or("/tmp/rustdoc/plugins".to_string());
425 let mut pm = plugins::PluginManager::new(Path::new(path));
426 for pass in &passes {
427 let plugin = match PASSES.iter()
428 .position(|&(p, _, _)| {
431 Some(i) => PASSES[i].1,
433 error!("unknown pass {}, skipping", *pass);
437 pm.add_plugin(plugin);
439 info!("loading plugins...");
440 for pname in plugins {
441 pm.load_plugin(pname);
445 info!("Executing passes/plugins");
446 let (krate, json) = pm.run_plugins(krate);
447 return Output { krate: krate, json_plugins: json, passes: passes, };
450 /// This input format purely deserializes the json output file. No passes are
451 /// run over the deserialized output.
452 fn json_input(input: &str) -> Result<Output, String> {
453 let mut input = match File::open(&Path::new(input)) {
456 return Err(format!("couldn't open {}: {}", input, e))
459 match json::from_reader(&mut input) {
460 Err(s) => Err(format!("{:?}", s)),
461 Ok(Json::Object(obj)) => {
463 // Make sure the schema is what we expect
464 match obj.remove(&"schema".to_string()) {
465 Some(Json::String(version)) => {
466 if version != SCHEMA_VERSION {
468 "sorry, but I only understand version {}",
472 Some(..) => return Err("malformed json".to_string()),
473 None => return Err("expected a schema version".to_string()),
475 let krate = match obj.remove(&"crate".to_string()) {
477 let mut d = json::Decoder::new(json);
478 Decodable::decode(&mut d).unwrap()
480 None => return Err("malformed json".to_string()),
482 // FIXME: this should read from the "plugins" field, but currently
483 // Json doesn't implement decodable...
484 let plugin_output = Vec::new();
485 Ok(Output { krate: krate, json_plugins: plugin_output, passes: Vec::new(), })
488 Err("malformed json input: expected an object at the \
494 /// Outputs the crate/plugin json as a giant json blob at the specified
496 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
497 dst: Path) -> old_io::IoResult<()> {
499 // "schema": version,
500 // "crate": { parsed crate ... },
501 // "plugins": { output of plugins ... }
503 let mut json = std::collections::BTreeMap::new();
504 json.insert("schema".to_string(), Json::String(SCHEMA_VERSION.to_string()));
505 let plugins_json = res.into_iter()
509 Some((string, json)) => {
510 Some((string.to_string(), json))
515 // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
516 // straight to the Rust JSON representation.
517 let crate_json_str = format!("{}", json::as_json(&krate));
518 let crate_json = match json::from_str(&crate_json_str) {
520 Err(e) => panic!("Rust generated JSON is invalid: {:?}", e)
523 json.insert("crate".to_string(), crate_json);
524 json.insert("plugins".to_string(), Json::Object(plugins_json));
526 let mut file = try!(File::create(&dst));
527 write!(&mut file, "{}", Json::Object(json))