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/")]
16 #![cfg_attr(stage0, feature(dyn_trait))]
18 #![feature(ascii_ctype)]
19 #![feature(rustc_private)]
20 #![feature(box_patterns)]
21 #![feature(box_syntax)]
22 #![feature(fs_read_write)]
23 #![feature(set_stdio)]
24 #![feature(slice_sort_by_cached_key)]
26 #![feature(vec_remove_item)]
27 #![feature(entry_and_modify)]
29 #![recursion_limit="256"]
33 extern crate env_logger;
35 extern crate rustc_data_structures;
36 extern crate rustc_trans_utils;
37 extern crate rustc_driver;
38 extern crate rustc_resolve;
39 extern crate rustc_lint;
40 extern crate rustc_metadata;
41 extern crate rustc_target;
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 #[macro_use] extern crate log;
48 extern crate rustc_errors as errors;
49 extern crate pulldown_cmark;
51 extern crate minifier;
53 extern crate serialize as rustc_serialize; // used by deriving
55 use errors::ColorConfig;
57 use std::collections::{BTreeMap, BTreeSet};
58 use std::default::Default;
60 use std::fmt::Display;
63 use std::path::{Path, PathBuf};
65 use std::sync::mpsc::channel;
67 use syntax::edition::Edition;
68 use externalfiles::ExternalHtml;
69 use rustc::session::search_paths::SearchPaths;
70 use rustc::session::config::{ErrorOutputType, RustcOptGroup, Externs, CodegenOptions};
71 use rustc::session::config::{nightly_options, build_codegen_options};
72 use rustc_target::spec::TargetTriple;
75 pub mod externalfiles;
99 use clean::AttributesExt;
103 renderinfo: html::render::RenderInfo,
108 const STACK_SIZE: usize = 32_000_000; // 32MB
109 rustc_driver::set_sigpipe_handler();
111 let res = std::thread::Builder::new().stack_size(STACK_SIZE).spawn(move || {
112 syntax::with_globals(move || {
113 get_args().map(|args| main_args(&args)).unwrap_or(1)
115 }).unwrap().join().unwrap_or(101);
116 process::exit(res as i32);
119 fn get_args() -> Option<Vec<String>> {
120 env::args_os().enumerate()
121 .map(|(i, arg)| arg.into_string().map_err(|arg| {
122 print_error(format!("Argument {} is not valid Unicode: {:?}", i, arg));
127 fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
128 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
130 RustcOptGroup::stable(name, f)
133 fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
134 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
136 RustcOptGroup::unstable(name, f)
139 pub fn opts() -> Vec<RustcOptGroup> {
141 stable("h", |o| o.optflag("h", "help", "show this help message")),
142 stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
143 stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
145 o.optopt("r", "input-format", "the input type of the specified file",
149 o.optopt("w", "output-format", "the output type to write", "[html]")
151 stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
152 stable("crate-name", |o| {
153 o.optopt("", "crate-name", "specify the name of this crate", "NAME")
156 o.optmulti("L", "library-path", "directory to add to crate search path",
159 stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
160 stable("extern", |o| {
161 o.optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH")
163 stable("plugin-path", |o| {
164 o.optmulti("", "plugin-path", "directory to load plugins from", "DIR")
167 o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
169 stable("passes", |o| {
170 o.optmulti("", "passes",
171 "list of passes to also run, you might want \
172 to pass it multiple times; a value of `list` \
173 will print available passes",
176 stable("plugins", |o| {
177 o.optmulti("", "plugins", "space separated list of plugins to also load",
180 stable("no-default", |o| {
181 o.optflag("", "no-defaults", "don't run the default passes")
183 stable("document-private-items", |o| {
184 o.optflag("", "document-private-items", "document private items")
186 stable("test", |o| o.optflag("", "test", "run code examples as tests")),
187 stable("test-args", |o| {
188 o.optmulti("", "test-args", "arguments to pass to the test runner",
191 stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
192 stable("markdown-css", |o| {
193 o.optmulti("", "markdown-css",
194 "CSS files to include via <link> in a rendered Markdown file",
197 stable("html-in-header", |o| {
198 o.optmulti("", "html-in-header",
199 "files to include inline in the <head> section of a rendered Markdown file \
200 or generated documentation",
203 stable("html-before-content", |o| {
204 o.optmulti("", "html-before-content",
205 "files to include inline between <body> and the content of a rendered \
206 Markdown file or generated documentation",
209 stable("html-after-content", |o| {
210 o.optmulti("", "html-after-content",
211 "files to include inline between the content and </body> of a rendered \
212 Markdown file or generated documentation",
215 unstable("markdown-before-content", |o| {
216 o.optmulti("", "markdown-before-content",
217 "files to include inline between <body> and the content of a rendered \
218 Markdown file or generated documentation",
221 unstable("markdown-after-content", |o| {
222 o.optmulti("", "markdown-after-content",
223 "files to include inline between the content and </body> of a rendered \
224 Markdown file or generated documentation",
227 stable("markdown-playground-url", |o| {
228 o.optopt("", "markdown-playground-url",
229 "URL to send code snippets to", "URL")
231 stable("markdown-no-toc", |o| {
232 o.optflag("", "markdown-no-toc", "don't include table of contents")
235 o.optopt("e", "extend-css",
236 "To add some CSS rules with a given file to generate doc with your \
237 own theme. However, your theme might break if the rustdoc's generated HTML \
238 changes, so be careful!", "PATH")
242 "internal and debugging options (only on nightly build)", "FLAG")
244 stable("sysroot", |o| {
245 o.optopt("", "sysroot", "Override the system root", "PATH")
247 unstable("playground-url", |o| {
248 o.optopt("", "playground-url",
249 "URL to send code snippets to, may be reset by --markdown-playground-url \
250 or `#![doc(html_playground_url=...)]`",
253 unstable("display-warnings", |o| {
254 o.optflag("", "display-warnings", "to print code warnings when testing doc")
256 unstable("crate-version", |o| {
257 o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
259 unstable("linker", |o| {
260 o.optopt("", "linker", "linker used for building executable test code", "PATH")
262 unstable("sort-modules-by-appearance", |o| {
263 o.optflag("", "sort-modules-by-appearance", "sort modules by where they appear in the \
264 program, rather than alphabetically")
266 unstable("themes", |o| {
267 o.optmulti("", "themes",
268 "additional themes which will be added to the generated docs",
271 unstable("theme-checker", |o| {
272 o.optmulti("", "theme-checker",
273 "check if given theme is valid",
276 unstable("resource-suffix", |o| {
279 "suffix to add to CSS and JavaScript files, e.g. \"light.css\" will become \
280 \"light-suffix.css\"",
283 unstable("edition", |o| {
284 o.optopt("", "edition",
285 "edition to use when compiling rust code (default: 2015)",
288 unstable("color", |o| {
291 "Configure coloring of output:
292 auto = colorize, if output goes to a tty (default);
293 always = always colorize output;
294 never = never colorize output",
297 unstable("error-format", |o| {
300 "How errors and other messages are produced",
303 unstable("disable-minification", |o| {
305 "disable-minification",
306 "Disable minification applied on JS files")
311 pub fn usage(argv0: &str) {
312 let mut options = getopts::Options::new();
313 for option in opts() {
314 (option.apply)(&mut options);
316 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
319 pub fn main_args(args: &[String]) -> isize {
320 let mut options = getopts::Options::new();
321 for option in opts() {
322 (option.apply)(&mut options);
324 let matches = match options.parse(&args[1..]) {
331 // Check for unstable options.
332 nightly_options::check_nightly_options(&matches, &opts());
334 // check for deprecated options
335 check_deprecated_options(&matches);
337 if matches.opt_present("h") || matches.opt_present("help") {
340 } else if matches.opt_present("version") {
341 rustc_driver::version("rustdoc", &matches);
345 if matches.opt_strs("passes") == ["list"] {
346 println!("Available passes for running rustdoc:");
347 for &(name, _, description) in passes::PASSES {
348 println!("{:>20} - {}", name, description);
350 println!("\nDefault passes for rustdoc:");
351 for &name in passes::DEFAULT_PASSES {
352 println!("{:>20}", name);
357 let to_check = matches.opt_strs("theme-checker");
358 if !to_check.is_empty() {
359 let paths = theme::load_css_paths(include_bytes!("html/static/themes/light.css"));
362 println!("rustdoc: [theme-checker] Starting tests!");
363 for theme_file in to_check.iter() {
364 print!(" - Checking \"{}\"...", theme_file);
365 let (success, differences) = theme::test_theme_against(theme_file, &paths);
366 if !differences.is_empty() || !success {
369 if !differences.is_empty() {
370 println!("{}", differences.join("\n"));
382 if matches.free.is_empty() {
383 print_error("missing file operand");
386 if matches.free.len() > 1 {
387 print_error("too many file operands");
390 let input = &matches.free[0];
392 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
393 Some("auto") => ColorConfig::Auto,
394 Some("always") => ColorConfig::Always,
395 Some("never") => ColorConfig::Never,
396 None => ColorConfig::Auto,
398 print_error(&format!("argument for --color must be `auto`, `always` or `never` \
399 (instead was `{}`)", arg));
403 let error_format = match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
404 Some("human") => ErrorOutputType::HumanReadable(color),
405 Some("json") => ErrorOutputType::Json(false),
406 Some("pretty-json") => ErrorOutputType::Json(true),
407 Some("short") => ErrorOutputType::Short(color),
408 None => ErrorOutputType::HumanReadable(color),
410 print_error(&format!("argument for --error-format must be `human`, `json` or \
411 `short` (instead was `{}`)", arg));
416 let mut libs = SearchPaths::new();
417 for s in &matches.opt_strs("L") {
418 libs.add_path(s, error_format);
420 let externs = match parse_externs(&matches) {
428 let test_args = matches.opt_strs("test-args");
429 let test_args: Vec<String> = test_args.iter()
430 .flat_map(|s| s.split_whitespace())
431 .map(|s| s.to_string())
434 let should_test = matches.opt_present("test");
435 let markdown_input = Path::new(input).extension()
436 .map_or(false, |e| e == "md" || e == "markdown");
438 let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
439 let css_file_extension = matches.opt_str("e").map(|s| PathBuf::from(&s));
440 let cfgs = matches.opt_strs("cfg");
442 if let Some(ref p) = css_file_extension {
446 "rustdoc: option --extend-css argument must be a file."
452 let mut themes = Vec::new();
453 if matches.opt_present("themes") {
454 let paths = theme::load_css_paths(include_bytes!("html/static/themes/light.css"));
456 for (theme_file, theme_s) in matches.opt_strs("themes")
458 .map(|s| (PathBuf::from(&s), s.to_owned())) {
459 if !theme_file.is_file() {
460 println!("rustdoc: option --themes arguments must all be files");
463 let (success, ret) = theme::test_theme_against(&theme_file, &paths);
464 if !success || !ret.is_empty() {
465 println!("rustdoc: invalid theme: \"{}\"", theme_s);
466 println!(" Check what's wrong with the \"theme-checker\" option");
469 themes.push(theme_file);
473 let external_html = match ExternalHtml::load(
474 &matches.opt_strs("html-in-header"),
475 &matches.opt_strs("html-before-content"),
476 &matches.opt_strs("html-after-content"),
477 &matches.opt_strs("markdown-before-content"),
478 &matches.opt_strs("markdown-after-content")) {
482 let crate_name = matches.opt_str("crate-name");
483 let playground_url = matches.opt_str("playground-url");
484 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
485 let display_warnings = matches.opt_present("display-warnings");
486 let linker = matches.opt_str("linker").map(PathBuf::from);
487 let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
488 let resource_suffix = matches.opt_str("resource-suffix");
489 let enable_minification = !matches.opt_present("disable-minification");
491 let edition = matches.opt_str("edition").unwrap_or("2015".to_string());
492 let edition = match edition.parse() {
495 print_error("could not parse edition");
500 let cg = build_codegen_options(&matches, ErrorOutputType::default());
502 match (should_test, markdown_input) {
504 return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot,
505 display_warnings, linker, edition, cg)
508 return test::run(Path::new(input), cfgs, libs, externs, test_args, crate_name,
509 maybe_sysroot, display_warnings, linker, edition, cg)
511 (false, true) => return markdown::render(Path::new(input),
512 output.unwrap_or(PathBuf::from("doc")),
513 &matches, &external_html,
514 !matches.opt_present("markdown-no-toc")),
518 let output_format = matches.opt_str("w");
520 let res = acquire_input(PathBuf::from(input), externs, edition, cg, &matches, error_format,
522 let Output { krate, passes, renderinfo } = out;
523 info!("going to format");
524 match output_format.as_ref().map(|s| &**s) {
525 Some("html") | None => {
526 html::render::run(krate, &external_html, playground_url,
527 output.unwrap_or(PathBuf::from("doc")),
528 resource_suffix.unwrap_or(String::new()),
529 passes.into_iter().collect(),
532 sort_modules_alphabetically,
535 .expect("failed to generate documentation");
539 print_error(format!("unknown output format: {}", s));
544 res.unwrap_or_else(|s| {
545 print_error(format!("input error: {}", s));
550 /// Prints an uniformized error message on the standard error output
551 fn print_error<T>(error_message: T) where T: Display {
554 "rustdoc: {}\nTry 'rustdoc --help' for more information.",
559 /// Looks inside the command line arguments to extract the relevant input format
560 /// and files and then generates the necessary rustdoc output for formatting.
561 fn acquire_input<R, F>(input: PathBuf,
565 matches: &getopts::Matches,
566 error_format: ErrorOutputType,
569 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
570 match matches.opt_str("r").as_ref().map(|s| &**s) {
571 Some("rust") => Ok(rust_input(input, externs, edition, cg, matches, error_format, f)),
572 Some(s) => Err(format!("unknown input format: {}", s)),
573 None => Ok(rust_input(input, externs, edition, cg, matches, error_format, f))
577 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
578 /// returns a map mapping crate names to their paths or else an
580 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
581 let mut externs = BTreeMap::new();
582 for arg in &matches.opt_strs("extern") {
583 let mut parts = arg.splitn(2, '=');
584 let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
585 let location = parts.next()
586 .ok_or("--extern value must be of the format `foo=bar`"
588 let name = name.to_string();
589 externs.entry(name).or_insert_with(BTreeSet::new).insert(location.to_string());
591 Ok(Externs::new(externs))
594 /// Interprets the input file as a rust source file, passing it through the
595 /// compiler all the way through the analysis passes. The rustdoc output is then
596 /// generated from the cleaned AST of the crate.
598 /// This form of input will run all of the plug/cleaning passes
599 fn rust_input<R, F>(cratefile: PathBuf,
603 matches: &getopts::Matches,
604 error_format: ErrorOutputType,
606 where R: 'static + Send,
607 F: 'static + Send + FnOnce(Output) -> R
609 let mut default_passes = !matches.opt_present("no-defaults");
610 let mut passes = matches.opt_strs("passes");
611 let mut plugins = matches.opt_strs("plugins");
613 // We hardcode in the passes here, as this is a new flag and we
614 // are generally deprecating passes.
615 if matches.opt_present("document-private-items") {
616 default_passes = false;
619 String::from("collapse-docs"),
620 String::from("unindent-comments"),
624 // First, parse the crate and extract all relevant information.
625 let mut paths = SearchPaths::new();
626 for s in &matches.opt_strs("L") {
627 paths.add_path(s, ErrorOutputType::default());
629 let cfgs = matches.opt_strs("cfg");
630 let triple = matches.opt_str("target").map(|target| {
631 if target.ends_with(".json") {
632 TargetTriple::TargetPath(PathBuf::from(target))
634 TargetTriple::TargetTriple(target)
637 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
638 let crate_name = matches.opt_str("crate-name");
639 let crate_version = matches.opt_str("crate-version");
640 let plugin_path = matches.opt_str("plugin-path");
642 info!("starting to run rustc");
643 let display_warnings = matches.opt_present("display-warnings");
645 let force_unstable_if_unmarked = matches.opt_strs("Z").iter().any(|x| {
646 *x == "force-unstable-if-unmarked"
649 let (tx, rx) = channel();
651 rustc_driver::monitor(move || syntax::with_globals(move || {
652 use rustc::session::config::Input;
654 let (mut krate, renderinfo) =
655 core::run_core(paths, cfgs, externs, Input::File(cratefile), triple, maybe_sysroot,
656 display_warnings, crate_name.clone(),
657 force_unstable_if_unmarked, edition, cg, error_format);
659 info!("finished with rustc");
661 if let Some(name) = crate_name {
665 krate.version = crate_version;
667 // Process all of the crate attributes, extracting plugin metadata along
668 // with the passes which we are supposed to run.
669 for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
670 let name = attr.name().map(|s| s.as_str());
671 let name = name.as_ref().map(|s| &s[..]);
673 if name == Some("no_default_passes") {
674 default_passes = false;
676 } else if let Some(value) = attr.value_str() {
677 let sink = match name {
678 Some("passes") => &mut passes,
679 Some("plugins") => &mut plugins,
682 for p in value.as_str().split_whitespace() {
683 sink.push(p.to_string());
689 for name in passes::DEFAULT_PASSES.iter().rev() {
690 passes.insert(0, name.to_string());
694 // Load all plugins/passes into a PluginManager
695 let path = plugin_path.unwrap_or("/tmp/rustdoc/plugins".to_string());
696 let mut pm = plugins::PluginManager::new(PathBuf::from(path));
697 for pass in &passes {
698 let plugin = match passes::PASSES.iter()
699 .position(|&(p, ..)| {
702 Some(i) => passes::PASSES[i].1,
704 error!("unknown pass {}, skipping", *pass);
708 pm.add_plugin(plugin);
710 info!("loading plugins...");
711 for pname in plugins {
712 pm.load_plugin(pname);
716 info!("Executing passes/plugins");
717 let krate = pm.run_plugins(krate);
719 tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes })).unwrap();
724 /// Prints deprecation warnings for deprecated options
725 fn check_deprecated_options(matches: &getopts::Matches) {
726 let deprecated_flags = [
735 for flag in deprecated_flags.into_iter() {
736 if matches.opt_present(flag) {
737 eprintln!("WARNING: the '{}' flag is considered deprecated", flag);
738 eprintln!("WARNING: please see https://github.com/rust-lang/rust/issues/44136");
742 if matches.opt_present("no-defaults") {
743 eprintln!("WARNING: (you may want to use --document-private-items)");