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;
96 use html::markdown::RenderType;
100 renderinfo: html::render::RenderInfo,
105 const STACK_SIZE: usize = 32_000_000; // 32MB
106 env_logger::init().unwrap();
107 let res = std::thread::Builder::new().stack_size(STACK_SIZE).spawn(move || {
108 let s = env::args().collect::<Vec<_>>();
110 }).unwrap().join().unwrap_or(101);
111 process::exit(res as i32);
114 fn stable(g: getopts::OptGroup) -> RustcOptGroup { RustcOptGroup::stable(g) }
115 fn unstable(g: getopts::OptGroup) -> RustcOptGroup { RustcOptGroup::unstable(g) }
117 pub fn opts() -> Vec<RustcOptGroup> {
120 stable(optflag("h", "help", "show this help message")),
121 stable(optflag("V", "version", "print rustdoc's version")),
122 stable(optflag("v", "verbose", "use verbose output")),
123 stable(optopt("r", "input-format", "the input type of the specified file",
125 stable(optopt("w", "output-format", "the output type to write",
127 stable(optopt("o", "output", "where to place the output", "PATH")),
128 stable(optopt("", "crate-name", "specify the name of this crate", "NAME")),
129 stable(optmulti("L", "library-path", "directory to add to crate search path",
131 stable(optmulti("", "cfg", "pass a --cfg to rustc", "")),
132 stable(optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH")),
133 stable(optmulti("", "plugin-path", "directory to load plugins from", "DIR")),
134 stable(optmulti("", "passes",
135 "list of passes to also run, you might want \
136 to pass it multiple times; a value of `list` \
137 will print available passes",
139 stable(optmulti("", "plugins", "space separated list of plugins to also load",
141 stable(optflag("", "no-defaults", "don't run the default passes")),
142 stable(optflag("", "test", "run code examples as tests")),
143 stable(optmulti("", "test-args", "arguments to pass to the test runner",
145 stable(optopt("", "target", "target triple to document", "TRIPLE")),
146 stable(optmulti("", "markdown-css",
147 "CSS files to include via <link> in a rendered Markdown file",
149 stable(optmulti("", "html-in-header",
150 "files to include inline in the <head> section of a rendered Markdown file \
151 or generated documentation",
153 stable(optmulti("", "html-before-content",
154 "files to include inline between <body> and the content of a rendered \
155 Markdown file or generated documentation",
157 stable(optmulti("", "html-after-content",
158 "files to include inline between the content and </body> of a rendered \
159 Markdown file or generated documentation",
161 stable(optopt("", "markdown-playground-url",
162 "URL to send code snippets to", "URL")),
163 stable(optflag("", "markdown-no-toc", "don't include table of contents")),
164 unstable(optopt("e", "extend-css",
165 "to redefine some css rules with a given file to generate doc with your \
166 own theme", "PATH")),
167 unstable(optmulti("Z", "",
168 "internal and debugging options (only on nightly build)", "FLAG")),
169 stable(optopt("", "sysroot", "Override the system root", "PATH")),
170 unstable(optopt("", "playground-url",
171 "URL to send code snippets to, may be reset by --markdown-playground-url \
172 or `#![doc(html_playground_url=...)]`",
174 unstable(optflag("", "enable-commonmark", "to enable commonmark doc rendering/testing")),
178 pub fn usage(argv0: &str) {
180 getopts::usage(&format!("{} [options] <input>", argv0),
182 .map(|x| x.opt_group)
183 .collect::<Vec<getopts::OptGroup>>()));
186 pub fn main_args(args: &[String]) -> isize {
187 let all_groups: Vec<getopts::OptGroup> = opts()
189 .map(|x| x.opt_group)
191 let matches = match getopts::getopts(&args[1..], &all_groups) {
198 // Check for unstable options.
199 nightly_options::check_nightly_options(&matches, &opts());
201 if matches.opt_present("h") || matches.opt_present("help") {
204 } else if matches.opt_present("version") {
205 rustc_driver::version("rustdoc", &matches);
209 if matches.opt_strs("passes") == ["list"] {
210 println!("Available passes for running rustdoc:");
211 for &(name, _, description) in passes::PASSES {
212 println!("{:>20} - {}", name, description);
214 println!("\nDefault passes for rustdoc:");
215 for &name in passes::DEFAULT_PASSES {
216 println!("{:>20}", name);
221 if matches.free.is_empty() {
222 print_error("missing file operand");
225 if matches.free.len() > 1 {
226 print_error("too many file operands");
229 let input = &matches.free[0];
231 let mut libs = SearchPaths::new();
232 for s in &matches.opt_strs("L") {
233 libs.add_path(s, ErrorOutputType::default());
235 let externs = match parse_externs(&matches) {
243 let test_args = matches.opt_strs("test-args");
244 let test_args: Vec<String> = test_args.iter()
245 .flat_map(|s| s.split_whitespace())
246 .map(|s| s.to_string())
249 let should_test = matches.opt_present("test");
250 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
252 let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
253 let css_file_extension = matches.opt_str("e").map(|s| PathBuf::from(&s));
254 let cfgs = matches.opt_strs("cfg");
256 let render_type = if matches.opt_present("enable-commonmark") {
262 if let Some(ref p) = css_file_extension {
266 "rustdoc: option --extend-css argument must be a file."
272 let external_html = match ExternalHtml::load(
273 &matches.opt_strs("html-in-header"),
274 &matches.opt_strs("html-before-content"),
275 &matches.opt_strs("html-after-content")) {
279 let crate_name = matches.opt_str("crate-name");
280 let playground_url = matches.opt_str("playground-url");
281 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
283 match (should_test, markdown_input) {
285 return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot, render_type)
288 return test::run(input, cfgs, libs, externs, test_args, crate_name, maybe_sysroot,
291 (false, true) => return markdown::render(input,
292 output.unwrap_or(PathBuf::from("doc")),
293 &matches, &external_html,
294 !matches.opt_present("markdown-no-toc"),
299 let output_format = matches.opt_str("w");
300 let res = acquire_input(input, externs, &matches, move |out| {
301 let Output { krate, passes, renderinfo } = out;
302 info!("going to format");
303 match output_format.as_ref().map(|s| &**s) {
304 Some("html") | None => {
305 html::render::run(krate, &external_html, playground_url,
306 output.unwrap_or(PathBuf::from("doc")),
307 passes.into_iter().collect(),
311 .expect("failed to generate documentation");
315 print_error(format!("unknown output format: {}", s));
320 res.unwrap_or_else(|s| {
321 print_error(format!("input error: {}", s));
326 /// Prints an uniformised error message on the standard error output
327 fn print_error<T>(error_message: T) where T: Display {
330 "rustdoc: {}\nTry 'rustdoc --help' for more information.",
335 /// Looks inside the command line arguments to extract the relevant input format
336 /// and files and then generates the necessary rustdoc output for formatting.
337 fn acquire_input<R, F>(input: &str,
339 matches: &getopts::Matches,
342 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
343 match matches.opt_str("r").as_ref().map(|s| &**s) {
344 Some("rust") => Ok(rust_input(input, externs, matches, f)),
345 Some(s) => Err(format!("unknown input format: {}", s)),
346 None => Ok(rust_input(input, externs, matches, f))
350 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
351 /// returns a map mapping crate names to their paths or else an
353 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
354 let mut externs = BTreeMap::new();
355 for arg in &matches.opt_strs("extern") {
356 let mut parts = arg.splitn(2, '=');
357 let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
358 let location = parts.next()
359 .ok_or("--extern value must be of the format `foo=bar`"
361 let name = name.to_string();
362 externs.entry(name).or_insert_with(BTreeSet::new).insert(location.to_string());
364 Ok(Externs::new(externs))
367 /// Interprets the input file as a rust source file, passing it through the
368 /// compiler all the way through the analysis passes. The rustdoc output is then
369 /// generated from the cleaned AST of the crate.
371 /// This form of input will run all of the plug/cleaning passes
372 fn rust_input<R, F>(cratefile: &str, externs: Externs, matches: &getopts::Matches, f: F) -> R
373 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
374 let mut default_passes = !matches.opt_present("no-defaults");
375 let mut passes = matches.opt_strs("passes");
376 let mut plugins = matches.opt_strs("plugins");
378 // First, parse the crate and extract all relevant information.
379 let mut paths = SearchPaths::new();
380 for s in &matches.opt_strs("L") {
381 paths.add_path(s, ErrorOutputType::default());
383 let cfgs = matches.opt_strs("cfg");
384 let triple = matches.opt_str("target");
385 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
386 let crate_name = matches.opt_str("crate-name");
387 let plugin_path = matches.opt_str("plugin-path");
389 let cr = PathBuf::from(cratefile);
390 info!("starting to run rustc");
392 let (tx, rx) = channel();
393 rustc_driver::monitor(move || {
394 use rustc::session::config::Input;
396 let (mut krate, renderinfo) =
397 core::run_core(paths, cfgs, externs, Input::File(cr), triple, maybe_sysroot);
399 info!("finished with rustc");
401 if let Some(name) = crate_name {
405 // Process all of the crate attributes, extracting plugin metadata along
406 // with the passes which we are supposed to run.
407 for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
408 let name = attr.name().map(|s| s.as_str());
409 let name = name.as_ref().map(|s| &s[..]);
411 if name == Some("no_default_passes") {
412 default_passes = false;
414 } else if let Some(value) = attr.value_str() {
415 let sink = match name {
416 Some("passes") => &mut passes,
417 Some("plugins") => &mut plugins,
420 for p in value.as_str().split_whitespace() {
421 sink.push(p.to_string());
427 for name in passes::DEFAULT_PASSES.iter().rev() {
428 passes.insert(0, name.to_string());
432 // Load all plugins/passes into a PluginManager
433 let path = plugin_path.unwrap_or("/tmp/rustdoc/plugins".to_string());
434 let mut pm = plugins::PluginManager::new(PathBuf::from(path));
435 for pass in &passes {
436 let plugin = match passes::PASSES.iter()
437 .position(|&(p, ..)| {
440 Some(i) => passes::PASSES[i].1,
442 error!("unknown pass {}, skipping", *pass);
446 pm.add_plugin(plugin);
448 info!("loading plugins...");
449 for pname in plugins {
450 pm.load_plugin(pname);
454 info!("Executing passes/plugins");
455 let krate = pm.run_plugins(krate);
457 tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes })).unwrap();