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"]
14 #![crate_type = "dylib"]
15 #![crate_type = "rlib"]
16 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
17 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
18 html_root_url = "http://doc.rust-lang.org/nightly/",
19 html_playground_url = "http://play.rust-lang.org/")]
20 #![feature(slicing_syntax)]
21 #![feature(box_syntax)]
22 #![allow(unknown_features)] #![feature(int_uint)]
28 extern crate rustc_trans;
29 extern crate rustc_driver;
30 extern crate serialize;
32 extern crate "test" as testing;
33 #[macro_use] extern crate log;
35 extern crate "serialize" as rustc_serialize; // used by deriving
37 use std::cell::RefCell;
38 use std::collections::HashMap;
42 use externalfiles::ExternalHtml;
43 use serialize::Decodable;
44 use serialize::json::{self, Json};
45 use rustc::session::search_paths::SearchPaths;
47 // reexported from `clean` so it can be easily updated with the mod itself
48 pub use clean::SCHEMA_VERSION;
51 pub mod externalfiles;
70 pub mod stability_summary;
75 type Pass = (&'static str, // name
76 fn(clean::Crate) -> plugins::PluginResult, // fn
77 &'static str); // description
79 static PASSES: &'static [Pass] = &[
80 ("strip-hidden", passes::strip_hidden,
81 "strips all doc(hidden) items from the output"),
82 ("unindent-comments", passes::unindent_comments,
83 "removes excess indentation on comments in order for markdown to like it"),
84 ("collapse-docs", passes::collapse_docs,
85 "concatenates all document attributes into one document attribute"),
86 ("strip-private", passes::strip_private,
87 "strips all private items from a crate which cannot be seen externally"),
90 static DEFAULT_PASSES: &'static [&'static str] = &[
97 thread_local!(pub static ANALYSISKEY: Rc<RefCell<Option<core::CrateAnalysis>>> = {
98 Rc::new(RefCell::new(None))
103 json_plugins: Vec<plugins::PluginJson>,
108 static STACK_SIZE: uint = 32000000; // 32MB
109 let res = std::thread::Builder::new().stack_size(STACK_SIZE).scoped(move || {
110 main_args(std::os::args().as_slice())
112 std::os::set_exit_status(res.map_err(|_| ()).unwrap());
115 pub fn opts() -> Vec<getopts::OptGroup> {
118 optflag("h", "help", "show this help message"),
119 optflag("V", "version", "print rustdoc's version"),
120 optflag("v", "verbose", "use verbose output"),
121 optopt("r", "input-format", "the input type of the specified file",
123 optopt("w", "output-format", "the output type to write",
125 optopt("o", "output", "where to place the output", "PATH"),
126 optopt("", "crate-name", "specify the name of this crate", "NAME"),
127 optmulti("L", "library-path", "directory to add to crate search path",
129 optmulti("", "cfg", "pass a --cfg to rustc", ""),
130 optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH"),
131 optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
132 optmulti("", "passes", "space separated list of passes to also run, a \
133 value of `list` will print available passes",
135 optmulti("", "plugins", "space separated list of plugins to also load",
137 optflag("", "no-defaults", "don't run the default passes"),
138 optflag("", "test", "run code examples as tests"),
139 optmulti("", "test-args", "arguments to pass to the test runner",
141 optopt("", "target", "target triple to document", "TRIPLE"),
142 optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
144 optmulti("", "html-in-header",
145 "files to include inline in the <head> section of a rendered Markdown file \
146 or generated documentation",
148 optmulti("", "html-before-content",
149 "files to include inline between <body> and the content of a rendered \
150 Markdown file or generated documentation",
152 optmulti("", "html-after-content",
153 "files to include inline between the content and </body> of a rendered \
154 Markdown file or generated documentation",
156 optopt("", "markdown-playground-url",
157 "URL to send code snippets to", "URL"),
158 optflag("", "markdown-no-toc", "don't include table of contents")
162 pub fn usage(argv0: &str) {
164 getopts::usage(format!("{} [options] <input>", argv0).as_slice(),
168 pub fn main_args(args: &[String]) -> int {
169 let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
176 if matches.opt_present("h") || matches.opt_present("help") {
177 usage(args[0].as_slice());
179 } else if matches.opt_present("version") {
180 rustc_driver::version("rustdoc", &matches);
184 if matches.opt_strs("passes") == ["list"] {
185 println!("Available passes for running rustdoc:");
186 for &(name, _, description) in PASSES.iter() {
187 println!("{:>20} - {}", name, description);
189 println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
190 for &name in DEFAULT_PASSES.iter() {
191 println!("{:>20}", name);
196 if matches.free.len() == 0 {
197 println!("expected an input file to act on");
199 } if matches.free.len() > 1 {
200 println!("only one input file may be specified");
203 let input = matches.free[0].as_slice();
205 let mut libs = SearchPaths::new();
206 for s in matches.opt_strs("L").iter() {
207 libs.add_path(s.as_slice());
209 let externs = match parse_externs(&matches) {
217 let test_args = matches.opt_strs("test-args");
218 let test_args: Vec<String> = test_args.iter()
219 .flat_map(|s| s.as_slice().words())
220 .map(|s| s.to_string())
223 let should_test = matches.opt_present("test");
224 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
226 let output = matches.opt_str("o").map(|s| Path::new(s));
227 let cfgs = matches.opt_strs("cfg");
229 let external_html = match ExternalHtml::load(
230 matches.opt_strs("html-in-header").as_slice(),
231 matches.opt_strs("html-before-content").as_slice(),
232 matches.opt_strs("html-after-content").as_slice()) {
236 let crate_name = matches.opt_str("crate-name");
238 match (should_test, markdown_input) {
240 return markdown::test(input, libs, externs, test_args)
243 return test::run(input, cfgs, libs, externs, test_args, crate_name)
245 (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
246 &matches, &external_html,
247 !matches.opt_present("markdown-no-toc")),
251 let out = match acquire_input(input, externs, &matches) {
254 println!("input error: {}", s);
258 let Output { krate, json_plugins, passes, } = out;
259 info!("going to format");
260 match matches.opt_str("w").as_ref().map(|s| s.as_slice()) {
261 Some("html") | None => {
262 match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc")),
263 passes.into_iter().collect()) {
265 Err(e) => panic!("failed to generate documentation: {}", e),
269 match json_output(krate, json_plugins,
270 output.unwrap_or(Path::new("doc.json"))) {
272 Err(e) => panic!("failed to write json: {}", e),
276 println!("unknown output format: {}", s);
284 /// Looks inside the command line arguments to extract the relevant input format
285 /// and files and then generates the necessary rustdoc output for formatting.
286 fn acquire_input(input: &str,
287 externs: core::Externs,
288 matches: &getopts::Matches) -> Result<Output, String> {
289 match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
290 Some("rust") => Ok(rust_input(input, externs, matches)),
291 Some("json") => json_input(input),
292 Some(s) => Err(format!("unknown input format: {}", s)),
294 if input.ends_with(".json") {
297 Ok(rust_input(input, externs, matches))
303 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
304 /// returns a `HashMap` mapping crate names to their paths or else an
306 fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
307 let mut externs = HashMap::new();
308 for arg in matches.opt_strs("extern").iter() {
309 let mut parts = arg.splitn(1, '=');
310 let name = match parts.next() {
313 return Err("--extern value must not be empty".to_string());
316 let location = match parts.next() {
319 return Err("--extern value must be of the format `foo=bar`".to_string());
322 let name = name.to_string();
323 let locs = externs.entry(name).get().unwrap_or_else(
324 |vacant_entry| vacant_entry.insert(Vec::with_capacity(1)));
325 locs.push(location.to_string());
330 /// Interprets the input file as a rust source file, passing it through the
331 /// compiler all the way through the analysis passes. The rustdoc output is then
332 /// generated from the cleaned AST of the crate.
334 /// This form of input will run all of the plug/cleaning passes
335 fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matches) -> Output {
336 let mut default_passes = !matches.opt_present("no-defaults");
337 let mut passes = matches.opt_strs("passes");
338 let mut plugins = matches.opt_strs("plugins");
340 // First, parse the crate and extract all relevant information.
341 let mut paths = SearchPaths::new();
342 for s in matches.opt_strs("L").iter() {
343 paths.add_path(s.as_slice());
345 let cfgs = matches.opt_strs("cfg");
346 let triple = matches.opt_str("target");
348 let cr = Path::new(cratefile);
349 info!("starting to run rustc");
351 let (mut krate, analysis) = std::thread::Thread::scoped(move |:| {
353 core::run_core(paths, cfgs, externs, &cr, triple)
354 }).join().map_err(|_| "rustc failed").unwrap();
355 info!("finished with rustc");
356 let mut analysis = Some(analysis);
357 ANALYSISKEY.with(|s| {
358 *s.borrow_mut() = analysis.take();
361 match matches.opt_str("crate-name") {
362 Some(name) => krate.name = name,
366 // Process all of the crate attributes, extracting plugin metadata along
367 // with the passes which we are supposed to run.
368 match krate.module.as_ref().unwrap().doc_list() {
370 for inner in nested.iter() {
373 if "no_default_passes" == *x => {
374 default_passes = false;
376 clean::NameValue(ref x, ref value)
377 if "passes" == *x => {
378 for pass in value.words() {
379 passes.push(pass.to_string());
382 clean::NameValue(ref x, ref value)
383 if "plugins" == *x => {
384 for p in value.words() {
385 plugins.push(p.to_string());
395 for name in DEFAULT_PASSES.iter().rev() {
396 passes.insert(0, name.to_string());
400 // Load all plugins/passes into a PluginManager
401 let path = matches.opt_str("plugin-path")
402 .unwrap_or("/tmp/rustdoc/plugins".to_string());
403 let mut pm = plugins::PluginManager::new(Path::new(path));
404 for pass in passes.iter() {
405 let plugin = match PASSES.iter()
406 .position(|&(p, _, _)| {
409 Some(i) => PASSES[i].1,
411 error!("unknown pass {}, skipping", *pass);
415 pm.add_plugin(plugin);
417 info!("loading plugins...");
418 for pname in plugins.into_iter() {
419 pm.load_plugin(pname);
423 info!("Executing passes/plugins");
424 let (krate, json) = pm.run_plugins(krate);
425 return Output { krate: krate, json_plugins: json, passes: passes, };
428 /// This input format purely deserializes the json output file. No passes are
429 /// run over the deserialized output.
430 fn json_input(input: &str) -> Result<Output, String> {
431 let mut input = match File::open(&Path::new(input)) {
434 return Err(format!("couldn't open {}: {}", input, e))
437 match json::from_reader(&mut input) {
438 Err(s) => Err(format!("{:?}", s)),
439 Ok(Json::Object(obj)) => {
441 // Make sure the schema is what we expect
442 match obj.remove(&"schema".to_string()) {
443 Some(Json::String(version)) => {
444 if version != SCHEMA_VERSION {
446 "sorry, but I only understand version {}",
450 Some(..) => return Err("malformed json".to_string()),
451 None => return Err("expected a schema version".to_string()),
453 let krate = match obj.remove(&"crate".to_string()) {
455 let mut d = json::Decoder::new(json);
456 Decodable::decode(&mut d).unwrap()
458 None => return Err("malformed json".to_string()),
460 // FIXME: this should read from the "plugins" field, but currently
461 // Json doesn't implement decodable...
462 let plugin_output = Vec::new();
463 Ok(Output { krate: krate, json_plugins: plugin_output, passes: Vec::new(), })
466 Err("malformed json input: expected an object at the \
472 /// Outputs the crate/plugin json as a giant json blob at the specified
474 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
475 dst: Path) -> io::IoResult<()> {
477 // "schema": version,
478 // "crate": { parsed crate ... },
479 // "plugins": { output of plugins ... }
481 let mut json = std::collections::BTreeMap::new();
482 json.insert("schema".to_string(), Json::String(SCHEMA_VERSION.to_string()));
483 let plugins_json = res.into_iter()
487 Some((string, json)) => {
488 Some((string.to_string(), json))
493 // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
494 // straight to the Rust JSON representation.
495 let crate_json_str = format!("{}", json::as_json(&krate));
496 let crate_json = match json::from_str(crate_json_str.as_slice()) {
498 Err(e) => panic!("Rust generated JSON is invalid: {:?}", e)
501 json.insert("crate".to_string(), crate_json);
502 json.insert("plugins".to_string(), Json::Object(plugins_json));
504 let mut file = try!(File::create(&dst));
505 write!(&mut file, "{}", Json::Object(json))