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 #![desc = "rustdoc, the Rust documentation extractor"]
14 #![license = "MIT/ASL2"]
15 #![crate_type = "dylib"]
16 #![crate_type = "rlib"]
18 #![allow(unknown_features)]
19 #![feature(globs, macro_rules, phase, slicing_syntax, tuple_indexing)]
25 extern crate rustc_trans;
26 extern crate serialize;
28 extern crate "test" as testing;
29 #[phase(plugin, link)] extern crate log;
33 use std::collections::HashMap;
34 use std::collections::hash_map::{Occupied, Vacant};
35 use serialize::{json, Decodable, Encodable};
36 use externalfiles::ExternalHtml;
38 // reexported from `clean` so it can be easily updated with the mod itself
39 pub use clean::SCHEMA_VERSION;
45 pub mod externalfiles;
60 pub mod stability_summary;
65 type Pass = (&'static str, // name
66 fn(clean::Crate) -> plugins::PluginResult, // fn
67 &'static str); // description
69 static PASSES: &'static [Pass] = &[
70 ("strip-hidden", passes::strip_hidden,
71 "strips all doc(hidden) items from the output"),
72 ("unindent-comments", passes::unindent_comments,
73 "removes excess indentation on comments in order for markdown to like it"),
74 ("collapse-docs", passes::collapse_docs,
75 "concatenates all document attributes into one document attribute"),
76 ("strip-private", passes::strip_private,
77 "strips all private items from a crate which cannot be seen externally"),
80 static DEFAULT_PASSES: &'static [&'static str] = &[
87 local_data_key!(pub analysiskey: core::CrateAnalysis)
91 json_plugins: Vec<plugins::PluginJson>,
96 std::os::set_exit_status(main_args(std::os::args().as_slice()));
99 pub fn opts() -> Vec<getopts::OptGroup> {
102 optflag("h", "help", "show this help message"),
103 optflagopt("", "version", "print rustdoc's version", "verbose"),
104 optopt("r", "input-format", "the input type of the specified file",
106 optopt("w", "output-format", "the output type to write",
108 optopt("o", "output", "where to place the output", "PATH"),
109 optopt("", "crate-name", "specify the name of this crate", "NAME"),
110 optmulti("L", "library-path", "directory to add to crate search path",
112 optmulti("", "cfg", "pass a --cfg to rustc", ""),
113 optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH"),
114 optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
115 optmulti("", "passes", "space separated list of passes to also run, a \
116 value of `list` will print available passes",
118 optmulti("", "plugins", "space separated list of plugins to also load",
120 optflag("", "no-defaults", "don't run the default passes"),
121 optflag("", "test", "run code examples as tests"),
122 optmulti("", "test-args", "arguments to pass to the test runner",
124 optopt("", "target", "target triple to document", "TRIPLE"),
125 optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
127 optmulti("", "html-in-header",
128 "files to include inline in the <head> section of a rendered Markdown file \
129 or generated documentation",
131 optmulti("", "html-before-content",
132 "files to include inline between <body> and the content of a rendered \
133 Markdown file or generated documentation",
135 optmulti("", "html-after-content",
136 "files to include inline between the content and </body> of a rendered \
137 Markdown file or generated documentation",
139 optopt("", "markdown-playground-url",
140 "URL to send code snippets to", "URL"),
141 optflag("", "markdown-no-toc", "don't include table of contents")
145 pub fn usage(argv0: &str) {
147 getopts::usage(format!("{} [options] <input>", argv0).as_slice(),
151 pub fn main_args(args: &[String]) -> int {
152 let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
159 if matches.opt_present("h") || matches.opt_present("help") {
160 usage(args[0].as_slice());
162 } else if matches.opt_present("version") {
163 match rustc_trans::driver::version("rustdoc", &matches) {
172 if matches.opt_strs("passes").as_slice() == &["list".to_string()] {
173 println!("Available passes for running rustdoc:");
174 for &(name, _, description) in PASSES.iter() {
175 println!("{:>20} - {}", name, description);
177 println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
178 for &name in DEFAULT_PASSES.iter() {
179 println!("{:>20}", name);
184 if matches.free.len() == 0 {
185 println!("expected an input file to act on");
187 } if matches.free.len() > 1 {
188 println!("only one input file may be specified");
191 let input = matches.free[0].as_slice();
193 let libs = matches.opt_strs("L").iter().map(|s| Path::new(s.as_slice())).collect();
194 let externs = match parse_externs(&matches) {
202 let test_args = matches.opt_strs("test-args");
203 let test_args: Vec<String> = test_args.iter()
204 .flat_map(|s| s.as_slice().words())
205 .map(|s| s.to_string())
208 let should_test = matches.opt_present("test");
209 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
211 let output = matches.opt_str("o").map(|s| Path::new(s));
212 let cfgs = matches.opt_strs("cfg");
214 let external_html = match ExternalHtml::load(
215 matches.opt_strs("html-in-header").as_slice(),
216 matches.opt_strs("html-before-content").as_slice(),
217 matches.opt_strs("html-after-content").as_slice()) {
221 let crate_name = matches.opt_str("crate-name");
223 match (should_test, markdown_input) {
225 return markdown::test(input, libs, externs, test_args)
228 return test::run(input, cfgs, libs, externs, test_args, crate_name)
230 (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
231 &matches, &external_html,
232 !matches.opt_present("markdown-no-toc")),
236 let out = match acquire_input(input, externs, &matches) {
239 println!("input error: {}", s);
243 let Output { krate, json_plugins, passes, } = out;
244 info!("going to format");
245 match matches.opt_str("w").as_ref().map(|s| s.as_slice()) {
246 Some("html") | None => {
247 match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc")),
248 passes.into_iter().collect()) {
250 Err(e) => panic!("failed to generate documentation: {}", e),
254 match json_output(krate, json_plugins,
255 output.unwrap_or(Path::new("doc.json"))) {
257 Err(e) => panic!("failed to write json: {}", e),
261 println!("unknown output format: {}", s);
269 /// Looks inside the command line arguments to extract the relevant input format
270 /// and files and then generates the necessary rustdoc output for formatting.
271 fn acquire_input(input: &str,
272 externs: core::Externs,
273 matches: &getopts::Matches) -> Result<Output, String> {
274 match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
275 Some("rust") => Ok(rust_input(input, externs, matches)),
276 Some("json") => json_input(input),
277 Some(s) => Err(format!("unknown input format: {}", s)),
279 if input.ends_with(".json") {
282 Ok(rust_input(input, externs, matches))
288 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
289 /// returns a `HashMap` mapping crate names to their paths or else an
291 fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
292 let mut externs = HashMap::new();
293 for arg in matches.opt_strs("extern").iter() {
294 let mut parts = arg.as_slice().splitn(1, '=');
295 let name = match parts.next() {
298 return Err("--extern value must not be empty".to_string());
301 let location = match parts.next() {
304 return Err("--extern value must be of the format `foo=bar`".to_string());
307 let locs = match externs.entry(name.to_string()) {
308 Vacant(entry) => entry.set(Vec::with_capacity(1)),
309 Occupied(entry) => entry.into_mut(),
311 locs.push(location.to_string());
316 /// Interprets the input file as a rust source file, passing it through the
317 /// compiler all the way through the analysis passes. The rustdoc output is then
318 /// generated from the cleaned AST of the crate.
320 /// This form of input will run all of the plug/cleaning passes
321 fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matches) -> Output {
322 let mut default_passes = !matches.opt_present("no-defaults");
323 let mut passes = matches.opt_strs("passes");
324 let mut plugins = matches.opt_strs("plugins");
326 // First, parse the crate and extract all relevant information.
327 let libs: Vec<Path> = matches.opt_strs("L")
329 .map(|s| Path::new(s.as_slice()))
331 let cfgs = matches.opt_strs("cfg");
332 let triple = matches.opt_str("target");
334 let cr = Path::new(cratefile);
335 info!("starting to run rustc");
336 let (mut krate, analysis) = std::task::try(proc() {
338 core::run_core(libs, cfgs, externs, &cr, triple)
339 }).map_err(|_| "rustc failed").unwrap();
340 info!("finished with rustc");
341 analysiskey.replace(Some(analysis));
343 match matches.opt_str("crate-name") {
344 Some(name) => krate.name = name,
348 // Process all of the crate attributes, extracting plugin metadata along
349 // with the passes which we are supposed to run.
350 match krate.module.as_ref().unwrap().doc_list() {
352 for inner in nested.iter() {
355 if "no_default_passes" == x.as_slice() => {
356 default_passes = false;
358 clean::NameValue(ref x, ref value)
359 if "passes" == x.as_slice() => {
360 for pass in value.as_slice().words() {
361 passes.push(pass.to_string());
364 clean::NameValue(ref x, ref value)
365 if "plugins" == x.as_slice() => {
366 for p in value.as_slice().words() {
367 plugins.push(p.to_string());
377 for name in DEFAULT_PASSES.iter().rev() {
378 passes.insert(0, name.to_string());
382 // Load all plugins/passes into a PluginManager
383 let path = matches.opt_str("plugin-path")
384 .unwrap_or("/tmp/rustdoc/plugins".to_string());
385 let mut pm = plugins::PluginManager::new(Path::new(path));
386 for pass in passes.iter() {
387 let plugin = match PASSES.iter()
388 .position(|&(p, _, _)| {
391 Some(i) => PASSES[i].val1(),
393 error!("unknown pass {}, skipping", *pass);
397 pm.add_plugin(plugin);
399 info!("loading plugins...");
400 for pname in plugins.into_iter() {
401 pm.load_plugin(pname);
405 info!("Executing passes/plugins");
406 let (krate, json) = pm.run_plugins(krate);
407 return Output { krate: krate, json_plugins: json, passes: passes, };
410 /// This input format purely deserializes the json output file. No passes are
411 /// run over the deserialized output.
412 fn json_input(input: &str) -> Result<Output, String> {
413 let mut input = match File::open(&Path::new(input)) {
416 return Err(format!("couldn't open {}: {}", input, e))
419 match json::from_reader(&mut input) {
420 Err(s) => Err(s.to_string()),
421 Ok(json::Object(obj)) => {
423 // Make sure the schema is what we expect
424 match obj.remove(&"schema".to_string()) {
425 Some(json::String(version)) => {
426 if version.as_slice() != SCHEMA_VERSION {
428 "sorry, but I only understand version {}",
432 Some(..) => return Err("malformed json".to_string()),
433 None => return Err("expected a schema version".to_string()),
435 let krate = match obj.remove(&"crate".to_string()) {
437 let mut d = json::Decoder::new(json);
438 Decodable::decode(&mut d).unwrap()
440 None => return Err("malformed json".to_string()),
442 // FIXME: this should read from the "plugins" field, but currently
443 // Json doesn't implement decodable...
444 let plugin_output = Vec::new();
445 Ok(Output { krate: krate, json_plugins: plugin_output, passes: Vec::new(), })
448 Err("malformed json input: expected an object at the \
454 /// Outputs the crate/plugin json as a giant json blob at the specified
456 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
457 dst: Path) -> io::IoResult<()> {
459 // "schema": version,
460 // "crate": { parsed crate ... },
461 // "plugins": { output of plugins ... }
463 let mut json = std::collections::TreeMap::new();
464 json.insert("schema".to_string(), json::String(SCHEMA_VERSION.to_string()));
465 let plugins_json = res.into_iter()
469 Some((string, json)) => {
470 Some((string.to_string(), json))
475 // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
476 // straight to the Rust JSON representation.
477 let crate_json_str = {
478 let mut w = Vec::new();
480 let mut encoder = json::Encoder::new(&mut w as &mut io::Writer);
481 krate.encode(&mut encoder).unwrap();
483 String::from_utf8(w).unwrap()
485 let crate_json = match json::from_str(crate_json_str.as_slice()) {
487 Err(e) => panic!("Rust generated JSON is invalid: {}", e)
490 json.insert("crate".to_string(), crate_json);
491 json.insert("plugins".to_string(), json::Object(plugins_json));
493 let mut file = try!(File::create(&dst));
494 json::Object(json).to_writer(&mut file)