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.10-pre"]
12 #![desc = "rustdoc, the Rust documentation extractor"]
13 #![license = "MIT/ASL2"]
14 #![crate_type = "dylib"]
15 #![crate_type = "rlib"]
17 #![feature(globs, struct_variant, managed_boxes, macro_rules, phase)]
21 extern crate serialize;
24 extern crate collections;
25 extern crate testing = "test";
27 #[phase(syntax, link)]
32 use std::io::{File, MemWriter};
34 use serialize::{json, Decodable, Encodable};
56 pub static SCHEMA_VERSION: &'static str = "0.8.1";
58 type Pass = (&'static str, // name
59 fn(clean::Crate) -> plugins::PluginResult, // fn
60 &'static str); // description
62 static PASSES: &'static [Pass] = &[
63 ("strip-hidden", passes::strip_hidden,
64 "strips all doc(hidden) items from the output"),
65 ("unindent-comments", passes::unindent_comments,
66 "removes excess indentation on comments in order for markdown to like it"),
67 ("collapse-docs", passes::collapse_docs,
68 "concatenates all document attributes into one document attribute"),
69 ("strip-private", passes::strip_private,
70 "strips all private items from a crate which cannot be seen externally"),
73 static DEFAULT_PASSES: &'static [&'static str] = &[
80 local_data_key!(pub ctxtkey: @core::DocContext)
81 local_data_key!(pub analysiskey: core::CrateAnalysis)
83 type Output = (clean::Crate, Vec<plugins::PluginJson> );
86 std::os::set_exit_status(main_args(std::os::args()));
89 pub fn opts() -> Vec<getopts::OptGroup> {
92 optflag("h", "help", "show this help message"),
93 optflag("", "version", "print rustdoc's version"),
94 optopt("r", "input-format", "the input type of the specified file",
96 optopt("w", "output-format", "the output type to write",
98 optopt("o", "output", "where to place the output", "PATH"),
99 optmulti("L", "library-path", "directory to add to crate search path",
101 optmulti("", "cfg", "pass a --cfg to rustc", ""),
102 optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
103 optmulti("", "passes", "space separated list of passes to also run, a \
104 value of `list` will print available passes",
106 optmulti("", "plugins", "space separated list of plugins to also load",
108 optflag("", "no-defaults", "don't run the default passes"),
109 optflag("", "test", "run code examples as tests"),
110 optmulti("", "test-args", "arguments to pass to the test runner",
112 optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
114 optmulti("", "markdown-in-header",
115 "files to include inline in the <head> section of a rendered Markdown file",
117 optmulti("", "markdown-before-content",
118 "files to include inline between <body> and the content of a rendered \
121 optmulti("", "markdown-after-content",
122 "files to include inline between the content and </body> of a rendered \
128 pub fn usage(argv0: &str) {
130 getopts::usage(format!("{} [options] <input>", argv0),
134 pub fn main_args(args: &[~str]) -> int {
135 let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
138 println!("{}", err.to_err_msg());
142 if matches.opt_present("h") || matches.opt_present("help") {
145 } else if matches.opt_present("version") {
146 rustc::version(args[0]);
150 if matches.free.len() == 0 {
151 println!("expected an input file to act on");
153 } if matches.free.len() > 1 {
154 println!("only one input file may be specified");
157 let input = matches.free.get(0).as_slice();
159 let libs = matches.opt_strs("L").iter().map(|s| Path::new(s.as_slice())).collect();
161 let test_args = matches.opt_strs("test-args");
162 let test_args: Vec<~str> = test_args.iter()
163 .flat_map(|s| s.words())
164 .map(|s| s.to_owned())
167 let should_test = matches.opt_present("test");
168 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
170 let output = matches.opt_str("o").map(|s| Path::new(s));
172 match (should_test, markdown_input) {
174 return markdown::test(input,
176 test_args.move_iter().collect())
178 (true, false) => return test::run(input, libs, test_args),
180 (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
185 if matches.opt_strs("passes").as_slice() == &[~"list"] {
186 println!("Available passes for running rustdoc:");
187 for &(name, _, description) in PASSES.iter() {
188 println!("{:>20s} - {}", name, description);
190 println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
191 for &name in DEFAULT_PASSES.iter() {
192 println!("{:>20s}", name);
197 let (krate, res) = match acquire_input(input, &matches) {
200 println!("input error: {}", s);
205 info!("going to format");
206 let started = time::precise_time_ns();
207 match matches.opt_str("w").as_ref().map(|s| s.as_slice()) {
208 Some("html") | None => {
209 match html::render::run(krate, output.unwrap_or(Path::new("doc"))) {
211 Err(e) => fail!("failed to generate documentation: {}", e),
215 match json_output(krate, res, output.unwrap_or(Path::new("doc.json"))) {
217 Err(e) => fail!("failed to write json: {}", e),
221 println!("unknown output format: {}", s);
225 let ended = time::precise_time_ns();
226 info!("Took {:.03f}s", (ended as f64 - started as f64) / 1e9f64);
231 /// Looks inside the command line arguments to extract the relevant input format
232 /// and files and then generates the necessary rustdoc output for formatting.
233 fn acquire_input(input: &str,
234 matches: &getopts::Matches) -> Result<Output, ~str> {
235 match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
236 Some("rust") => Ok(rust_input(input, matches)),
237 Some("json") => json_input(input),
238 Some(s) => Err("unknown input format: " + s),
240 if input.ends_with(".json") {
243 Ok(rust_input(input, matches))
249 /// Interprets the input file as a rust source file, passing it through the
250 /// compiler all the way through the analysis passes. The rustdoc output is then
251 /// generated from the cleaned AST of the crate.
253 /// This form of input will run all of the plug/cleaning passes
254 fn rust_input(cratefile: &str, matches: &getopts::Matches) -> Output {
255 let mut default_passes = !matches.opt_present("no-defaults");
256 let mut passes = matches.opt_strs("passes");
257 let mut plugins = matches.opt_strs("plugins");
259 // First, parse the crate and extract all relevant information.
260 let libs: Vec<Path> = matches.opt_strs("L")
262 .map(|s| Path::new(s.as_slice()))
264 let cfgs = matches.opt_strs("cfg");
265 let cr = Path::new(cratefile);
266 info!("starting to run rustc");
267 let (krate, analysis) = std::task::try(proc() {
269 core::run_core(libs.move_iter().collect(),
270 cfgs.move_iter().collect(),
273 info!("finished with rustc");
274 local_data::set(analysiskey, analysis);
276 // Process all of the crate attributes, extracting plugin metadata along
277 // with the passes which we are supposed to run.
278 match krate.module.get_ref().doc_list() {
280 for inner in nested.iter() {
282 clean::Word(ref x) if "no_default_passes" == *x => {
283 default_passes = false;
285 clean::NameValue(ref x, ref value) if "passes" == *x => {
286 for pass in value.words() {
287 passes.push(pass.to_owned());
290 clean::NameValue(ref x, ref value) if "plugins" == *x => {
291 for p in value.words() {
292 plugins.push(p.to_owned());
302 for name in DEFAULT_PASSES.rev_iter() {
303 passes.unshift(name.to_owned());
307 // Load all plugins/passes into a PluginManager
308 let path = matches.opt_str("plugin-path").unwrap_or(~"/tmp/rustdoc/plugins");
309 let mut pm = plugins::PluginManager::new(Path::new(path));
310 for pass in passes.iter() {
311 let plugin = match PASSES.iter().position(|&(p, _, _)| p == *pass) {
312 Some(i) => PASSES[i].val1(),
314 error!("unknown pass {}, skipping", *pass);
318 pm.add_plugin(plugin);
320 info!("loading plugins...");
321 for pname in plugins.move_iter() {
322 pm.load_plugin(pname);
326 info!("Executing passes/plugins");
327 return pm.run_plugins(krate);
330 /// This input format purely deserializes the json output file. No passes are
331 /// run over the deserialized output.
332 fn json_input(input: &str) -> Result<Output, ~str> {
333 let mut input = match File::open(&Path::new(input)) {
335 Err(e) => return Err(format!("couldn't open {}: {}", input, e)),
337 match json::from_reader(&mut input) {
338 Err(s) => Err(s.to_str()),
339 Ok(json::Object(obj)) => {
341 // Make sure the schema is what we expect
342 match obj.pop(&~"schema") {
343 Some(json::String(version)) => {
344 if version.as_slice() != SCHEMA_VERSION {
345 return Err(format!("sorry, but I only understand \
346 version {}", SCHEMA_VERSION))
349 Some(..) => return Err(~"malformed json"),
350 None => return Err(~"expected a schema version"),
352 let krate = match obj.pop(&~"crate") {
354 let mut d = json::Decoder::new(json);
355 Decodable::decode(&mut d).unwrap()
357 None => return Err(~"malformed json"),
359 // FIXME: this should read from the "plugins" field, but currently
360 // Json doesn't implement decodable...
361 let plugin_output = Vec::new();
362 Ok((krate, plugin_output))
364 Ok(..) => Err(~"malformed json input: expected an object at the top"),
368 /// Outputs the crate/plugin json as a giant json blob at the specified
370 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
371 dst: Path) -> io::IoResult<()> {
373 // "schema": version,
374 // "crate": { parsed crate ... },
375 // "plugins": { output of plugins ... }
377 let mut json = ~collections::TreeMap::new();
378 json.insert(~"schema", json::String(SCHEMA_VERSION.to_owned()));
379 let plugins_json = ~res.move_iter().filter_map(|opt| opt).collect();
381 // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
382 // straight to the Rust JSON representation.
383 let crate_json_str = {
384 let mut w = MemWriter::new();
386 let mut encoder = json::Encoder::new(&mut w as &mut io::Writer);
387 krate.encode(&mut encoder).unwrap();
389 str::from_utf8_owned(w.unwrap()).unwrap()
391 let crate_json = match json::from_str(crate_json_str) {
393 Err(e) => fail!("Rust generated JSON is invalid: {:?}", e)
396 json.insert(~"crate", crate_json);
397 json.insert(~"plugins", json::Object(plugins_json));
399 let mut file = try!(File::create(&dst));
400 try!(json::Object(json).to_writer(&mut file));