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 #![feature(globs, struct_variant, managed_boxes, macro_rules, phase)]
24 extern crate serialize;
26 extern crate testing = "test";
28 #[phase(plugin, link)] extern crate log;
31 use std::io::{File, MemWriter};
34 use serialize::{json, Decodable, Encodable};
35 use externalfiles::ExternalHtml;
37 // reexported from `clean` so it can be easily updated with the mod itself
38 pub use clean::SCHEMA_VERSION;
44 pub mod externalfiles;
59 pub mod stability_summary;
64 type Pass = (&'static str, // name
65 fn(clean::Crate) -> plugins::PluginResult, // fn
66 &'static str); // description
68 static PASSES: &'static [Pass] = &[
69 ("strip-hidden", passes::strip_hidden,
70 "strips all doc(hidden) items from the output"),
71 ("unindent-comments", passes::unindent_comments,
72 "removes excess indentation on comments in order for markdown to like it"),
73 ("collapse-docs", passes::collapse_docs,
74 "concatenates all document attributes into one document attribute"),
75 ("strip-private", passes::strip_private,
76 "strips all private items from a crate which cannot be seen externally"),
79 static DEFAULT_PASSES: &'static [&'static str] = &[
86 local_data_key!(pub ctxtkey: Gc<core::DocContext>)
87 local_data_key!(pub analysiskey: core::CrateAnalysis)
89 type Output = (clean::Crate, Vec<plugins::PluginJson> );
92 std::os::set_exit_status(main_args(std::os::args().as_slice()));
95 pub fn opts() -> Vec<getopts::OptGroup> {
98 optflag("h", "help", "show this help message"),
99 optflagopt("", "version", "print rustdoc's version", "verbose"),
100 optopt("r", "input-format", "the input type of the specified file",
102 optopt("w", "output-format", "the output type to write",
104 optopt("o", "output", "where to place the output", "PATH"),
105 optmulti("L", "library-path", "directory to add to crate search path",
107 optmulti("", "cfg", "pass a --cfg to rustc", ""),
108 optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
109 optmulti("", "passes", "space separated list of passes to also run, a \
110 value of `list` will print available passes",
112 optmulti("", "plugins", "space separated list of plugins to also load",
114 optflag("", "no-defaults", "don't run the default passes"),
115 optflag("", "test", "run code examples as tests"),
116 optmulti("", "test-args", "arguments to pass to the test runner",
118 optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
120 optmulti("", "html-in-header",
121 "files to include inline in the <head> section of a rendered Markdown file \
122 or generated documentation",
124 optmulti("", "html-before-content",
125 "files to include inline between <body> and the content of a rendered \
126 Markdown file or generated documentation",
128 optmulti("", "html-after-content",
129 "files to include inline between the content and </body> of a rendered \
130 Markdown file or generated documentation",
132 optopt("", "markdown-playground-url",
133 "URL to send code snippets to", "URL")
137 pub fn usage(argv0: &str) {
139 getopts::usage(format!("{} [options] <input>", argv0).as_slice(),
143 pub fn main_args(args: &[String]) -> int {
144 let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
151 if matches.opt_present("h") || matches.opt_present("help") {
152 usage(args[0].as_slice());
154 } else if matches.opt_present("version") {
155 match rustc::driver::version("rustdoc", &matches) {
164 if matches.free.len() == 0 {
165 println!("expected an input file to act on");
167 } if matches.free.len() > 1 {
168 println!("only one input file may be specified");
171 let input = matches.free.get(0).as_slice();
173 let libs = matches.opt_strs("L").iter().map(|s| Path::new(s.as_slice())).collect();
175 let test_args = matches.opt_strs("test-args");
176 let test_args: Vec<String> = test_args.iter()
177 .flat_map(|s| s.as_slice().words())
178 .map(|s| s.to_string())
181 let should_test = matches.opt_present("test");
182 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
184 let output = matches.opt_str("o").map(|s| Path::new(s));
185 let cfgs = matches.opt_strs("cfg");
187 let external_html = match ExternalHtml::load(
188 matches.opt_strs("html-in-header").as_slice(),
189 matches.opt_strs("html-before-content").as_slice(),
190 matches.opt_strs("html-after-content").as_slice()) {
195 match (should_test, markdown_input) {
197 return markdown::test(input, libs, test_args)
200 return test::run(input, cfgs, libs, test_args)
202 (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
203 &matches, &external_html),
207 if matches.opt_strs("passes").as_slice() == &["list".to_string()] {
208 println!("Available passes for running rustdoc:");
209 for &(name, _, description) in PASSES.iter() {
210 println!("{:>20s} - {}", name, description);
212 println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
213 for &name in DEFAULT_PASSES.iter() {
214 println!("{:>20s}", name);
219 let (krate, res) = match acquire_input(input, &matches) {
222 println!("input error: {}", s);
227 info!("going to format");
228 let started = time::precise_time_ns();
229 match matches.opt_str("w").as_ref().map(|s| s.as_slice()) {
230 Some("html") | None => {
231 match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc"))) {
233 Err(e) => fail!("failed to generate documentation: {}", e),
237 match json_output(krate, res, output.unwrap_or(Path::new("doc.json"))) {
239 Err(e) => fail!("failed to write json: {}", e),
243 println!("unknown output format: {}", s);
247 let ended = time::precise_time_ns();
248 info!("Took {:.03f}s", (ended as f64 - started as f64) / 1e9f64);
253 /// Looks inside the command line arguments to extract the relevant input format
254 /// and files and then generates the necessary rustdoc output for formatting.
255 fn acquire_input(input: &str,
256 matches: &getopts::Matches) -> Result<Output, String> {
257 match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
258 Some("rust") => Ok(rust_input(input, matches)),
259 Some("json") => json_input(input),
260 Some(s) => Err(format!("unknown input format: {}", s)),
262 if input.ends_with(".json") {
265 Ok(rust_input(input, matches))
271 /// Interprets the input file as a rust source file, passing it through the
272 /// compiler all the way through the analysis passes. The rustdoc output is then
273 /// generated from the cleaned AST of the crate.
275 /// This form of input will run all of the plug/cleaning passes
276 fn rust_input(cratefile: &str, matches: &getopts::Matches) -> Output {
277 let mut default_passes = !matches.opt_present("no-defaults");
278 let mut passes = matches.opt_strs("passes");
279 let mut plugins = matches.opt_strs("plugins");
281 // First, parse the crate and extract all relevant information.
282 let libs: Vec<Path> = matches.opt_strs("L")
284 .map(|s| Path::new(s.as_slice()))
286 let cfgs = matches.opt_strs("cfg");
287 let cr = Path::new(cratefile);
288 info!("starting to run rustc");
289 let (krate, analysis) = std::task::try(proc() {
291 core::run_core(libs.move_iter().map(|x| x.clone()).collect(),
294 }).map_err(|boxed_any|format!("{:?}", boxed_any)).unwrap();
295 info!("finished with rustc");
296 analysiskey.replace(Some(analysis));
298 // Process all of the crate attributes, extracting plugin metadata along
299 // with the passes which we are supposed to run.
300 match krate.module.get_ref().doc_list() {
302 for inner in nested.iter() {
305 if "no_default_passes" == x.as_slice() => {
306 default_passes = false;
308 clean::NameValue(ref x, ref value)
309 if "passes" == x.as_slice() => {
310 for pass in value.as_slice().words() {
311 passes.push(pass.to_string());
314 clean::NameValue(ref x, ref value)
315 if "plugins" == x.as_slice() => {
316 for p in value.as_slice().words() {
317 plugins.push(p.to_string());
327 for name in DEFAULT_PASSES.iter().rev() {
328 passes.unshift(name.to_string());
332 // Load all plugins/passes into a PluginManager
333 let path = matches.opt_str("plugin-path")
334 .unwrap_or("/tmp/rustdoc/plugins".to_string());
335 let mut pm = plugins::PluginManager::new(Path::new(path));
336 for pass in passes.iter() {
337 let plugin = match PASSES.iter()
338 .position(|&(p, _, _)| {
341 Some(i) => PASSES[i].val1(),
343 error!("unknown pass {}, skipping", *pass);
347 pm.add_plugin(plugin);
349 info!("loading plugins...");
350 for pname in plugins.move_iter() {
351 pm.load_plugin(pname);
355 info!("Executing passes/plugins");
356 return pm.run_plugins(krate);
359 /// This input format purely deserializes the json output file. No passes are
360 /// run over the deserialized output.
361 fn json_input(input: &str) -> Result<Output, String> {
362 let mut input = match File::open(&Path::new(input)) {
365 return Err(format!("couldn't open {}: {}", input, e))
368 match json::from_reader(&mut input) {
369 Err(s) => Err(s.to_string()),
370 Ok(json::Object(obj)) => {
372 // Make sure the schema is what we expect
373 match obj.pop(&"schema".to_string()) {
374 Some(json::String(version)) => {
375 if version.as_slice() != SCHEMA_VERSION {
377 "sorry, but I only understand version {}",
381 Some(..) => return Err("malformed json".to_string()),
382 None => return Err("expected a schema version".to_string()),
384 let krate = match obj.pop(&"crate".to_string()) {
386 let mut d = json::Decoder::new(json);
387 Decodable::decode(&mut d).unwrap()
389 None => return Err("malformed json".to_string()),
391 // FIXME: this should read from the "plugins" field, but currently
392 // Json doesn't implement decodable...
393 let plugin_output = Vec::new();
394 Ok((krate, plugin_output))
397 Err("malformed json input: expected an object at the \
403 /// Outputs the crate/plugin json as a giant json blob at the specified
405 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
406 dst: Path) -> io::IoResult<()> {
408 // "schema": version,
409 // "crate": { parsed crate ... },
410 // "plugins": { output of plugins ... }
412 let mut json = std::collections::TreeMap::new();
413 json.insert("schema".to_string(), json::String(SCHEMA_VERSION.to_string()));
414 let plugins_json = res.move_iter()
418 Some((string, json)) => {
419 Some((string.to_string(), json))
424 // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
425 // straight to the Rust JSON representation.
426 let crate_json_str = {
427 let mut w = MemWriter::new();
429 let mut encoder = json::Encoder::new(&mut w as &mut io::Writer);
430 krate.encode(&mut encoder).unwrap();
432 str::from_utf8_owned(w.unwrap()).unwrap()
434 let crate_json = match json::from_str(crate_json_str.as_slice()) {
436 Err(e) => fail!("Rust generated JSON is invalid: {:?}", e)
439 json.insert("crate".to_string(), crate_json);
440 json.insert("plugins".to_string(), json::Object(plugins_json));
442 let mut file = try!(File::create(&dst));
443 json::Object(json).to_writer(&mut file)