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 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
17 html_root_url = "http://doc.rust-lang.org/nightly/",
18 html_playground_url = "http://play.rust-lang.org/")]
20 #![allow(unknown_features)]
21 #![feature(globs, macro_rules, phase, slicing_syntax)]
22 #![feature(unboxed_closures)]
23 #![feature(old_orphan_check)]
24 #![feature(associated_types)]
30 extern crate rustc_trans;
31 extern crate rustc_driver;
32 extern crate serialize;
34 extern crate "test" as testing;
35 #[phase(plugin, link)] extern crate log;
37 extern crate "serialize" as rustc_serialize; // used by deriving
39 use std::cell::RefCell;
40 use std::collections::HashMap;
41 use std::collections::hash_map::Entry::{Occupied, Vacant};
45 use externalfiles::ExternalHtml;
46 use serialize::Decodable;
47 use serialize::json::{self, Json};
48 use rustc::session::search_paths::SearchPaths;
50 // reexported from `clean` so it can be easily updated with the mod itself
51 pub use clean::SCHEMA_VERSION;
57 pub mod externalfiles;
72 pub mod stability_summary;
77 type Pass = (&'static str, // name
78 fn(clean::Crate) -> plugins::PluginResult, // fn
79 &'static str); // description
81 static PASSES: &'static [Pass] = &[
82 ("strip-hidden", passes::strip_hidden,
83 "strips all doc(hidden) items from the output"),
84 ("unindent-comments", passes::unindent_comments,
85 "removes excess indentation on comments in order for markdown to like it"),
86 ("collapse-docs", passes::collapse_docs,
87 "concatenates all document attributes into one document attribute"),
88 ("strip-private", passes::strip_private,
89 "strips all private items from a crate which cannot be seen externally"),
92 static DEFAULT_PASSES: &'static [&'static str] = &[
99 thread_local!(pub static ANALYSISKEY: Rc<RefCell<Option<core::CrateAnalysis>>> = {
100 Rc::new(RefCell::new(None))
105 json_plugins: Vec<plugins::PluginJson>,
110 static STACK_SIZE: uint = 32000000; // 32MB
111 let res = std::thread::Builder::new().stack_size(STACK_SIZE).spawn(move || {
112 main_args(std::os::args().as_slice())
114 std::os::set_exit_status(res.map_err(|_| ()).unwrap());
117 pub fn opts() -> Vec<getopts::OptGroup> {
120 optflag("h", "help", "show this help message"),
121 optflag("V", "version", "print rustdoc's version"),
122 optflag("v", "verbose", "use verbose output"),
123 optopt("r", "input-format", "the input type of the specified file",
125 optopt("w", "output-format", "the output type to write",
127 optopt("o", "output", "where to place the output", "PATH"),
128 optopt("", "crate-name", "specify the name of this crate", "NAME"),
129 optmulti("L", "library-path", "directory to add to crate search path",
131 optmulti("", "cfg", "pass a --cfg to rustc", ""),
132 optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH"),
133 optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
134 optmulti("", "passes", "space separated list of passes to also run, a \
135 value of `list` will print available passes",
137 optmulti("", "plugins", "space separated list of plugins to also load",
139 optflag("", "no-defaults", "don't run the default passes"),
140 optflag("", "test", "run code examples as tests"),
141 optmulti("", "test-args", "arguments to pass to the test runner",
143 optopt("", "target", "target triple to document", "TRIPLE"),
144 optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
146 optmulti("", "html-in-header",
147 "files to include inline in the <head> section of a rendered Markdown file \
148 or generated documentation",
150 optmulti("", "html-before-content",
151 "files to include inline between <body> and the content of a rendered \
152 Markdown file or generated documentation",
154 optmulti("", "html-after-content",
155 "files to include inline between the content and </body> of a rendered \
156 Markdown file or generated documentation",
158 optopt("", "markdown-playground-url",
159 "URL to send code snippets to", "URL"),
160 optflag("", "markdown-no-toc", "don't include table of contents")
164 pub fn usage(argv0: &str) {
166 getopts::usage(format!("{} [options] <input>", argv0).as_slice(),
170 pub fn main_args(args: &[String]) -> int {
171 let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
178 if matches.opt_present("h") || matches.opt_present("help") {
179 usage(args[0].as_slice());
181 } else if matches.opt_present("version") {
182 rustc_driver::version("rustdoc", &matches);
186 if matches.opt_strs("passes") == ["list"] {
187 println!("Available passes for running rustdoc:");
188 for &(name, _, description) in PASSES.iter() {
189 println!("{:>20} - {}", name, description);
191 println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
192 for &name in DEFAULT_PASSES.iter() {
193 println!("{:>20}", name);
198 if matches.free.len() == 0 {
199 println!("expected an input file to act on");
201 } if matches.free.len() > 1 {
202 println!("only one input file may be specified");
205 let input = matches.free[0].as_slice();
207 let mut libs = SearchPaths::new();
208 for s in matches.opt_strs("L").iter() {
209 libs.add_path(s.as_slice());
211 let externs = match parse_externs(&matches) {
219 let test_args = matches.opt_strs("test-args");
220 let test_args: Vec<String> = test_args.iter()
221 .flat_map(|s| s.as_slice().words())
222 .map(|s| s.to_string())
225 let should_test = matches.opt_present("test");
226 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
228 let output = matches.opt_str("o").map(|s| Path::new(s));
229 let cfgs = matches.opt_strs("cfg");
231 let external_html = match ExternalHtml::load(
232 matches.opt_strs("html-in-header").as_slice(),
233 matches.opt_strs("html-before-content").as_slice(),
234 matches.opt_strs("html-after-content").as_slice()) {
238 let crate_name = matches.opt_str("crate-name");
240 match (should_test, markdown_input) {
242 return markdown::test(input, libs, externs, test_args)
245 return test::run(input, cfgs, libs, externs, test_args, crate_name)
247 (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
248 &matches, &external_html,
249 !matches.opt_present("markdown-no-toc")),
253 let out = match acquire_input(input, externs, &matches) {
256 println!("input error: {}", s);
260 let Output { krate, json_plugins, passes, } = out;
261 info!("going to format");
262 match matches.opt_str("w").as_ref().map(|s| s.as_slice()) {
263 Some("html") | None => {
264 match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc")),
265 passes.into_iter().collect()) {
267 Err(e) => panic!("failed to generate documentation: {}", e),
271 match json_output(krate, json_plugins,
272 output.unwrap_or(Path::new("doc.json"))) {
274 Err(e) => panic!("failed to write json: {}", e),
278 println!("unknown output format: {}", s);
286 /// Looks inside the command line arguments to extract the relevant input format
287 /// and files and then generates the necessary rustdoc output for formatting.
288 fn acquire_input(input: &str,
289 externs: core::Externs,
290 matches: &getopts::Matches) -> Result<Output, String> {
291 match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
292 Some("rust") => Ok(rust_input(input, externs, matches)),
293 Some("json") => json_input(input),
294 Some(s) => Err(format!("unknown input format: {}", s)),
296 if input.ends_with(".json") {
299 Ok(rust_input(input, externs, matches))
305 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
306 /// returns a `HashMap` mapping crate names to their paths or else an
308 fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
309 let mut externs = HashMap::new();
310 for arg in matches.opt_strs("extern").iter() {
311 let mut parts = arg.splitn(1, '=');
312 let name = match parts.next() {
315 return Err("--extern value must not be empty".to_string());
318 let location = match parts.next() {
321 return Err("--extern value must be of the format `foo=bar`".to_string());
324 let locs = match externs.entry(name.to_string()) {
325 Vacant(entry) => entry.set(Vec::with_capacity(1)),
326 Occupied(entry) => entry.into_mut(),
328 locs.push(location.to_string());
333 /// Interprets the input file as a rust source file, passing it through the
334 /// compiler all the way through the analysis passes. The rustdoc output is then
335 /// generated from the cleaned AST of the crate.
337 /// This form of input will run all of the plug/cleaning passes
338 fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matches) -> Output {
339 let mut default_passes = !matches.opt_present("no-defaults");
340 let mut passes = matches.opt_strs("passes");
341 let mut plugins = matches.opt_strs("plugins");
343 // First, parse the crate and extract all relevant information.
344 let mut paths = SearchPaths::new();
345 for s in matches.opt_strs("L").iter() {
346 paths.add_path(s.as_slice());
348 let cfgs = matches.opt_strs("cfg");
349 let triple = matches.opt_str("target");
351 let cr = Path::new(cratefile);
352 info!("starting to run rustc");
354 let (mut krate, analysis) = std::thread::Thread::spawn(move |:| {
356 core::run_core(paths, cfgs, externs, &cr, triple)
357 }).join().map_err(|_| "rustc failed").unwrap();
358 info!("finished with rustc");
359 let mut analysis = Some(analysis);
360 ANALYSISKEY.with(|s| {
361 *s.borrow_mut() = analysis.take();
364 match matches.opt_str("crate-name") {
365 Some(name) => krate.name = name,
369 // Process all of the crate attributes, extracting plugin metadata along
370 // with the passes which we are supposed to run.
371 match krate.module.as_ref().unwrap().doc_list() {
373 for inner in nested.iter() {
376 if "no_default_passes" == *x => {
377 default_passes = false;
379 clean::NameValue(ref x, ref value)
380 if "passes" == *x => {
381 for pass in value.words() {
382 passes.push(pass.to_string());
385 clean::NameValue(ref x, ref value)
386 if "plugins" == *x => {
387 for p in value.words() {
388 plugins.push(p.to_string());
398 for name in DEFAULT_PASSES.iter().rev() {
399 passes.insert(0, name.to_string());
403 // Load all plugins/passes into a PluginManager
404 let path = matches.opt_str("plugin-path")
405 .unwrap_or("/tmp/rustdoc/plugins".to_string());
406 let mut pm = plugins::PluginManager::new(Path::new(path));
407 for pass in passes.iter() {
408 let plugin = match PASSES.iter()
409 .position(|&(p, _, _)| {
412 Some(i) => PASSES[i].1,
414 error!("unknown pass {}, skipping", *pass);
418 pm.add_plugin(plugin);
420 info!("loading plugins...");
421 for pname in plugins.into_iter() {
422 pm.load_plugin(pname);
426 info!("Executing passes/plugins");
427 let (krate, json) = pm.run_plugins(krate);
428 return Output { krate: krate, json_plugins: json, passes: passes, };
431 /// This input format purely deserializes the json output file. No passes are
432 /// run over the deserialized output.
433 fn json_input(input: &str) -> Result<Output, String> {
434 let mut input = match File::open(&Path::new(input)) {
437 return Err(format!("couldn't open {}: {}", input, e))
440 match json::from_reader(&mut input) {
441 Err(s) => Err(s.to_string()),
442 Ok(Json::Object(obj)) => {
444 // Make sure the schema is what we expect
445 match obj.remove(&"schema".to_string()) {
446 Some(Json::String(version)) => {
447 if version != SCHEMA_VERSION {
449 "sorry, but I only understand version {}",
453 Some(..) => return Err("malformed json".to_string()),
454 None => return Err("expected a schema version".to_string()),
456 let krate = match obj.remove(&"crate".to_string()) {
458 let mut d = json::Decoder::new(json);
459 Decodable::decode(&mut d).unwrap()
461 None => return Err("malformed json".to_string()),
463 // FIXME: this should read from the "plugins" field, but currently
464 // Json doesn't implement decodable...
465 let plugin_output = Vec::new();
466 Ok(Output { krate: krate, json_plugins: plugin_output, passes: Vec::new(), })
469 Err("malformed json input: expected an object at the \
475 /// Outputs the crate/plugin json as a giant json blob at the specified
477 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
478 dst: Path) -> io::IoResult<()> {
480 // "schema": version,
481 // "crate": { parsed crate ... },
482 // "plugins": { output of plugins ... }
484 let mut json = std::collections::BTreeMap::new();
485 json.insert("schema".to_string(), Json::String(SCHEMA_VERSION.to_string()));
486 let plugins_json = res.into_iter()
490 Some((string, json)) => {
491 Some((string.to_string(), json))
496 // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
497 // straight to the Rust JSON representation.
498 let crate_json_str = format!("{}", json::as_json(&krate));
499 let crate_json = match json::from_str(crate_json_str.as_slice()) {
501 Err(e) => panic!("Rust generated JSON is invalid: {}", e)
504 json.insert("crate".to_string(), crate_json);
505 json.insert("plugins".to_string(), Json::Object(plugins_json));
507 let mut file = try!(File::create(&dst));
508 write!(&mut file, "{}", Json::Object(json))