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)]
33 extern crate env_logger;
36 extern crate rustc_data_structures;
37 extern crate rustc_trans;
38 extern crate rustc_driver;
39 extern crate rustc_resolve;
40 extern crate rustc_lint;
41 extern crate rustc_back;
42 extern crate rustc_metadata;
43 extern crate serialize;
44 #[macro_use] extern crate syntax;
45 extern crate syntax_pos;
46 extern crate test as testing;
47 extern crate std_unicode;
48 #[macro_use] extern crate log;
49 extern crate rustc_errors as errors;
50 extern crate pulldown_cmark;
52 extern crate serialize as rustc_serialize; // used by deriving
54 use std::collections::{BTreeMap, BTreeSet};
55 use std::default::Default;
57 use std::fmt::Display;
60 use std::path::PathBuf;
62 use std::sync::mpsc::channel;
64 use externalfiles::ExternalHtml;
65 use rustc::session::search_paths::SearchPaths;
66 use rustc::session::config::{ErrorOutputType, RustcOptGroup, nightly_options,
70 pub mod externalfiles;
93 use clean::AttributesExt;
97 renderinfo: html::render::RenderInfo,
102 const STACK_SIZE: usize = 32_000_000; // 32MB
103 env_logger::init().unwrap();
104 let res = std::thread::Builder::new().stack_size(STACK_SIZE).spawn(move || {
105 let s = env::args().collect::<Vec<_>>();
107 }).unwrap().join().unwrap_or(101);
108 process::exit(res as i32);
111 fn stable(g: getopts::OptGroup) -> RustcOptGroup { RustcOptGroup::stable(g) }
112 fn unstable(g: getopts::OptGroup) -> RustcOptGroup { RustcOptGroup::unstable(g) }
114 pub fn opts() -> Vec<RustcOptGroup> {
117 stable(optflag("h", "help", "show this help message")),
118 stable(optflag("V", "version", "print rustdoc's version")),
119 stable(optflag("v", "verbose", "use verbose output")),
120 stable(optopt("r", "input-format", "the input type of the specified file",
122 stable(optopt("w", "output-format", "the output type to write",
124 stable(optopt("o", "output", "where to place the output", "PATH")),
125 stable(optopt("", "crate-name", "specify the name of this crate", "NAME")),
126 stable(optmulti("L", "library-path", "directory to add to crate search path",
128 stable(optmulti("", "cfg", "pass a --cfg to rustc", "")),
129 stable(optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH")),
130 stable(optmulti("", "plugin-path", "directory to load plugins from", "DIR")),
131 stable(optmulti("", "passes",
132 "list of passes to also run, you might want \
133 to pass it multiple times; a value of `list` \
134 will print available passes",
136 stable(optmulti("", "plugins", "space separated list of plugins to also load",
138 stable(optflag("", "no-defaults", "don't run the default passes")),
139 stable(optflag("", "test", "run code examples as tests")),
140 stable(optmulti("", "test-args", "arguments to pass to the test runner",
142 stable(optopt("", "target", "target triple to document", "TRIPLE")),
143 stable(optmulti("", "markdown-css",
144 "CSS files to include via <link> in a rendered Markdown file",
146 stable(optmulti("", "html-in-header",
147 "files to include inline in the <head> section of a rendered Markdown file \
148 or generated documentation",
150 stable(optmulti("", "html-before-content",
151 "files to include inline between <body> and the content of a rendered \
152 Markdown file or generated documentation",
154 stable(optmulti("", "html-after-content",
155 "files to include inline between the content and </body> of a rendered \
156 Markdown file or generated documentation",
158 stable(optopt("", "markdown-playground-url",
159 "URL to send code snippets to", "URL")),
160 stable(optflag("", "markdown-no-toc", "don't include table of contents")),
161 unstable(optopt("e", "extend-css",
162 "to redefine some css rules with a given file to generate doc with your \
163 own theme", "PATH")),
164 unstable(optmulti("Z", "",
165 "internal and debugging options (only on nightly build)", "FLAG")),
166 stable(optopt("", "sysroot", "Override the system root", "PATH")),
167 unstable(optopt("", "playground-url",
168 "URL to send code snippets to, may be reset by --markdown-playground-url \
169 or `#![doc(html_playground_url=...)]`",
174 pub fn usage(argv0: &str) {
176 getopts::usage(&format!("{} [options] <input>", argv0),
178 .map(|x| x.opt_group)
179 .collect::<Vec<getopts::OptGroup>>()));
182 pub fn main_args(args: &[String]) -> isize {
183 let all_groups: Vec<getopts::OptGroup> = opts()
185 .map(|x| x.opt_group)
187 let matches = match getopts::getopts(&args[1..], &all_groups) {
194 // Check for unstable options.
195 nightly_options::check_nightly_options(&matches, &opts());
197 if matches.opt_present("h") || matches.opt_present("help") {
200 } else if matches.opt_present("version") {
201 rustc_driver::version("rustdoc", &matches);
205 if matches.opt_strs("passes") == ["list"] {
206 println!("Available passes for running rustdoc:");
207 for &(name, _, description) in passes::PASSES {
208 println!("{:>20} - {}", name, description);
210 println!("\nDefault passes for rustdoc:");
211 for &name in passes::DEFAULT_PASSES {
212 println!("{:>20}", name);
217 if matches.free.is_empty() {
218 print_error("missing file operand");
221 if matches.free.len() > 1 {
222 print_error("too many file operands");
225 let input = &matches.free[0];
227 let mut libs = SearchPaths::new();
228 for s in &matches.opt_strs("L") {
229 libs.add_path(s, ErrorOutputType::default());
231 let externs = match parse_externs(&matches) {
239 let test_args = matches.opt_strs("test-args");
240 let test_args: Vec<String> = test_args.iter()
241 .flat_map(|s| s.split_whitespace())
242 .map(|s| s.to_string())
245 let should_test = matches.opt_present("test");
246 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
248 let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
249 let css_file_extension = matches.opt_str("e").map(|s| PathBuf::from(&s));
250 let cfgs = matches.opt_strs("cfg");
252 if let Some(ref p) = css_file_extension {
256 "rustdoc: option --extend-css argument must be a file."
262 let external_html = match ExternalHtml::load(
263 &matches.opt_strs("html-in-header"),
264 &matches.opt_strs("html-before-content"),
265 &matches.opt_strs("html-after-content")) {
269 let crate_name = matches.opt_str("crate-name");
270 let playground_url = matches.opt_str("playground-url");
271 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
273 match (should_test, markdown_input) {
275 return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot)
278 return test::run(input, cfgs, libs, externs, test_args, crate_name, maybe_sysroot)
280 (false, true) => return markdown::render(input,
281 output.unwrap_or(PathBuf::from("doc")),
282 &matches, &external_html,
283 !matches.opt_present("markdown-no-toc")),
287 let output_format = matches.opt_str("w");
288 let res = acquire_input(input, externs, &matches, move |out| {
289 let Output { krate, passes, renderinfo } = out;
290 info!("going to format");
291 match output_format.as_ref().map(|s| &**s) {
292 Some("html") | None => {
293 html::render::run(krate, &external_html, playground_url,
294 output.unwrap_or(PathBuf::from("doc")),
295 passes.into_iter().collect(),
298 .expect("failed to generate documentation");
302 print_error(format!("unknown output format: {}", s));
307 res.unwrap_or_else(|s| {
308 print_error(format!("input error: {}", s));
313 /// Prints an uniformised error message on the standard error output
314 fn print_error<T>(error_message: T) where T: Display {
317 "rustdoc: {}\nTry 'rustdoc --help' for more information.",
322 /// Looks inside the command line arguments to extract the relevant input format
323 /// and files and then generates the necessary rustdoc output for formatting.
324 fn acquire_input<R, F>(input: &str,
326 matches: &getopts::Matches,
329 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
330 match matches.opt_str("r").as_ref().map(|s| &**s) {
331 Some("rust") => Ok(rust_input(input, externs, matches, f)),
332 Some(s) => Err(format!("unknown input format: {}", s)),
333 None => Ok(rust_input(input, externs, matches, f))
337 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
338 /// returns a map mapping crate names to their paths or else an
340 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
341 let mut externs = BTreeMap::new();
342 for arg in &matches.opt_strs("extern") {
343 let mut parts = arg.splitn(2, '=');
344 let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
345 let location = parts.next()
346 .ok_or("--extern value must be of the format `foo=bar`"
348 let name = name.to_string();
349 externs.entry(name).or_insert_with(BTreeSet::new).insert(location.to_string());
351 Ok(Externs::new(externs))
354 /// Interprets the input file as a rust source file, passing it through the
355 /// compiler all the way through the analysis passes. The rustdoc output is then
356 /// generated from the cleaned AST of the crate.
358 /// This form of input will run all of the plug/cleaning passes
359 fn rust_input<R, F>(cratefile: &str, externs: Externs, matches: &getopts::Matches, f: F) -> R
360 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
361 let mut default_passes = !matches.opt_present("no-defaults");
362 let mut passes = matches.opt_strs("passes");
363 let mut plugins = matches.opt_strs("plugins");
365 // First, parse the crate and extract all relevant information.
366 let mut paths = SearchPaths::new();
367 for s in &matches.opt_strs("L") {
368 paths.add_path(s, ErrorOutputType::default());
370 let cfgs = matches.opt_strs("cfg");
371 let triple = matches.opt_str("target");
372 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
373 let crate_name = matches.opt_str("crate-name");
374 let plugin_path = matches.opt_str("plugin-path");
376 let cr = PathBuf::from(cratefile);
377 info!("starting to run rustc");
379 let (tx, rx) = channel();
380 rustc_driver::monitor(move || {
381 use rustc::session::config::Input;
383 let (mut krate, renderinfo) =
384 core::run_core(paths, cfgs, externs, Input::File(cr), triple, maybe_sysroot);
386 info!("finished with rustc");
388 if let Some(name) = crate_name {
392 // Process all of the crate attributes, extracting plugin metadata along
393 // with the passes which we are supposed to run.
394 for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
395 let name = attr.name().map(|s| s.as_str());
396 let name = name.as_ref().map(|s| &s[..]);
398 if name == Some("no_default_passes") {
399 default_passes = false;
401 } else if let Some(value) = attr.value_str() {
402 let sink = match name {
403 Some("passes") => &mut passes,
404 Some("plugins") => &mut plugins,
407 for p in value.as_str().split_whitespace() {
408 sink.push(p.to_string());
414 for name in passes::DEFAULT_PASSES.iter().rev() {
415 passes.insert(0, name.to_string());
419 // Load all plugins/passes into a PluginManager
420 let path = plugin_path.unwrap_or("/tmp/rustdoc/plugins".to_string());
421 let mut pm = plugins::PluginManager::new(PathBuf::from(path));
422 for pass in &passes {
423 let plugin = match passes::PASSES.iter()
424 .position(|&(p, ..)| {
427 Some(i) => passes::PASSES[i].1,
429 error!("unknown pass {}, skipping", *pass);
433 pm.add_plugin(plugin);
435 info!("loading plugins...");
436 for pname in plugins {
437 pm.load_plugin(pname);
441 info!("Executing passes/plugins");
442 let krate = pm.run_plugins(krate);
444 tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes })).unwrap();