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_id = "rustdoc#0.11.0"]
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;
63 type Pass = (&'static str, // name
64 fn(clean::Crate) -> plugins::PluginResult, // fn
65 &'static str); // description
67 static PASSES: &'static [Pass] = &[
68 ("strip-hidden", passes::strip_hidden,
69 "strips all doc(hidden) items from the output"),
70 ("unindent-comments", passes::unindent_comments,
71 "removes excess indentation on comments in order for markdown to like it"),
72 ("collapse-docs", passes::collapse_docs,
73 "concatenates all document attributes into one document attribute"),
74 ("strip-private", passes::strip_private,
75 "strips all private items from a crate which cannot be seen externally"),
78 static DEFAULT_PASSES: &'static [&'static str] = &[
85 local_data_key!(pub ctxtkey: Gc<core::DocContext>)
86 local_data_key!(pub analysiskey: core::CrateAnalysis)
88 type Output = (clean::Crate, Vec<plugins::PluginJson> );
91 std::os::set_exit_status(main_args(std::os::args().as_slice()));
94 pub fn opts() -> Vec<getopts::OptGroup> {
97 optflag("h", "help", "show this help message"),
98 optflagopt("", "version", "print rustdoc's version", "verbose"),
99 optopt("r", "input-format", "the input type of the specified file",
101 optopt("w", "output-format", "the output type to write",
103 optopt("o", "output", "where to place the output", "PATH"),
104 optmulti("L", "library-path", "directory to add to crate search path",
106 optmulti("", "cfg", "pass a --cfg to rustc", ""),
107 optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
108 optmulti("", "passes", "space separated list of passes to also run, a \
109 value of `list` will print available passes",
111 optmulti("", "plugins", "space separated list of plugins to also load",
113 optflag("", "no-defaults", "don't run the default passes"),
114 optflag("", "test", "run code examples as tests"),
115 optmulti("", "test-args", "arguments to pass to the test runner",
117 optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
119 optmulti("", "html-in-header",
120 "files to include inline in the <head> section of a rendered Markdown file \
121 or generated documentation",
123 optmulti("", "html-before-content",
124 "files to include inline between <body> and the content of a rendered \
125 Markdown file or generated documentation",
127 optmulti("", "html-after-content",
128 "files to include inline between the content and </body> of a rendered \
129 Markdown file or generated documentation",
131 optopt("", "markdown-playground-url",
132 "URL to send code snippets to", "URL")
136 pub fn usage(argv0: &str) {
138 getopts::usage(format!("{} [options] <input>", argv0).as_slice(),
142 pub fn main_args(args: &[String]) -> int {
143 let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
150 if matches.opt_present("h") || matches.opt_present("help") {
151 usage(args[0].as_slice());
153 } else if matches.opt_present("version") {
154 match rustc::driver::version("rustdoc", &matches) {
163 if matches.free.len() == 0 {
164 println!("expected an input file to act on");
166 } if matches.free.len() > 1 {
167 println!("only one input file may be specified");
170 let input = matches.free.get(0).as_slice();
172 let libs = matches.opt_strs("L").iter().map(|s| Path::new(s.as_slice())).collect();
174 let test_args = matches.opt_strs("test-args");
175 let test_args: Vec<String> = test_args.iter()
176 .flat_map(|s| s.as_slice().words())
177 .map(|s| s.to_string())
180 let should_test = matches.opt_present("test");
181 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
183 let output = matches.opt_str("o").map(|s| Path::new(s));
184 let cfgs = matches.opt_strs("cfg");
186 let external_html = match ExternalHtml::load(
187 matches.opt_strs("html-in-header").as_slice(),
188 matches.opt_strs("html-before-content").as_slice(),
189 matches.opt_strs("html-after-content").as_slice()) {
194 match (should_test, markdown_input) {
196 return markdown::test(input, libs, test_args)
199 return test::run(input, cfgs, libs, test_args)
201 (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
202 &matches, &external_html),
206 if matches.opt_strs("passes").as_slice() == &["list".to_string()] {
207 println!("Available passes for running rustdoc:");
208 for &(name, _, description) in PASSES.iter() {
209 println!("{:>20s} - {}", name, description);
211 println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
212 for &name in DEFAULT_PASSES.iter() {
213 println!("{:>20s}", name);
218 let (krate, res) = match acquire_input(input, &matches) {
221 println!("input error: {}", s);
226 info!("going to format");
227 let started = time::precise_time_ns();
228 match matches.opt_str("w").as_ref().map(|s| s.as_slice()) {
229 Some("html") | None => {
230 match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc"))) {
232 Err(e) => fail!("failed to generate documentation: {}", e),
236 match json_output(krate, res, output.unwrap_or(Path::new("doc.json"))) {
238 Err(e) => fail!("failed to write json: {}", e),
242 println!("unknown output format: {}", s);
246 let ended = time::precise_time_ns();
247 info!("Took {:.03f}s", (ended as f64 - started as f64) / 1e9f64);
252 /// Looks inside the command line arguments to extract the relevant input format
253 /// and files and then generates the necessary rustdoc output for formatting.
254 fn acquire_input(input: &str,
255 matches: &getopts::Matches) -> Result<Output, String> {
256 match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
257 Some("rust") => Ok(rust_input(input, matches)),
258 Some("json") => json_input(input),
259 Some(s) => Err(format!("unknown input format: {}", s)),
261 if input.ends_with(".json") {
264 Ok(rust_input(input, matches))
270 /// Interprets the input file as a rust source file, passing it through the
271 /// compiler all the way through the analysis passes. The rustdoc output is then
272 /// generated from the cleaned AST of the crate.
274 /// This form of input will run all of the plug/cleaning passes
275 fn rust_input(cratefile: &str, matches: &getopts::Matches) -> Output {
276 let mut default_passes = !matches.opt_present("no-defaults");
277 let mut passes = matches.opt_strs("passes");
278 let mut plugins = matches.opt_strs("plugins");
280 // First, parse the crate and extract all relevant information.
281 let libs: Vec<Path> = matches.opt_strs("L")
283 .map(|s| Path::new(s.as_slice()))
285 let cfgs = matches.opt_strs("cfg");
286 let cr = Path::new(cratefile);
287 info!("starting to run rustc");
288 let (krate, analysis) = std::task::try(proc() {
290 core::run_core(libs.move_iter().map(|x| x.clone()).collect(),
293 }).map_err(|boxed_any|format!("{:?}", boxed_any)).unwrap();
294 info!("finished with rustc");
295 analysiskey.replace(Some(analysis));
297 // Process all of the crate attributes, extracting plugin metadata along
298 // with the passes which we are supposed to run.
299 match krate.module.get_ref().doc_list() {
301 for inner in nested.iter() {
304 if "no_default_passes" == x.as_slice() => {
305 default_passes = false;
307 clean::NameValue(ref x, ref value)
308 if "passes" == x.as_slice() => {
309 for pass in value.as_slice().words() {
310 passes.push(pass.to_string());
313 clean::NameValue(ref x, ref value)
314 if "plugins" == x.as_slice() => {
315 for p in value.as_slice().words() {
316 plugins.push(p.to_string());
326 for name in DEFAULT_PASSES.iter().rev() {
327 passes.unshift(name.to_string());
331 // Load all plugins/passes into a PluginManager
332 let path = matches.opt_str("plugin-path")
333 .unwrap_or("/tmp/rustdoc/plugins".to_string());
334 let mut pm = plugins::PluginManager::new(Path::new(path));
335 for pass in passes.iter() {
336 let plugin = match PASSES.iter()
337 .position(|&(p, _, _)| {
340 Some(i) => PASSES[i].val1(),
342 error!("unknown pass {}, skipping", *pass);
346 pm.add_plugin(plugin);
348 info!("loading plugins...");
349 for pname in plugins.move_iter() {
350 pm.load_plugin(pname);
354 info!("Executing passes/plugins");
355 return pm.run_plugins(krate);
358 /// This input format purely deserializes the json output file. No passes are
359 /// run over the deserialized output.
360 fn json_input(input: &str) -> Result<Output, String> {
361 let mut input = match File::open(&Path::new(input)) {
364 return Err(format!("couldn't open {}: {}", input, e))
367 match json::from_reader(&mut input) {
368 Err(s) => Err(s.to_str()),
369 Ok(json::Object(obj)) => {
371 // Make sure the schema is what we expect
372 match obj.pop(&"schema".to_string()) {
373 Some(json::String(version)) => {
374 if version.as_slice() != SCHEMA_VERSION {
376 "sorry, but I only understand version {}",
380 Some(..) => return Err("malformed json".to_string()),
381 None => return Err("expected a schema version".to_string()),
383 let krate = match obj.pop(&"crate".to_string()) {
385 let mut d = json::Decoder::new(json);
386 Decodable::decode(&mut d).unwrap()
388 None => return Err("malformed json".to_string()),
390 // FIXME: this should read from the "plugins" field, but currently
391 // Json doesn't implement decodable...
392 let plugin_output = Vec::new();
393 Ok((krate, plugin_output))
396 Err("malformed json input: expected an object at the \
402 /// Outputs the crate/plugin json as a giant json blob at the specified
404 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
405 dst: Path) -> io::IoResult<()> {
407 // "schema": version,
408 // "crate": { parsed crate ... },
409 // "plugins": { output of plugins ... }
411 let mut json = std::collections::TreeMap::new();
412 json.insert("schema".to_string(), json::String(SCHEMA_VERSION.to_string()));
413 let plugins_json = res.move_iter()
417 Some((string, json)) => {
418 Some((string.to_string(), json))
423 // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
424 // straight to the Rust JSON representation.
425 let crate_json_str = {
426 let mut w = MemWriter::new();
428 let mut encoder = json::Encoder::new(&mut w as &mut io::Writer);
429 krate.encode(&mut encoder).unwrap();
431 str::from_utf8_owned(w.unwrap()).unwrap()
433 let crate_json = match json::from_str(crate_json_str.as_slice()) {
435 Err(e) => fail!("Rust generated JSON is invalid: {:?}", e)
438 json.insert("crate".to_string(), crate_json);
439 json.insert("plugins".to_string(), json::Object(plugins_json));
441 let mut file = try!(File::create(&dst));
442 json::Object(json).to_writer(&mut file)