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 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
12 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
13 html_root_url = "https://doc.rust-lang.org/nightly/",
14 html_playground_url = "https://play.rust-lang.org/")]
17 #![feature(rustc_private)]
18 #![feature(box_patterns)]
19 #![feature(box_syntax)]
21 #![feature(set_stdio)]
22 #![feature(slice_patterns)]
25 #![feature(vec_remove_item)]
26 #![feature(ascii_ctype)]
30 extern crate env_logger;
31 extern crate html_diff;
34 extern crate rustc_data_structures;
35 extern crate rustc_const_math;
36 extern crate rustc_trans;
37 extern crate rustc_driver;
38 extern crate rustc_resolve;
39 extern crate rustc_lint;
40 extern crate rustc_back;
41 extern crate rustc_metadata;
42 extern crate rustc_typeck;
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;
95 use html::markdown::RenderType;
99 renderinfo: html::render::RenderInfo,
104 const STACK_SIZE: usize = 32_000_000; // 32MB
105 env_logger::init().unwrap();
106 let res = std::thread::Builder::new().stack_size(STACK_SIZE).spawn(move || {
107 get_args().map(|args| main_args(&args)).unwrap_or(1)
108 }).unwrap().join().unwrap_or(101);
109 process::exit(res as i32);
112 fn get_args() -> Option<Vec<String>> {
113 env::args_os().enumerate()
114 .map(|(i, arg)| arg.into_string().map_err(|arg| {
115 print_error(format!("Argument {} is not valid Unicode: {:?}", i, arg));
120 fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
121 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
123 RustcOptGroup::stable(name, f)
126 fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
127 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
129 RustcOptGroup::unstable(name, f)
132 pub fn opts() -> Vec<RustcOptGroup> {
134 stable("h", |o| o.optflag("h", "help", "show this help message")),
135 stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
136 stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
138 o.optopt("r", "input-format", "the input type of the specified file",
142 o.optopt("w", "output-format", "the output type to write", "[html]")
144 stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
145 stable("crate-name", |o| {
146 o.optopt("", "crate-name", "specify the name of this crate", "NAME")
149 o.optmulti("L", "library-path", "directory to add to crate search path",
152 stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
153 stable("extern", |o| {
154 o.optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH")
156 stable("plugin-path", |o| {
157 o.optmulti("", "plugin-path", "directory to load plugins from", "DIR")
159 stable("passes", |o| {
160 o.optmulti("", "passes",
161 "list of passes to also run, you might want \
162 to pass it multiple times; a value of `list` \
163 will print available passes",
166 stable("plugins", |o| {
167 o.optmulti("", "plugins", "space separated list of plugins to also load",
170 stable("no-default", |o| {
171 o.optflag("", "no-defaults", "don't run the default passes")
173 stable("test", |o| o.optflag("", "test", "run code examples as tests")),
174 stable("test-args", |o| {
175 o.optmulti("", "test-args", "arguments to pass to the test runner",
178 stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
179 stable("markdown-css", |o| {
180 o.optmulti("", "markdown-css",
181 "CSS files to include via <link> in a rendered Markdown file",
184 stable("html-in-header", |o| {
185 o.optmulti("", "html-in-header",
186 "files to include inline in the <head> section of a rendered Markdown file \
187 or generated documentation",
190 stable("html-before-content", |o| {
191 o.optmulti("", "html-before-content",
192 "files to include inline between <body> and the content of a rendered \
193 Markdown file or generated documentation",
196 stable("html-after-content", |o| {
197 o.optmulti("", "html-after-content",
198 "files to include inline between the content and </body> of a rendered \
199 Markdown file or generated documentation",
202 unstable("markdown-before-content", |o| {
203 o.optmulti("", "markdown-before-content",
204 "files to include inline between <body> and the content of a rendered \
205 Markdown file or generated documentation",
208 unstable("markdown-after-content", |o| {
209 o.optmulti("", "markdown-after-content",
210 "files to include inline between the content and </body> of a rendered \
211 Markdown file or generated documentation",
214 stable("markdown-playground-url", |o| {
215 o.optopt("", "markdown-playground-url",
216 "URL to send code snippets to", "URL")
218 stable("markdown-no-toc", |o| {
219 o.optflag("", "markdown-no-toc", "don't include table of contents")
222 o.optopt("e", "extend-css",
223 "To add some CSS rules with a given file to generate doc with your \
224 own theme. However, your theme might break if the rustdoc's generated HTML \
225 changes, so be careful!", "PATH")
229 "internal and debugging options (only on nightly build)", "FLAG")
231 stable("sysroot", |o| {
232 o.optopt("", "sysroot", "Override the system root", "PATH")
234 unstable("playground-url", |o| {
235 o.optopt("", "playground-url",
236 "URL to send code snippets to, may be reset by --markdown-playground-url \
237 or `#![doc(html_playground_url=...)]`",
240 unstable("enable-commonmark", |o| {
241 o.optflag("", "enable-commonmark", "to enable commonmark doc rendering/testing")
243 unstable("display-warnings", |o| {
244 o.optflag("", "display-warnings", "to print code warnings when testing doc")
246 unstable("crate-version", |o| {
247 o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
249 unstable("linker", |o| {
250 o.optopt("", "linker", "linker used for building executable test code", "PATH")
255 pub fn usage(argv0: &str) {
256 let mut options = getopts::Options::new();
257 for option in opts() {
258 (option.apply)(&mut options);
260 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
263 pub fn main_args(args: &[String]) -> isize {
264 let mut options = getopts::Options::new();
265 for option in opts() {
266 (option.apply)(&mut options);
268 let matches = match options.parse(&args[1..]) {
275 // Check for unstable options.
276 nightly_options::check_nightly_options(&matches, &opts());
278 if matches.opt_present("h") || matches.opt_present("help") {
281 } else if matches.opt_present("version") {
282 rustc_driver::version("rustdoc", &matches);
286 if matches.opt_strs("passes") == ["list"] {
287 println!("Available passes for running rustdoc:");
288 for &(name, _, description) in passes::PASSES {
289 println!("{:>20} - {}", name, description);
291 println!("\nDefault passes for rustdoc:");
292 for &name in passes::DEFAULT_PASSES {
293 println!("{:>20}", name);
298 if matches.free.is_empty() {
299 print_error("missing file operand");
302 if matches.free.len() > 1 {
303 print_error("too many file operands");
306 let input = &matches.free[0];
308 let mut libs = SearchPaths::new();
309 for s in &matches.opt_strs("L") {
310 libs.add_path(s, ErrorOutputType::default());
312 let externs = match parse_externs(&matches) {
320 let test_args = matches.opt_strs("test-args");
321 let test_args: Vec<String> = test_args.iter()
322 .flat_map(|s| s.split_whitespace())
323 .map(|s| s.to_string())
326 let should_test = matches.opt_present("test");
327 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
329 let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
330 let css_file_extension = matches.opt_str("e").map(|s| PathBuf::from(&s));
331 let cfgs = matches.opt_strs("cfg");
333 let render_type = if matches.opt_present("enable-commonmark") {
339 if let Some(ref p) = css_file_extension {
343 "rustdoc: option --extend-css argument must be a file."
349 let external_html = match ExternalHtml::load(
350 &matches.opt_strs("html-in-header"),
351 &matches.opt_strs("html-before-content"),
352 &matches.opt_strs("html-after-content"),
353 &matches.opt_strs("markdown-before-content"),
354 &matches.opt_strs("markdown-after-content"),
359 let crate_name = matches.opt_str("crate-name");
360 let playground_url = matches.opt_str("playground-url");
361 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
362 let display_warnings = matches.opt_present("display-warnings");
363 let linker = matches.opt_str("linker");
365 match (should_test, markdown_input) {
367 return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot, render_type,
368 display_warnings, linker)
371 return test::run(input, cfgs, libs, externs, test_args, crate_name, maybe_sysroot,
372 render_type, display_warnings, linker)
374 (false, true) => return markdown::render(input,
375 output.unwrap_or(PathBuf::from("doc")),
376 &matches, &external_html,
377 !matches.opt_present("markdown-no-toc"),
382 let output_format = matches.opt_str("w");
383 let res = acquire_input(input, externs, &matches, move |out| {
384 let Output { krate, passes, renderinfo } = out;
385 info!("going to format");
386 match output_format.as_ref().map(|s| &**s) {
387 Some("html") | None => {
388 html::render::run(krate, &external_html, playground_url,
389 output.unwrap_or(PathBuf::from("doc")),
390 passes.into_iter().collect(),
394 .expect("failed to generate documentation");
398 print_error(format!("unknown output format: {}", s));
403 res.unwrap_or_else(|s| {
404 print_error(format!("input error: {}", s));
409 /// Prints an uniformized error message on the standard error output
410 fn print_error<T>(error_message: T) where T: Display {
413 "rustdoc: {}\nTry 'rustdoc --help' for more information.",
418 /// Looks inside the command line arguments to extract the relevant input format
419 /// and files and then generates the necessary rustdoc output for formatting.
420 fn acquire_input<R, F>(input: &str,
422 matches: &getopts::Matches,
425 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
426 match matches.opt_str("r").as_ref().map(|s| &**s) {
427 Some("rust") => Ok(rust_input(input, externs, matches, f)),
428 Some(s) => Err(format!("unknown input format: {}", s)),
429 None => Ok(rust_input(input, externs, matches, f))
433 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
434 /// returns a map mapping crate names to their paths or else an
436 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
437 let mut externs = BTreeMap::new();
438 for arg in &matches.opt_strs("extern") {
439 let mut parts = arg.splitn(2, '=');
440 let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
441 let location = parts.next()
442 .ok_or("--extern value must be of the format `foo=bar`"
444 let name = name.to_string();
445 externs.entry(name).or_insert_with(BTreeSet::new).insert(location.to_string());
447 Ok(Externs::new(externs))
450 /// Interprets the input file as a rust source file, passing it through the
451 /// compiler all the way through the analysis passes. The rustdoc output is then
452 /// generated from the cleaned AST of the crate.
454 /// This form of input will run all of the plug/cleaning passes
455 fn rust_input<R, F>(cratefile: &str, externs: Externs, matches: &getopts::Matches, f: F) -> R
456 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
457 let mut default_passes = !matches.opt_present("no-defaults");
458 let mut passes = matches.opt_strs("passes");
459 let mut plugins = matches.opt_strs("plugins");
461 // First, parse the crate and extract all relevant information.
462 let mut paths = SearchPaths::new();
463 for s in &matches.opt_strs("L") {
464 paths.add_path(s, ErrorOutputType::default());
466 let cfgs = matches.opt_strs("cfg");
467 let triple = matches.opt_str("target");
468 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
469 let crate_name = matches.opt_str("crate-name");
470 let crate_version = matches.opt_str("crate-version");
471 let plugin_path = matches.opt_str("plugin-path");
473 let cr = PathBuf::from(cratefile);
474 info!("starting to run rustc");
475 let display_warnings = matches.opt_present("display-warnings");
477 let force_unstable_if_unmarked = matches.opt_strs("Z").iter().any(|x| {
478 *x == "force-unstable-if-unmarked"
481 let (tx, rx) = channel();
482 rustc_driver::monitor(move || {
483 use rustc::session::config::Input;
485 let (mut krate, renderinfo) =
486 core::run_core(paths, cfgs, externs, Input::File(cr), triple, maybe_sysroot,
487 display_warnings, force_unstable_if_unmarked);
489 info!("finished with rustc");
491 if let Some(name) = crate_name {
495 krate.version = crate_version;
497 // Process all of the crate attributes, extracting plugin metadata along
498 // with the passes which we are supposed to run.
499 for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
500 let name = attr.name().map(|s| s.as_str());
501 let name = name.as_ref().map(|s| &s[..]);
503 if name == Some("no_default_passes") {
504 default_passes = false;
506 } else if let Some(value) = attr.value_str() {
507 let sink = match name {
508 Some("passes") => &mut passes,
509 Some("plugins") => &mut plugins,
512 for p in value.as_str().split_whitespace() {
513 sink.push(p.to_string());
519 for name in passes::DEFAULT_PASSES.iter().rev() {
520 passes.insert(0, name.to_string());
524 // Load all plugins/passes into a PluginManager
525 let path = plugin_path.unwrap_or("/tmp/rustdoc/plugins".to_string());
526 let mut pm = plugins::PluginManager::new(PathBuf::from(path));
527 for pass in &passes {
528 let plugin = match passes::PASSES.iter()
529 .position(|&(p, ..)| {
532 Some(i) => passes::PASSES[i].1,
534 error!("unknown pass {}, skipping", *pass);
538 pm.add_plugin(plugin);
540 info!("loading plugins...");
541 for pname in plugins {
542 pm.load_plugin(pname);
546 info!("Executing passes/plugins");
547 let krate = pm.run_plugins(krate);
549 tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes })).unwrap();