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"]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
17 html_root_url = "http://doc.rust-lang.org/nightly/",
18 html_playground_url = "http://play.rust-lang.org/")]
19 #![feature(slicing_syntax)]
25 extern crate rustc_trans;
26 extern crate rustc_driver;
27 extern crate serialize;
29 extern crate "test" as testing;
30 #[macro_use] extern crate log;
32 extern crate "serialize" as rustc_serialize; // used by deriving
34 use std::cell::RefCell;
35 use std::collections::HashMap;
39 use externalfiles::ExternalHtml;
40 use serialize::Decodable;
41 use serialize::json::{self, Json};
42 use rustc::session::search_paths::SearchPaths;
44 // reexported from `clean` so it can be easily updated with the mod itself
45 pub use clean::SCHEMA_VERSION;
48 pub mod externalfiles;
67 pub mod stability_summary;
72 type Pass = (&'static str, // name
73 fn(clean::Crate) -> plugins::PluginResult, // fn
74 &'static str); // description
76 static PASSES: &'static [Pass] = &[
77 ("strip-hidden", passes::strip_hidden,
78 "strips all doc(hidden) items from the output"),
79 ("unindent-comments", passes::unindent_comments,
80 "removes excess indentation on comments in order for markdown to like it"),
81 ("collapse-docs", passes::collapse_docs,
82 "concatenates all document attributes into one document attribute"),
83 ("strip-private", passes::strip_private,
84 "strips all private items from a crate which cannot be seen externally"),
87 static DEFAULT_PASSES: &'static [&'static str] = &[
94 thread_local!(pub static ANALYSISKEY: Rc<RefCell<Option<core::CrateAnalysis>>> = {
95 Rc::new(RefCell::new(None))
100 json_plugins: Vec<plugins::PluginJson>,
105 static STACK_SIZE: uint = 32000000; // 32MB
106 let res = std::thread::Builder::new().stack_size(STACK_SIZE).scoped(move || {
107 main_args(std::os::args().as_slice())
109 std::os::set_exit_status(res.map_err(|_| ()).unwrap());
112 pub fn opts() -> Vec<getopts::OptGroup> {
115 optflag("h", "help", "show this help message"),
116 optflag("V", "version", "print rustdoc's version"),
117 optflag("v", "verbose", "use verbose output"),
118 optopt("r", "input-format", "the input type of the specified file",
120 optopt("w", "output-format", "the output type to write",
122 optopt("o", "output", "where to place the output", "PATH"),
123 optopt("", "crate-name", "specify the name of this crate", "NAME"),
124 optmulti("L", "library-path", "directory to add to crate search path",
126 optmulti("", "cfg", "pass a --cfg to rustc", ""),
127 optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH"),
128 optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
129 optmulti("", "passes", "space separated list of passes to also run, a \
130 value of `list` will print available passes",
132 optmulti("", "plugins", "space separated list of plugins to also load",
134 optflag("", "no-defaults", "don't run the default passes"),
135 optflag("", "test", "run code examples as tests"),
136 optmulti("", "test-args", "arguments to pass to the test runner",
138 optopt("", "target", "target triple to document", "TRIPLE"),
139 optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
141 optmulti("", "html-in-header",
142 "files to include inline in the <head> section of a rendered Markdown file \
143 or generated documentation",
145 optmulti("", "html-before-content",
146 "files to include inline between <body> and the content of a rendered \
147 Markdown file or generated documentation",
149 optmulti("", "html-after-content",
150 "files to include inline between the content and </body> of a rendered \
151 Markdown file or generated documentation",
153 optopt("", "markdown-playground-url",
154 "URL to send code snippets to", "URL"),
155 optflag("", "markdown-no-toc", "don't include table of contents")
159 pub fn usage(argv0: &str) {
161 getopts::usage(format!("{} [options] <input>", argv0).as_slice(),
165 pub fn main_args(args: &[String]) -> int {
166 let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
173 if matches.opt_present("h") || matches.opt_present("help") {
174 usage(args[0].as_slice());
176 } else if matches.opt_present("version") {
177 rustc_driver::version("rustdoc", &matches);
181 if matches.opt_strs("passes") == ["list"] {
182 println!("Available passes for running rustdoc:");
183 for &(name, _, description) in PASSES.iter() {
184 println!("{:>20} - {}", name, description);
186 println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
187 for &name in DEFAULT_PASSES.iter() {
188 println!("{:>20}", name);
193 if matches.free.len() == 0 {
194 println!("expected an input file to act on");
196 } if matches.free.len() > 1 {
197 println!("only one input file may be specified");
200 let input = matches.free[0].as_slice();
202 let mut libs = SearchPaths::new();
203 for s in matches.opt_strs("L").iter() {
204 libs.add_path(s.as_slice());
206 let externs = match parse_externs(&matches) {
214 let test_args = matches.opt_strs("test-args");
215 let test_args: Vec<String> = test_args.iter()
216 .flat_map(|s| s.as_slice().words())
217 .map(|s| s.to_string())
220 let should_test = matches.opt_present("test");
221 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
223 let output = matches.opt_str("o").map(|s| Path::new(s));
224 let cfgs = matches.opt_strs("cfg");
226 let external_html = match ExternalHtml::load(
227 matches.opt_strs("html-in-header").as_slice(),
228 matches.opt_strs("html-before-content").as_slice(),
229 matches.opt_strs("html-after-content").as_slice()) {
233 let crate_name = matches.opt_str("crate-name");
235 match (should_test, markdown_input) {
237 return markdown::test(input, libs, externs, test_args)
240 return test::run(input, cfgs, libs, externs, test_args, crate_name)
242 (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
243 &matches, &external_html,
244 !matches.opt_present("markdown-no-toc")),
248 let out = match acquire_input(input, externs, &matches) {
251 println!("input error: {}", s);
255 let Output { krate, json_plugins, passes, } = out;
256 info!("going to format");
257 match matches.opt_str("w").as_ref().map(|s| s.as_slice()) {
258 Some("html") | None => {
259 match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc")),
260 passes.into_iter().collect()) {
262 Err(e) => panic!("failed to generate documentation: {}", e),
266 match json_output(krate, json_plugins,
267 output.unwrap_or(Path::new("doc.json"))) {
269 Err(e) => panic!("failed to write json: {}", e),
273 println!("unknown output format: {}", s);
281 /// Looks inside the command line arguments to extract the relevant input format
282 /// and files and then generates the necessary rustdoc output for formatting.
283 fn acquire_input(input: &str,
284 externs: core::Externs,
285 matches: &getopts::Matches) -> Result<Output, String> {
286 match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
287 Some("rust") => Ok(rust_input(input, externs, matches)),
288 Some("json") => json_input(input),
289 Some(s) => Err(format!("unknown input format: {}", s)),
291 if input.ends_with(".json") {
294 Ok(rust_input(input, externs, matches))
300 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
301 /// returns a `HashMap` mapping crate names to their paths or else an
303 fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
304 let mut externs = HashMap::new();
305 for arg in matches.opt_strs("extern").iter() {
306 let mut parts = arg.splitn(1, '=');
307 let name = match parts.next() {
310 return Err("--extern value must not be empty".to_string());
313 let location = match parts.next() {
316 return Err("--extern value must be of the format `foo=bar`".to_string());
319 let name = name.to_string();
320 let locs = externs.entry(name).get().unwrap_or_else(
321 |vacant_entry| vacant_entry.insert(Vec::with_capacity(1)));
322 locs.push(location.to_string());
327 /// Interprets the input file as a rust source file, passing it through the
328 /// compiler all the way through the analysis passes. The rustdoc output is then
329 /// generated from the cleaned AST of the crate.
331 /// This form of input will run all of the plug/cleaning passes
332 fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matches) -> Output {
333 let mut default_passes = !matches.opt_present("no-defaults");
334 let mut passes = matches.opt_strs("passes");
335 let mut plugins = matches.opt_strs("plugins");
337 // First, parse the crate and extract all relevant information.
338 let mut paths = SearchPaths::new();
339 for s in matches.opt_strs("L").iter() {
340 paths.add_path(s.as_slice());
342 let cfgs = matches.opt_strs("cfg");
343 let triple = matches.opt_str("target");
345 let cr = Path::new(cratefile);
346 info!("starting to run rustc");
348 let (mut krate, analysis) = std::thread::Thread::scoped(move |:| {
350 core::run_core(paths, cfgs, externs, &cr, triple)
351 }).join().map_err(|_| "rustc failed").unwrap();
352 info!("finished with rustc");
353 let mut analysis = Some(analysis);
354 ANALYSISKEY.with(|s| {
355 *s.borrow_mut() = analysis.take();
358 match matches.opt_str("crate-name") {
359 Some(name) => krate.name = name,
363 // Process all of the crate attributes, extracting plugin metadata along
364 // with the passes which we are supposed to run.
365 match krate.module.as_ref().unwrap().doc_list() {
367 for inner in nested.iter() {
370 if "no_default_passes" == *x => {
371 default_passes = false;
373 clean::NameValue(ref x, ref value)
374 if "passes" == *x => {
375 for pass in value.words() {
376 passes.push(pass.to_string());
379 clean::NameValue(ref x, ref value)
380 if "plugins" == *x => {
381 for p in value.words() {
382 plugins.push(p.to_string());
392 for name in DEFAULT_PASSES.iter().rev() {
393 passes.insert(0, name.to_string());
397 // Load all plugins/passes into a PluginManager
398 let path = matches.opt_str("plugin-path")
399 .unwrap_or("/tmp/rustdoc/plugins".to_string());
400 let mut pm = plugins::PluginManager::new(Path::new(path));
401 for pass in passes.iter() {
402 let plugin = match PASSES.iter()
403 .position(|&(p, _, _)| {
406 Some(i) => PASSES[i].1,
408 error!("unknown pass {}, skipping", *pass);
412 pm.add_plugin(plugin);
414 info!("loading plugins...");
415 for pname in plugins.into_iter() {
416 pm.load_plugin(pname);
420 info!("Executing passes/plugins");
421 let (krate, json) = pm.run_plugins(krate);
422 return Output { krate: krate, json_plugins: json, passes: passes, };
425 /// This input format purely deserializes the json output file. No passes are
426 /// run over the deserialized output.
427 fn json_input(input: &str) -> Result<Output, String> {
428 let mut input = match File::open(&Path::new(input)) {
431 return Err(format!("couldn't open {}: {}", input, e))
434 match json::from_reader(&mut input) {
435 Err(s) => Err(format!("{:?}", s)),
436 Ok(Json::Object(obj)) => {
438 // Make sure the schema is what we expect
439 match obj.remove(&"schema".to_string()) {
440 Some(Json::String(version)) => {
441 if version != SCHEMA_VERSION {
443 "sorry, but I only understand version {}",
447 Some(..) => return Err("malformed json".to_string()),
448 None => return Err("expected a schema version".to_string()),
450 let krate = match obj.remove(&"crate".to_string()) {
452 let mut d = json::Decoder::new(json);
453 Decodable::decode(&mut d).unwrap()
455 None => return Err("malformed json".to_string()),
457 // FIXME: this should read from the "plugins" field, but currently
458 // Json doesn't implement decodable...
459 let plugin_output = Vec::new();
460 Ok(Output { krate: krate, json_plugins: plugin_output, passes: Vec::new(), })
463 Err("malformed json input: expected an object at the \
469 /// Outputs the crate/plugin json as a giant json blob at the specified
471 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
472 dst: Path) -> io::IoResult<()> {
474 // "schema": version,
475 // "crate": { parsed crate ... },
476 // "plugins": { output of plugins ... }
478 let mut json = std::collections::BTreeMap::new();
479 json.insert("schema".to_string(), Json::String(SCHEMA_VERSION.to_string()));
480 let plugins_json = res.into_iter()
484 Some((string, json)) => {
485 Some((string.to_string(), json))
490 // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
491 // straight to the Rust JSON representation.
492 let crate_json_str = format!("{}", json::as_json(&krate));
493 let crate_json = match json::from_str(crate_json_str.as_slice()) {
495 Err(e) => panic!("Rust generated JSON is invalid: {:?}", e)
498 json.insert("crate".to_string(), crate_json);
499 json.insert("plugins".to_string(), Json::Object(plugins_json));
501 let mut file = try!(File::create(&dst));
502 write!(&mut file, "{}", Json::Object(json))