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)]
32 #![feature(rustc_private)]
33 #![feature(staged_api)]
37 #![feature(str_words)]
43 extern crate rustc_trans;
44 extern crate rustc_driver;
45 extern crate rustc_resolve;
46 extern crate serialize;
48 extern crate "test" as testing;
49 #[macro_use] extern crate log;
51 extern crate "serialize" as rustc_serialize; // used by deriving
53 use std::cell::RefCell;
54 use std::collections::HashMap;
56 use std::old_io::File;
59 use std::sync::mpsc::channel;
60 use externalfiles::ExternalHtml;
61 use serialize::Decodable;
62 use serialize::json::{self, Json};
63 use rustc::session::search_paths::SearchPaths;
65 // reexported from `clean` so it can be easily updated with the mod itself
66 pub use clean::SCHEMA_VERSION;
69 pub mod externalfiles;
88 pub mod stability_summary;
93 type Pass = (&'static str, // name
94 fn(clean::Crate) -> plugins::PluginResult, // fn
95 &'static str); // description
97 static PASSES: &'static [Pass] = &[
98 ("strip-hidden", passes::strip_hidden,
99 "strips all doc(hidden) items from the output"),
100 ("unindent-comments", passes::unindent_comments,
101 "removes excess indentation on comments in order for markdown to like it"),
102 ("collapse-docs", passes::collapse_docs,
103 "concatenates all document attributes into one document attribute"),
104 ("strip-private", passes::strip_private,
105 "strips all private items from a crate which cannot be seen externally"),
108 static DEFAULT_PASSES: &'static [&'static str] = &[
115 thread_local!(pub static ANALYSISKEY: Rc<RefCell<Option<core::CrateAnalysis>>> = {
116 Rc::new(RefCell::new(None))
121 json_plugins: Vec<plugins::PluginJson>,
126 const STACK_SIZE: usize = 32000000; // 32MB
127 let res = std::thread::Builder::new().stack_size(STACK_SIZE).scoped(move || {
128 let s = env::args().collect::<Vec<_>>();
131 env::set_exit_status(res as i32);
134 pub fn opts() -> Vec<getopts::OptGroup> {
137 optflag("h", "help", "show this help message"),
138 optflag("V", "version", "print rustdoc's version"),
139 optflag("v", "verbose", "use verbose output"),
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),
187 pub fn main_args(args: &[String]) -> int {
188 let matches = match getopts::getopts(args.tail(), &opts()) {
195 if matches.opt_present("h") || matches.opt_present("help") {
198 } else if matches.opt_present("version") {
199 rustc_driver::version("rustdoc", &matches);
203 if matches.opt_strs("passes") == ["list"] {
204 println!("Available passes for running rustdoc:");
205 for &(name, _, description) in PASSES {
206 println!("{:>20} - {}", name, description);
208 println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
209 for &name in DEFAULT_PASSES {
210 println!("{:>20}", name);
215 if matches.free.len() == 0 {
216 println!("expected an input file to act on");
218 } if matches.free.len() > 1 {
219 println!("only one input file may be specified");
222 let input = &matches.free[0];
224 let mut libs = SearchPaths::new();
225 for s in &matches.opt_strs("L") {
228 let externs = match parse_externs(&matches) {
236 let test_args = matches.opt_strs("test-args");
237 let test_args: Vec<String> = test_args.iter()
238 .flat_map(|s| s.words())
239 .map(|s| s.to_string())
242 let should_test = matches.opt_present("test");
243 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
245 let output = matches.opt_str("o").map(|s| Path::new(s));
246 let cfgs = matches.opt_strs("cfg");
248 let external_html = match ExternalHtml::load(
249 &matches.opt_strs("html-in-header"),
250 &matches.opt_strs("html-before-content"),
251 &matches.opt_strs("html-after-content")) {
255 let crate_name = matches.opt_str("crate-name");
257 match (should_test, markdown_input) {
259 return markdown::test(input, libs, externs, test_args)
262 return test::run(input, cfgs, libs, externs, test_args, crate_name)
264 (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
265 &matches, &external_html,
266 !matches.opt_present("markdown-no-toc")),
270 let out = match acquire_input(input, externs, &matches) {
273 println!("input error: {}", s);
277 let Output { krate, json_plugins, passes, } = out;
278 info!("going to format");
279 match matches.opt_str("w").as_ref().map(|s| &**s) {
280 Some("html") | None => {
281 match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc")),
282 passes.into_iter().collect()) {
284 Err(e) => panic!("failed to generate documentation: {}", e),
288 match json_output(krate, json_plugins,
289 output.unwrap_or(Path::new("doc.json"))) {
291 Err(e) => panic!("failed to write json: {}", e),
295 println!("unknown output format: {}", s);
303 /// Looks inside the command line arguments to extract the relevant input format
304 /// and files and then generates the necessary rustdoc output for formatting.
305 fn acquire_input(input: &str,
306 externs: core::Externs,
307 matches: &getopts::Matches) -> Result<Output, String> {
308 match matches.opt_str("r").as_ref().map(|s| &**s) {
309 Some("rust") => Ok(rust_input(input, externs, matches)),
310 Some("json") => json_input(input),
311 Some(s) => Err(format!("unknown input format: {}", s)),
313 if input.ends_with(".json") {
316 Ok(rust_input(input, externs, matches))
322 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
323 /// returns a `HashMap` mapping crate names to their paths or else an
325 fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
326 let mut externs = HashMap::new();
327 for arg in &matches.opt_strs("extern") {
328 let mut parts = arg.splitn(1, '=');
329 let name = match parts.next() {
332 return Err("--extern value must not be empty".to_string());
335 let location = match parts.next() {
338 return Err("--extern value must be of the format `foo=bar`".to_string());
341 let name = name.to_string();
342 let locs = externs.entry(name).get().unwrap_or_else(
343 |vacant_entry| vacant_entry.insert(Vec::with_capacity(1)));
344 locs.push(location.to_string());
349 /// Interprets the input file as a rust source file, passing it through the
350 /// compiler all the way through the analysis passes. The rustdoc output is then
351 /// generated from the cleaned AST of the crate.
353 /// This form of input will run all of the plug/cleaning passes
354 fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matches) -> Output {
355 let mut default_passes = !matches.opt_present("no-defaults");
356 let mut passes = matches.opt_strs("passes");
357 let mut plugins = matches.opt_strs("plugins");
359 // First, parse the crate and extract all relevant information.
360 let mut paths = SearchPaths::new();
361 for s in &matches.opt_strs("L") {
364 let cfgs = matches.opt_strs("cfg");
365 let triple = matches.opt_str("target");
367 let cr = Path::new(cratefile);
368 info!("starting to run rustc");
370 let (tx, rx) = channel();
371 std::thread::spawn(move || {
372 use rustc::session::config::Input;
375 tx.send(core::run_core(paths, cfgs, externs, Input::File(cr), triple)).unwrap();
376 }).join().map_err(|_| "rustc failed").unwrap();
377 let (mut krate, analysis) = rx.recv().unwrap();
378 info!("finished with rustc");
379 let mut analysis = Some(analysis);
380 ANALYSISKEY.with(|s| {
381 *s.borrow_mut() = analysis.take();
384 match matches.opt_str("crate-name") {
385 Some(name) => krate.name = name,
389 // Process all of the crate attributes, extracting plugin metadata along
390 // with the passes which we are supposed to run.
391 match krate.module.as_ref().unwrap().doc_list() {
393 for inner in nested {
396 if "no_default_passes" == *x => {
397 default_passes = false;
399 clean::NameValue(ref x, ref value)
400 if "passes" == *x => {
401 for pass in value.words() {
402 passes.push(pass.to_string());
405 clean::NameValue(ref x, ref value)
406 if "plugins" == *x => {
407 for p in value.words() {
408 plugins.push(p.to_string());
418 for name in DEFAULT_PASSES.iter().rev() {
419 passes.insert(0, name.to_string());
423 // Load all plugins/passes into a PluginManager
424 let path = matches.opt_str("plugin-path")
425 .unwrap_or("/tmp/rustdoc/plugins".to_string());
426 let mut pm = plugins::PluginManager::new(Path::new(path));
427 for pass in &passes {
428 let plugin = match PASSES.iter()
429 .position(|&(p, _, _)| {
432 Some(i) => PASSES[i].1,
434 error!("unknown pass {}, skipping", *pass);
438 pm.add_plugin(plugin);
440 info!("loading plugins...");
441 for pname in plugins {
442 pm.load_plugin(pname);
446 info!("Executing passes/plugins");
447 let (krate, json) = pm.run_plugins(krate);
448 return Output { krate: krate, json_plugins: json, passes: passes, };
451 /// This input format purely deserializes the json output file. No passes are
452 /// run over the deserialized output.
453 fn json_input(input: &str) -> Result<Output, String> {
454 let mut input = match File::open(&Path::new(input)) {
457 return Err(format!("couldn't open {}: {}", input, e))
460 match json::from_reader(&mut input) {
461 Err(s) => Err(format!("{:?}", s)),
462 Ok(Json::Object(obj)) => {
464 // Make sure the schema is what we expect
465 match obj.remove(&"schema".to_string()) {
466 Some(Json::String(version)) => {
467 if version != SCHEMA_VERSION {
469 "sorry, but I only understand version {}",
473 Some(..) => return Err("malformed json".to_string()),
474 None => return Err("expected a schema version".to_string()),
476 let krate = match obj.remove(&"crate".to_string()) {
478 let mut d = json::Decoder::new(json);
479 Decodable::decode(&mut d).unwrap()
481 None => return Err("malformed json".to_string()),
483 // FIXME: this should read from the "plugins" field, but currently
484 // Json doesn't implement decodable...
485 let plugin_output = Vec::new();
486 Ok(Output { krate: krate, json_plugins: plugin_output, passes: Vec::new(), })
489 Err("malformed json input: expected an object at the \
495 /// Outputs the crate/plugin json as a giant json blob at the specified
497 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
498 dst: Path) -> old_io::IoResult<()> {
500 // "schema": version,
501 // "crate": { parsed crate ... },
502 // "plugins": { output of plugins ... }
504 let mut json = std::collections::BTreeMap::new();
505 json.insert("schema".to_string(), Json::String(SCHEMA_VERSION.to_string()));
506 let plugins_json = res.into_iter()
510 Some((string, json)) => {
511 Some((string.to_string(), json))
516 // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
517 // straight to the Rust JSON representation.
518 let crate_json_str = format!("{}", json::as_json(&krate));
519 let crate_json = match json::from_str(&crate_json_str) {
521 Err(e) => panic!("Rust generated JSON is invalid: {:?}", e)
524 json.insert("crate".to_string(), crate_json);
525 json.insert("plugins".to_string(), Json::Object(plugins_json));
527 let mut file = try!(File::create(&dst));
528 write!(&mut file, "{}", Json::Object(json))