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"]
12 #![unstable(feature = "rustc_private", issue = "27812")]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
17 html_root_url = "https://doc.rust-lang.org/nightly/",
18 html_playground_url = "https://play.rust-lang.org/")]
21 #![feature(box_patterns)]
22 #![feature(box_syntax)]
24 #![feature(rustc_private)]
25 #![feature(set_stdio)]
26 #![feature(slice_patterns)]
27 #![feature(staged_api)]
30 #![feature(vec_remove_item)]
34 extern crate env_logger;
37 extern crate rustc_data_structures;
38 extern crate rustc_trans;
39 extern crate rustc_driver;
40 extern crate rustc_resolve;
41 extern crate rustc_lint;
42 extern crate rustc_back;
43 extern crate rustc_metadata;
44 extern crate serialize;
45 #[macro_use] extern crate syntax;
46 extern crate syntax_pos;
47 extern crate test as testing;
48 extern crate std_unicode;
49 #[macro_use] extern crate log;
50 extern crate rustc_errors as errors;
51 extern crate pulldown_cmark;
53 extern crate serialize as rustc_serialize; // used by deriving
55 use std::collections::{BTreeMap, BTreeSet};
56 use std::default::Default;
58 use std::fmt::Display;
61 use std::path::PathBuf;
63 use std::sync::mpsc::channel;
65 use externalfiles::ExternalHtml;
66 use rustc::session::search_paths::SearchPaths;
67 use rustc::session::config::{ErrorOutputType, RustcOptGroup, nightly_options,
71 pub mod externalfiles;
94 use clean::AttributesExt;
98 renderinfo: html::render::RenderInfo,
103 const STACK_SIZE: usize = 32_000_000; // 32MB
104 env_logger::init().unwrap();
105 let res = std::thread::Builder::new().stack_size(STACK_SIZE).spawn(move || {
106 let s = env::args().collect::<Vec<_>>();
108 }).unwrap().join().unwrap_or(101);
109 process::exit(res as i32);
112 fn stable(g: getopts::OptGroup) -> RustcOptGroup { RustcOptGroup::stable(g) }
113 fn unstable(g: getopts::OptGroup) -> RustcOptGroup { RustcOptGroup::unstable(g) }
115 pub fn opts() -> Vec<RustcOptGroup> {
118 stable(optflag("h", "help", "show this help message")),
119 stable(optflag("V", "version", "print rustdoc's version")),
120 stable(optflag("v", "verbose", "use verbose output")),
121 stable(optopt("r", "input-format", "the input type of the specified file",
123 stable(optopt("w", "output-format", "the output type to write",
125 stable(optopt("o", "output", "where to place the output", "PATH")),
126 stable(optopt("", "crate-name", "specify the name of this crate", "NAME")),
127 stable(optmulti("L", "library-path", "directory to add to crate search path",
129 stable(optmulti("", "cfg", "pass a --cfg to rustc", "")),
130 stable(optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH")),
131 stable(optmulti("", "plugin-path", "directory to load plugins from", "DIR")),
132 stable(optmulti("", "passes",
133 "list of passes to also run, you might want \
134 to pass it multiple times; a value of `list` \
135 will print available passes",
137 stable(optmulti("", "plugins", "space separated list of plugins to also load",
139 stable(optflag("", "no-defaults", "don't run the default passes")),
140 stable(optflag("", "test", "run code examples as tests")),
141 stable(optmulti("", "test-args", "arguments to pass to the test runner",
143 stable(optopt("", "target", "target triple to document", "TRIPLE")),
144 stable(optmulti("", "markdown-css",
145 "CSS files to include via <link> in a rendered Markdown file",
147 stable(optmulti("", "html-in-header",
148 "files to include inline in the <head> section of a rendered Markdown file \
149 or generated documentation",
151 stable(optmulti("", "html-before-content",
152 "files to include inline between <body> and the content of a rendered \
153 Markdown file or generated documentation",
155 stable(optmulti("", "html-after-content",
156 "files to include inline between the content and </body> of a rendered \
157 Markdown file or generated documentation",
159 stable(optopt("", "markdown-playground-url",
160 "URL to send code snippets to", "URL")),
161 stable(optflag("", "markdown-no-toc", "don't include table of contents")),
162 unstable(optopt("e", "extend-css",
163 "to redefine some css rules with a given file to generate doc with your \
164 own theme", "PATH")),
165 unstable(optmulti("Z", "",
166 "internal and debugging options (only on nightly build)", "FLAG")),
167 stable(optopt("", "sysroot", "Override the system root", "PATH")),
168 unstable(optopt("", "playground-url",
169 "URL to send code snippets to, may be reset by --markdown-playground-url \
170 or `#![doc(html_playground_url=...)]`",
175 pub fn usage(argv0: &str) {
177 getopts::usage(&format!("{} [options] <input>", argv0),
179 .map(|x| x.opt_group)
180 .collect::<Vec<getopts::OptGroup>>()));
183 pub fn main_args(args: &[String]) -> isize {
184 let all_groups: Vec<getopts::OptGroup> = opts()
186 .map(|x| x.opt_group)
188 let matches = match getopts::getopts(&args[1..], &all_groups) {
195 // Check for unstable options.
196 nightly_options::check_nightly_options(&matches, &opts());
198 if matches.opt_present("h") || matches.opt_present("help") {
201 } else if matches.opt_present("version") {
202 rustc_driver::version("rustdoc", &matches);
206 if matches.opt_strs("passes") == ["list"] {
207 println!("Available passes for running rustdoc:");
208 for &(name, _, description) in passes::PASSES {
209 println!("{:>20} - {}", name, description);
211 println!("\nDefault passes for rustdoc:");
212 for &name in passes::DEFAULT_PASSES {
213 println!("{:>20}", name);
218 if matches.free.is_empty() {
219 print_error("missing file operand");
222 if matches.free.len() > 1 {
223 print_error("too many file operands");
226 let input = &matches.free[0];
228 let mut libs = SearchPaths::new();
229 for s in &matches.opt_strs("L") {
230 libs.add_path(s, ErrorOutputType::default());
232 let externs = match parse_externs(&matches) {
240 let test_args = matches.opt_strs("test-args");
241 let test_args: Vec<String> = test_args.iter()
242 .flat_map(|s| s.split_whitespace())
243 .map(|s| s.to_string())
246 let should_test = matches.opt_present("test");
247 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
249 let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
250 let css_file_extension = matches.opt_str("e").map(|s| PathBuf::from(&s));
251 let cfgs = matches.opt_strs("cfg");
253 if let Some(ref p) = css_file_extension {
257 "rustdoc: option --extend-css argument must be a file."
263 let external_html = match ExternalHtml::load(
264 &matches.opt_strs("html-in-header"),
265 &matches.opt_strs("html-before-content"),
266 &matches.opt_strs("html-after-content")) {
270 let crate_name = matches.opt_str("crate-name");
271 let playground_url = matches.opt_str("playground-url");
272 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
274 match (should_test, markdown_input) {
276 return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot)
279 return test::run(input, cfgs, libs, externs, test_args, crate_name, maybe_sysroot)
281 (false, true) => return markdown::render(input,
282 output.unwrap_or(PathBuf::from("doc")),
283 &matches, &external_html,
284 !matches.opt_present("markdown-no-toc")),
288 let output_format = matches.opt_str("w");
289 let res = acquire_input(input, externs, &matches, move |out| {
290 let Output { krate, passes, renderinfo } = out;
291 info!("going to format");
292 match output_format.as_ref().map(|s| &**s) {
293 Some("html") | None => {
294 html::render::run(krate, &external_html, playground_url,
295 output.unwrap_or(PathBuf::from("doc")),
296 passes.into_iter().collect(),
299 .expect("failed to generate documentation");
303 print_error(format!("unknown output format: {}", s));
308 res.unwrap_or_else(|s| {
309 print_error(format!("input error: {}", s));
314 /// Prints an uniformised error message on the standard error output
315 fn print_error<T>(error_message: T) where T: Display {
318 "rustdoc: {}\nTry 'rustdoc --help' for more information.",
323 /// Looks inside the command line arguments to extract the relevant input format
324 /// and files and then generates the necessary rustdoc output for formatting.
325 fn acquire_input<R, F>(input: &str,
327 matches: &getopts::Matches,
330 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
331 match matches.opt_str("r").as_ref().map(|s| &**s) {
332 Some("rust") => Ok(rust_input(input, externs, matches, f)),
333 Some(s) => Err(format!("unknown input format: {}", s)),
334 None => Ok(rust_input(input, externs, matches, f))
338 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
339 /// returns a map mapping crate names to their paths or else an
341 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
342 let mut externs = BTreeMap::new();
343 for arg in &matches.opt_strs("extern") {
344 let mut parts = arg.splitn(2, '=');
345 let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
346 let location = parts.next()
347 .ok_or("--extern value must be of the format `foo=bar`"
349 let name = name.to_string();
350 externs.entry(name).or_insert_with(BTreeSet::new).insert(location.to_string());
352 Ok(Externs::new(externs))
355 /// Interprets the input file as a rust source file, passing it through the
356 /// compiler all the way through the analysis passes. The rustdoc output is then
357 /// generated from the cleaned AST of the crate.
359 /// This form of input will run all of the plug/cleaning passes
360 fn rust_input<R, F>(cratefile: &str, externs: Externs, matches: &getopts::Matches, f: F) -> R
361 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
362 let mut default_passes = !matches.opt_present("no-defaults");
363 let mut passes = matches.opt_strs("passes");
364 let mut plugins = matches.opt_strs("plugins");
366 // First, parse the crate and extract all relevant information.
367 let mut paths = SearchPaths::new();
368 for s in &matches.opt_strs("L") {
369 paths.add_path(s, ErrorOutputType::default());
371 let cfgs = matches.opt_strs("cfg");
372 let triple = matches.opt_str("target");
373 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
374 let crate_name = matches.opt_str("crate-name");
375 let plugin_path = matches.opt_str("plugin-path");
377 let cr = PathBuf::from(cratefile);
378 info!("starting to run rustc");
380 let (tx, rx) = channel();
381 rustc_driver::monitor(move || {
382 use rustc::session::config::Input;
384 let (mut krate, renderinfo) =
385 core::run_core(paths, cfgs, externs, Input::File(cr), triple, maybe_sysroot);
387 info!("finished with rustc");
389 if let Some(name) = crate_name {
393 // Process all of the crate attributes, extracting plugin metadata along
394 // with the passes which we are supposed to run.
395 for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
396 let name = attr.name().map(|s| s.as_str());
397 let name = name.as_ref().map(|s| &s[..]);
399 if name == Some("no_default_passes") {
400 default_passes = false;
402 } else if let Some(value) = attr.value_str() {
403 let sink = match name {
404 Some("passes") => &mut passes,
405 Some("plugins") => &mut plugins,
408 for p in value.as_str().split_whitespace() {
409 sink.push(p.to_string());
415 for name in passes::DEFAULT_PASSES.iter().rev() {
416 passes.insert(0, name.to_string());
420 // Load all plugins/passes into a PluginManager
421 let path = plugin_path.unwrap_or("/tmp/rustdoc/plugins".to_string());
422 let mut pm = plugins::PluginManager::new(PathBuf::from(path));
423 for pass in &passes {
424 let plugin = match passes::PASSES.iter()
425 .position(|&(p, ..)| {
428 Some(i) => passes::PASSES[i].1,
430 error!("unknown pass {}, skipping", *pass);
434 pm.add_plugin(plugin);
436 info!("loading plugins...");
437 for pname in plugins {
438 pm.load_plugin(pname);
442 info!("Executing passes/plugins");
443 let krate = pm.run_plugins(krate);
445 tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes })).unwrap();