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"]
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/")]
20 #![feature(slicing_syntax)]
21 #![feature(box_syntax)]
22 #![allow(unknown_features)] #![feature(int_uint)]
28 extern crate rustc_trans;
29 extern crate rustc_driver;
30 extern crate rustc_resolve;
31 extern crate serialize;
33 extern crate "test" as testing;
34 #[macro_use] extern crate log;
36 extern crate "serialize" as rustc_serialize; // used by deriving
38 use std::cell::RefCell;
39 use std::collections::HashMap;
43 use externalfiles::ExternalHtml;
44 use serialize::Decodable;
45 use serialize::json::{self, Json};
46 use rustc::session::search_paths::SearchPaths;
48 // reexported from `clean` so it can be easily updated with the mod itself
49 pub use clean::SCHEMA_VERSION;
52 pub mod externalfiles;
71 pub mod stability_summary;
76 type Pass = (&'static str, // name
77 fn(clean::Crate) -> plugins::PluginResult, // fn
78 &'static str); // description
80 static PASSES: &'static [Pass] = &[
81 ("strip-hidden", passes::strip_hidden,
82 "strips all doc(hidden) items from the output"),
83 ("unindent-comments", passes::unindent_comments,
84 "removes excess indentation on comments in order for markdown to like it"),
85 ("collapse-docs", passes::collapse_docs,
86 "concatenates all document attributes into one document attribute"),
87 ("strip-private", passes::strip_private,
88 "strips all private items from a crate which cannot be seen externally"),
91 static DEFAULT_PASSES: &'static [&'static str] = &[
98 thread_local!(pub static ANALYSISKEY: Rc<RefCell<Option<core::CrateAnalysis>>> = {
99 Rc::new(RefCell::new(None))
104 json_plugins: Vec<plugins::PluginJson>,
109 static STACK_SIZE: uint = 32000000; // 32MB
110 let res = std::thread::Builder::new().stack_size(STACK_SIZE).scoped(move || {
111 main_args(std::os::args().as_slice())
113 std::os::set_exit_status(res.map_err(|_| ()).unwrap());
116 pub fn opts() -> Vec<getopts::OptGroup> {
119 optflag("h", "help", "show this help message"),
120 optflag("V", "version", "print rustdoc's version"),
121 optflag("v", "verbose", "use verbose output"),
122 optopt("r", "input-format", "the input type of the specified file",
124 optopt("w", "output-format", "the output type to write",
126 optopt("o", "output", "where to place the output", "PATH"),
127 optopt("", "crate-name", "specify the name of this crate", "NAME"),
128 optmulti("L", "library-path", "directory to add to crate search path",
130 optmulti("", "cfg", "pass a --cfg to rustc", ""),
131 optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH"),
132 optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
133 optmulti("", "passes", "space separated list of passes to also run, a \
134 value of `list` will print available passes",
136 optmulti("", "plugins", "space separated list of plugins to also load",
138 optflag("", "no-defaults", "don't run the default passes"),
139 optflag("", "test", "run code examples as tests"),
140 optmulti("", "test-args", "arguments to pass to the test runner",
142 optopt("", "target", "target triple to document", "TRIPLE"),
143 optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
145 optmulti("", "html-in-header",
146 "files to include inline in the <head> section of a rendered Markdown file \
147 or generated documentation",
149 optmulti("", "html-before-content",
150 "files to include inline between <body> and the content of a rendered \
151 Markdown file or generated documentation",
153 optmulti("", "html-after-content",
154 "files to include inline between the content and </body> of a rendered \
155 Markdown file or generated documentation",
157 optopt("", "markdown-playground-url",
158 "URL to send code snippets to", "URL"),
159 optflag("", "markdown-no-toc", "don't include table of contents")
163 pub fn usage(argv0: &str) {
165 getopts::usage(format!("{} [options] <input>", argv0).as_slice(),
169 pub fn main_args(args: &[String]) -> int {
170 let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
177 if matches.opt_present("h") || matches.opt_present("help") {
178 usage(args[0].as_slice());
180 } else if matches.opt_present("version") {
181 rustc_driver::version("rustdoc", &matches);
185 if matches.opt_strs("passes") == ["list"] {
186 println!("Available passes for running rustdoc:");
187 for &(name, _, description) in PASSES.iter() {
188 println!("{:>20} - {}", name, description);
190 println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
191 for &name in DEFAULT_PASSES.iter() {
192 println!("{:>20}", name);
197 if matches.free.len() == 0 {
198 println!("expected an input file to act on");
200 } if matches.free.len() > 1 {
201 println!("only one input file may be specified");
204 let input = matches.free[0].as_slice();
206 let mut libs = SearchPaths::new();
207 for s in matches.opt_strs("L").iter() {
208 libs.add_path(s.as_slice());
210 let externs = match parse_externs(&matches) {
218 let test_args = matches.opt_strs("test-args");
219 let test_args: Vec<String> = test_args.iter()
220 .flat_map(|s| s.as_slice().words())
221 .map(|s| s.to_string())
224 let should_test = matches.opt_present("test");
225 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
227 let output = matches.opt_str("o").map(|s| Path::new(s));
228 let cfgs = matches.opt_strs("cfg");
230 let external_html = match ExternalHtml::load(
231 matches.opt_strs("html-in-header").as_slice(),
232 matches.opt_strs("html-before-content").as_slice(),
233 matches.opt_strs("html-after-content").as_slice()) {
237 let crate_name = matches.opt_str("crate-name");
239 match (should_test, markdown_input) {
241 return markdown::test(input, libs, externs, test_args)
244 return test::run(input, cfgs, libs, externs, test_args, crate_name)
246 (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
247 &matches, &external_html,
248 !matches.opt_present("markdown-no-toc")),
252 let out = match acquire_input(input, externs, &matches) {
255 println!("input error: {}", s);
259 let Output { krate, json_plugins, passes, } = out;
260 info!("going to format");
261 match matches.opt_str("w").as_ref().map(|s| s.as_slice()) {
262 Some("html") | None => {
263 match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc")),
264 passes.into_iter().collect()) {
266 Err(e) => panic!("failed to generate documentation: {}", e),
270 match json_output(krate, json_plugins,
271 output.unwrap_or(Path::new("doc.json"))) {
273 Err(e) => panic!("failed to write json: {}", e),
277 println!("unknown output format: {}", s);
285 /// Looks inside the command line arguments to extract the relevant input format
286 /// and files and then generates the necessary rustdoc output for formatting.
287 fn acquire_input(input: &str,
288 externs: core::Externs,
289 matches: &getopts::Matches) -> Result<Output, String> {
290 match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
291 Some("rust") => Ok(rust_input(input, externs, matches)),
292 Some("json") => json_input(input),
293 Some(s) => Err(format!("unknown input format: {}", s)),
295 if input.ends_with(".json") {
298 Ok(rust_input(input, externs, matches))
304 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
305 /// returns a `HashMap` mapping crate names to their paths or else an
307 fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
308 let mut externs = HashMap::new();
309 for arg in matches.opt_strs("extern").iter() {
310 let mut parts = arg.splitn(1, '=');
311 let name = match parts.next() {
314 return Err("--extern value must not be empty".to_string());
317 let location = match parts.next() {
320 return Err("--extern value must be of the format `foo=bar`".to_string());
323 let name = name.to_string();
324 let locs = externs.entry(name).get().unwrap_or_else(
325 |vacant_entry| vacant_entry.insert(Vec::with_capacity(1)));
326 locs.push(location.to_string());
331 /// Interprets the input file as a rust source file, passing it through the
332 /// compiler all the way through the analysis passes. The rustdoc output is then
333 /// generated from the cleaned AST of the crate.
335 /// This form of input will run all of the plug/cleaning passes
336 fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matches) -> Output {
337 let mut default_passes = !matches.opt_present("no-defaults");
338 let mut passes = matches.opt_strs("passes");
339 let mut plugins = matches.opt_strs("plugins");
341 // First, parse the crate and extract all relevant information.
342 let mut paths = SearchPaths::new();
343 for s in matches.opt_strs("L").iter() {
344 paths.add_path(s.as_slice());
346 let cfgs = matches.opt_strs("cfg");
347 let triple = matches.opt_str("target");
349 let cr = Path::new(cratefile);
350 info!("starting to run rustc");
352 let (mut krate, analysis) = std::thread::Thread::scoped(move |:| {
353 use rustc::session::config::Input;
356 core::run_core(paths, cfgs, externs, Input::File(cr), triple)
357 }).join().map_err(|_| "rustc failed").unwrap();
358 info!("finished with rustc");
359 let mut analysis = Some(analysis);
360 ANALYSISKEY.with(|s| {
361 *s.borrow_mut() = analysis.take();
364 match matches.opt_str("crate-name") {
365 Some(name) => krate.name = name,
369 // Process all of the crate attributes, extracting plugin metadata along
370 // with the passes which we are supposed to run.
371 match krate.module.as_ref().unwrap().doc_list() {
373 for inner in nested.iter() {
376 if "no_default_passes" == *x => {
377 default_passes = false;
379 clean::NameValue(ref x, ref value)
380 if "passes" == *x => {
381 for pass in value.words() {
382 passes.push(pass.to_string());
385 clean::NameValue(ref x, ref value)
386 if "plugins" == *x => {
387 for p in value.words() {
388 plugins.push(p.to_string());
398 for name in DEFAULT_PASSES.iter().rev() {
399 passes.insert(0, name.to_string());
403 // Load all plugins/passes into a PluginManager
404 let path = matches.opt_str("plugin-path")
405 .unwrap_or("/tmp/rustdoc/plugins".to_string());
406 let mut pm = plugins::PluginManager::new(Path::new(path));
407 for pass in passes.iter() {
408 let plugin = match PASSES.iter()
409 .position(|&(p, _, _)| {
412 Some(i) => PASSES[i].1,
414 error!("unknown pass {}, skipping", *pass);
418 pm.add_plugin(plugin);
420 info!("loading plugins...");
421 for pname in plugins.into_iter() {
422 pm.load_plugin(pname);
426 info!("Executing passes/plugins");
427 let (krate, json) = pm.run_plugins(krate);
428 return Output { krate: krate, json_plugins: json, passes: passes, };
431 /// This input format purely deserializes the json output file. No passes are
432 /// run over the deserialized output.
433 fn json_input(input: &str) -> Result<Output, String> {
434 let mut input = match File::open(&Path::new(input)) {
437 return Err(format!("couldn't open {}: {}", input, e))
440 match json::from_reader(&mut input) {
441 Err(s) => Err(format!("{:?}", s)),
442 Ok(Json::Object(obj)) => {
444 // Make sure the schema is what we expect
445 match obj.remove(&"schema".to_string()) {
446 Some(Json::String(version)) => {
447 if version != SCHEMA_VERSION {
449 "sorry, but I only understand version {}",
453 Some(..) => return Err("malformed json".to_string()),
454 None => return Err("expected a schema version".to_string()),
456 let krate = match obj.remove(&"crate".to_string()) {
458 let mut d = json::Decoder::new(json);
459 Decodable::decode(&mut d).unwrap()
461 None => return Err("malformed json".to_string()),
463 // FIXME: this should read from the "plugins" field, but currently
464 // Json doesn't implement decodable...
465 let plugin_output = Vec::new();
466 Ok(Output { krate: krate, json_plugins: plugin_output, passes: Vec::new(), })
469 Err("malformed json input: expected an object at the \
475 /// Outputs the crate/plugin json as a giant json blob at the specified
477 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
478 dst: Path) -> io::IoResult<()> {
480 // "schema": version,
481 // "crate": { parsed crate ... },
482 // "plugins": { output of plugins ... }
484 let mut json = std::collections::BTreeMap::new();
485 json.insert("schema".to_string(), Json::String(SCHEMA_VERSION.to_string()));
486 let plugins_json = res.into_iter()
490 Some((string, json)) => {
491 Some((string.to_string(), json))
496 // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
497 // straight to the Rust JSON representation.
498 let crate_json_str = format!("{}", json::as_json(&krate));
499 let crate_json = match json::from_str(crate_json_str.as_slice()) {
501 Err(e) => panic!("Rust generated JSON is invalid: {:?}", e)
504 json.insert("crate".to_string(), crate_json);
505 json.insert("plugins".to_string(), Json::Object(plugins_json));
507 let mut file = try!(File::create(&dst));
508 write!(&mut file, "{}", Json::Object(json))