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", issue = "27812")]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
17 html_root_url = "https://doc.rust-lang.org/nightly/",
18 html_playground_url = "https://play.rust-lang.org/")]
20 #![feature(box_patterns)]
21 #![feature(box_syntax)]
22 #![feature(dynamic_lib)]
24 #![feature(rustc_private)]
25 #![feature(set_stdio)]
26 #![feature(slice_patterns)]
27 #![feature(staged_api)]
35 extern crate rustc_trans;
36 extern crate rustc_driver;
37 extern crate rustc_resolve;
38 extern crate rustc_lint;
39 extern crate rustc_back;
40 extern crate rustc_front;
41 extern crate rustc_metadata;
42 extern crate serialize;
44 extern crate test as testing;
45 extern crate rustc_unicode;
46 #[macro_use] extern crate log;
48 extern crate serialize as rustc_serialize; // used by deriving
50 use std::cell::RefCell;
51 use std::collections::HashMap;
52 use std::default::Default;
55 use std::io::{self, Read, Write};
56 use std::path::PathBuf;
59 use std::sync::mpsc::channel;
61 use externalfiles::ExternalHtml;
62 use serialize::Decodable;
63 use serialize::json::{self, Json};
64 use rustc::session::search_paths::SearchPaths;
65 use rustc::session::config::ErrorOutputType;
67 // reexported from `clean` so it can be easily updated with the mod itself
68 pub use clean::SCHEMA_VERSION;
71 pub mod externalfiles;
94 type Pass = (&'static str, // name
95 fn(clean::Crate) -> plugins::PluginResult, // fn
96 &'static str); // description
98 const PASSES: &'static [Pass] = &[
99 ("strip-hidden", passes::strip_hidden,
100 "strips all doc(hidden) items from the output"),
101 ("unindent-comments", passes::unindent_comments,
102 "removes excess indentation on comments in order for markdown to like it"),
103 ("collapse-docs", passes::collapse_docs,
104 "concatenates all document attributes into one document attribute"),
105 ("strip-private", passes::strip_private,
106 "strips all private items from a crate which cannot be seen externally"),
109 const DEFAULT_PASSES: &'static [&'static str] = &[
116 thread_local!(pub static ANALYSISKEY: Rc<RefCell<Option<core::CrateAnalysis>>> = {
117 Rc::new(RefCell::new(None))
122 json_plugins: Vec<plugins::PluginJson>,
127 const STACK_SIZE: usize = 32000000; // 32MB
128 let res = std::thread::Builder::new().stack_size(STACK_SIZE).spawn(move || {
129 let s = env::args().collect::<Vec<_>>();
131 }).unwrap().join().unwrap_or(101);
132 process::exit(res as i32);
135 pub fn opts() -> Vec<getopts::OptGroup> {
138 optflag("h", "help", "show this help message"),
139 optflag("V", "version", "print rustdoc's version"),
140 optflag("v", "verbose", "use verbose output"),
141 optopt("r", "input-format", "the input type of the specified file",
143 optopt("w", "output-format", "the output type to write",
145 optopt("o", "output", "where to place the output", "PATH"),
146 optopt("", "crate-name", "specify the name of this crate", "NAME"),
147 optmulti("L", "library-path", "directory to add to crate search path",
149 optmulti("", "cfg", "pass a --cfg to rustc", ""),
150 optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH"),
151 optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
152 optmulti("", "passes", "list of passes to also run, you might want \
153 to pass it multiple times; a value of `list` \
154 will print available passes",
156 optmulti("", "plugins", "space separated list of plugins to also load",
158 optflag("", "no-defaults", "don't run the default passes"),
159 optflag("", "test", "run code examples as tests"),
160 optmulti("", "test-args", "arguments to pass to the test runner",
162 optopt("", "target", "target triple to document", "TRIPLE"),
163 optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
165 optmulti("", "html-in-header",
166 "files to include inline in the <head> section of a rendered Markdown file \
167 or generated documentation",
169 optmulti("", "html-before-content",
170 "files to include inline between <body> and the content of a rendered \
171 Markdown file or generated documentation",
173 optmulti("", "html-after-content",
174 "files to include inline between the content and </body> of a rendered \
175 Markdown file or generated documentation",
177 optopt("", "markdown-playground-url",
178 "URL to send code snippets to", "URL"),
179 optflag("", "markdown-no-toc", "don't include table of contents")
183 pub fn usage(argv0: &str) {
185 getopts::usage(&format!("{} [options] <input>", argv0),
189 pub fn main_args(args: &[String]) -> isize {
190 let matches = match getopts::getopts(&args[1..], &opts()) {
197 if matches.opt_present("h") || matches.opt_present("help") {
200 } else if matches.opt_present("version") {
201 rustc_driver::version("rustdoc", &matches);
205 if matches.opt_strs("passes") == ["list"] {
206 println!("Available passes for running rustdoc:");
207 for &(name, _, description) in PASSES {
208 println!("{:>20} - {}", name, description);
210 println!("\nDefault passes for rustdoc:");
211 for &name in DEFAULT_PASSES {
212 println!("{:>20}", name);
217 if matches.free.is_empty() {
218 println!("expected an input file to act on");
220 } if matches.free.len() > 1 {
221 println!("only one input file may be specified");
224 let input = &matches.free[0];
226 let mut libs = SearchPaths::new();
227 for s in &matches.opt_strs("L") {
228 libs.add_path(s, ErrorOutputType::default());
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.split_whitespace())
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| PathBuf::from(&s));
248 let cfgs = matches.opt_strs("cfg");
250 let external_html = match ExternalHtml::load(
251 &matches.opt_strs("html-in-header"),
252 &matches.opt_strs("html-before-content"),
253 &matches.opt_strs("html-after-content")) {
257 let crate_name = matches.opt_str("crate-name");
259 match (should_test, markdown_input) {
261 return markdown::test(input, cfgs, libs, externs, test_args)
264 return test::run(input, cfgs, libs, externs, test_args, crate_name)
266 (false, true) => return markdown::render(input,
267 output.unwrap_or(PathBuf::from("doc")),
268 &matches, &external_html,
269 !matches.opt_present("markdown-no-toc")),
272 let out = match acquire_input(input, externs, &matches) {
275 println!("input error: {}", s);
279 let Output { krate, json_plugins, passes, } = out;
280 info!("going to format");
281 match matches.opt_str("w").as_ref().map(|s| &**s) {
282 Some("html") | None => {
283 match html::render::run(krate, &external_html,
284 output.unwrap_or(PathBuf::from("doc")),
285 passes.into_iter().collect()) {
287 Err(e) => panic!("failed to generate documentation: {}", e),
291 match json_output(krate, json_plugins,
292 output.unwrap_or(PathBuf::from("doc.json"))) {
294 Err(e) => panic!("failed to write json: {}", e),
298 println!("unknown output format: {}", s);
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) {
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") {
331 let mut parts = arg.splitn(2, '=');
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 name = name.to_string();
345 externs.entry(name).or_insert(vec![]).push(location.to_string());
350 /// Interprets the input file as a rust source file, passing it through the
351 /// compiler all the way through the analysis passes. The rustdoc output is then
352 /// generated from the cleaned AST of the crate.
354 /// This form of input will run all of the plug/cleaning passes
355 fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matches) -> Output {
356 let mut default_passes = !matches.opt_present("no-defaults");
357 let mut passes = matches.opt_strs("passes");
358 let mut plugins = matches.opt_strs("plugins");
360 // First, parse the crate and extract all relevant information.
361 let mut paths = SearchPaths::new();
362 for s in &matches.opt_strs("L") {
363 paths.add_path(s, ErrorOutputType::default());
365 let cfgs = matches.opt_strs("cfg");
366 let triple = matches.opt_str("target");
368 let cr = PathBuf::from(cratefile);
369 info!("starting to run rustc");
371 let (tx, rx) = channel();
372 rustc_driver::monitor(move || {
373 use rustc::session::config::Input;
375 tx.send(core::run_core(paths, cfgs, externs, Input::File(cr),
378 let (mut krate, analysis) = rx.recv().unwrap();
379 info!("finished with rustc");
380 let mut analysis = Some(analysis);
381 ANALYSISKEY.with(|s| {
382 *s.borrow_mut() = analysis.take();
385 match matches.opt_str("crate-name") {
386 Some(name) => krate.name = name,
390 // Process all of the crate attributes, extracting plugin metadata along
391 // with the passes which we are supposed to run.
392 match krate.module.as_ref().unwrap().doc_list() {
394 for inner in nested {
397 if "no_default_passes" == *x => {
398 default_passes = false;
400 clean::NameValue(ref x, ref value)
401 if "passes" == *x => {
402 for pass in value.split_whitespace() {
403 passes.push(pass.to_string());
406 clean::NameValue(ref x, ref value)
407 if "plugins" == *x => {
408 for p in value.split_whitespace() {
409 plugins.push(p.to_string());
419 for name in DEFAULT_PASSES.iter().rev() {
420 passes.insert(0, name.to_string());
424 // Load all plugins/passes into a PluginManager
425 let path = matches.opt_str("plugin-path")
426 .unwrap_or("/tmp/rustdoc/plugins".to_string());
427 let mut pm = plugins::PluginManager::new(PathBuf::from(path));
428 for pass in &passes {
429 let plugin = match PASSES.iter()
430 .position(|&(p, _, _)| {
433 Some(i) => PASSES[i].1,
435 error!("unknown pass {}, skipping", *pass);
439 pm.add_plugin(plugin);
441 info!("loading plugins...");
442 for pname in plugins {
443 pm.load_plugin(pname);
447 info!("Executing passes/plugins");
448 let (krate, json) = pm.run_plugins(krate);
449 return Output { krate: krate, json_plugins: json, passes: passes, };
452 /// This input format purely deserializes the json output file. No passes are
453 /// run over the deserialized output.
454 fn json_input(input: &str) -> Result<Output, String> {
455 let mut bytes = Vec::new();
456 match File::open(input).and_then(|mut f| f.read_to_end(&mut bytes)) {
458 Err(e) => return Err(format!("couldn't open {}: {}", input, e)),
460 match json::from_reader(&mut &bytes[..]) {
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: PathBuf) -> io::Result<()> {
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))