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 #![feature(rustc_private)]
17 #![feature(box_patterns)]
18 #![feature(box_syntax)]
19 #![feature(iterator_find_map)]
20 #![feature(set_stdio)]
21 #![feature(slice_sort_by_cached_key)]
23 #![feature(vec_remove_item)]
24 #![feature(ptr_offset_from)]
25 #![feature(crate_visibility_modifier)]
28 #![recursion_limit="256"]
32 extern crate env_logger;
34 extern crate rustc_data_structures;
35 extern crate rustc_codegen_utils;
36 extern crate rustc_driver;
37 extern crate rustc_resolve;
38 extern crate rustc_lint;
39 extern crate rustc_metadata;
40 extern crate rustc_target;
41 extern crate rustc_typeck;
42 extern crate serialize;
43 #[macro_use] extern crate syntax;
44 extern crate syntax_pos;
45 extern crate test as testing;
46 #[macro_use] extern crate log;
47 extern crate rustc_errors as errors;
48 extern crate pulldown_cmark;
49 extern crate tempfile;
50 extern crate minifier;
52 extern crate serialize as rustc_serialize; // used by deriving
54 use errors::ColorConfig;
56 use std::collections::{BTreeMap, BTreeSet};
57 use std::default::Default;
60 use std::path::{Path, PathBuf};
62 use std::sync::mpsc::channel;
64 use syntax::edition::Edition;
65 use externalfiles::ExternalHtml;
66 use rustc::session::{early_warn, early_error};
67 use rustc::session::search_paths::SearchPaths;
68 use rustc::session::config::{ErrorOutputType, RustcOptGroup, Externs, CodegenOptions};
69 use rustc::session::config::{nightly_options, build_codegen_options};
70 use rustc_target::spec::TargetTriple;
71 use rustc::session::config::get_cmd_lint_options;
99 renderinfo: html::render::RenderInfo,
104 let thread_stack_size: usize = if cfg!(target_os = "haiku") {
105 16_000_000 // 16MB on Haiku
107 32_000_000 // 32MB on other platforms
109 rustc_driver::set_sigpipe_handler();
111 let res = std::thread::Builder::new().stack_size(thread_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(rustc_driver::EXIT_FAILURE);
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 early_warn(ErrorOutputType::default(),
123 &format!("Argument {} is not valid Unicode: {:?}", i, arg));
128 fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
129 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
131 RustcOptGroup::stable(name, f)
134 fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
135 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
137 RustcOptGroup::unstable(name, f)
140 fn opts() -> Vec<RustcOptGroup> {
142 stable("h", |o| o.optflag("h", "help", "show this help message")),
143 stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
144 stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
146 o.optopt("r", "input-format", "the input type of the specified file",
150 o.optopt("w", "output-format", "the output type to write", "[html]")
152 stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
153 stable("crate-name", |o| {
154 o.optopt("", "crate-name", "specify the name of this crate", "NAME")
157 o.optmulti("L", "library-path", "directory to add to crate search path",
160 stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
161 stable("extern", |o| {
162 o.optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH")
164 stable("plugin-path", |o| {
165 o.optmulti("", "plugin-path", "removed", "DIR")
168 o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
170 stable("passes", |o| {
171 o.optmulti("", "passes",
172 "list of passes to also run, you might want \
173 to pass it multiple times; a value of `list` \
174 will print available passes",
177 stable("plugins", |o| {
178 o.optmulti("", "plugins", "removed",
181 stable("no-default", |o| {
182 o.optflag("", "no-defaults", "don't run the default passes")
184 stable("document-private-items", |o| {
185 o.optflag("", "document-private-items", "document private items")
187 stable("test", |o| o.optflag("", "test", "run code examples as tests")),
188 stable("test-args", |o| {
189 o.optmulti("", "test-args", "arguments to pass to the test runner",
192 stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
193 stable("markdown-css", |o| {
194 o.optmulti("", "markdown-css",
195 "CSS files to include via <link> in a rendered Markdown file",
198 stable("html-in-header", |o| {
199 o.optmulti("", "html-in-header",
200 "files to include inline in the <head> section of a rendered Markdown file \
201 or generated documentation",
204 stable("html-before-content", |o| {
205 o.optmulti("", "html-before-content",
206 "files to include inline between <body> and the content of a rendered \
207 Markdown file or generated documentation",
210 stable("html-after-content", |o| {
211 o.optmulti("", "html-after-content",
212 "files to include inline between the content and </body> of a rendered \
213 Markdown file or generated documentation",
216 unstable("markdown-before-content", |o| {
217 o.optmulti("", "markdown-before-content",
218 "files to include inline between <body> and the content of a rendered \
219 Markdown file or generated documentation",
222 unstable("markdown-after-content", |o| {
223 o.optmulti("", "markdown-after-content",
224 "files to include inline between the content and </body> of a rendered \
225 Markdown file or generated documentation",
228 stable("markdown-playground-url", |o| {
229 o.optopt("", "markdown-playground-url",
230 "URL to send code snippets to", "URL")
232 stable("markdown-no-toc", |o| {
233 o.optflag("", "markdown-no-toc", "don't include table of contents")
236 o.optopt("e", "extend-css",
237 "To add some CSS rules with a given file to generate doc with your \
238 own theme. However, your theme might break if the rustdoc's generated HTML \
239 changes, so be careful!", "PATH")
243 "internal and debugging options (only on nightly build)", "FLAG")
245 stable("sysroot", |o| {
246 o.optopt("", "sysroot", "Override the system root", "PATH")
248 unstable("playground-url", |o| {
249 o.optopt("", "playground-url",
250 "URL to send code snippets to, may be reset by --markdown-playground-url \
251 or `#![doc(html_playground_url=...)]`",
254 unstable("display-warnings", |o| {
255 o.optflag("", "display-warnings", "to print code warnings when testing doc")
257 unstable("crate-version", |o| {
258 o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
260 unstable("linker", |o| {
261 o.optopt("", "linker", "linker used for building executable test code", "PATH")
263 unstable("sort-modules-by-appearance", |o| {
264 o.optflag("", "sort-modules-by-appearance", "sort modules by where they appear in the \
265 program, rather than alphabetically")
267 unstable("themes", |o| {
268 o.optmulti("", "themes",
269 "additional themes which will be added to the generated docs",
272 unstable("theme-checker", |o| {
273 o.optmulti("", "theme-checker",
274 "check if given theme is valid",
277 unstable("resource-suffix", |o| {
280 "suffix to add to CSS and JavaScript files, e.g. \"light.css\" will become \
281 \"light-suffix.css\"",
284 unstable("edition", |o| {
285 o.optopt("", "edition",
286 "edition to use when compiling rust code (default: 2015)",
289 stable("color", |o| {
292 "Configure coloring of output:
293 auto = colorize, if output goes to a tty (default);
294 always = always colorize output;
295 never = never colorize output",
298 stable("error-format", |o| {
301 "How errors and other messages are produced",
304 unstable("disable-minification", |o| {
306 "disable-minification",
307 "Disable minification applied on JS files")
310 o.optmulti("W", "warn", "Set lint warnings", "OPT")
312 stable("allow", |o| {
313 o.optmulti("A", "allow", "Set lint allowed", "OPT")
316 o.optmulti("D", "deny", "Set lint denied", "OPT")
318 stable("forbid", |o| {
319 o.optmulti("F", "forbid", "Set lint forbidden", "OPT")
321 stable("cap-lints", |o| {
325 "Set the most restrictive lint level. \
326 More restrictive lints are capped at this \
327 level. By default, it is at `forbid` level.",
334 fn usage(argv0: &str) {
335 let mut options = getopts::Options::new();
336 for option in opts() {
337 (option.apply)(&mut options);
339 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
342 fn main_args(args: &[String]) -> isize {
343 let mut options = getopts::Options::new();
344 for option in opts() {
345 (option.apply)(&mut options);
347 let matches = match options.parse(&args[1..]) {
350 early_error(ErrorOutputType::default(), &err.to_string());
353 // Check for unstable options.
354 nightly_options::check_nightly_options(&matches, &opts());
356 if matches.opt_present("h") || matches.opt_present("help") {
359 } else if matches.opt_present("version") {
360 rustc_driver::version("rustdoc", &matches);
364 if matches.opt_strs("passes") == ["list"] {
365 println!("Available passes for running rustdoc:");
366 for pass in passes::PASSES {
367 println!("{:>20} - {}", pass.name(), pass.description());
369 println!("\nDefault passes for rustdoc:");
370 for &name in passes::DEFAULT_PASSES {
371 println!("{:>20}", name);
373 println!("\nPasses run with `--document-private-items`:");
374 for &name in passes::DEFAULT_PRIVATE_PASSES {
375 println!("{:>20}", name);
380 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
381 Some("auto") => ColorConfig::Auto,
382 Some("always") => ColorConfig::Always,
383 Some("never") => ColorConfig::Never,
384 None => ColorConfig::Auto,
386 early_error(ErrorOutputType::default(),
387 &format!("argument for --color must be `auto`, `always` or `never` \
388 (instead was `{}`)", arg));
391 let error_format = match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
392 Some("human") => ErrorOutputType::HumanReadable(color),
393 Some("json") => ErrorOutputType::Json(false),
394 Some("pretty-json") => ErrorOutputType::Json(true),
395 Some("short") => ErrorOutputType::Short(color),
396 None => ErrorOutputType::HumanReadable(color),
398 early_error(ErrorOutputType::default(),
399 &format!("argument for --error-format must be `human`, `json` or \
400 `short` (instead was `{}`)", arg));
404 let diag = core::new_handler(error_format, None);
406 // check for deprecated options
407 check_deprecated_options(&matches, &diag);
409 let to_check = matches.opt_strs("theme-checker");
410 if !to_check.is_empty() {
411 let paths = theme::load_css_paths(include_bytes!("html/static/themes/light.css"));
414 println!("rustdoc: [theme-checker] Starting tests!");
415 for theme_file in to_check.iter() {
416 print!(" - Checking \"{}\"...", theme_file);
417 let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag);
418 if !differences.is_empty() || !success {
421 if !differences.is_empty() {
422 println!("{}", differences.join("\n"));
434 if matches.free.is_empty() {
435 diag.struct_err("missing file operand").emit();
438 if matches.free.len() > 1 {
439 diag.struct_err("too many file operands").emit();
442 let input = &matches.free[0];
444 let mut libs = SearchPaths::new();
445 for s in &matches.opt_strs("L") {
446 libs.add_path(s, error_format);
448 let externs = match parse_externs(&matches) {
451 diag.struct_err(&err.to_string()).emit();
456 let test_args = matches.opt_strs("test-args");
457 let test_args: Vec<String> = test_args.iter()
458 .flat_map(|s| s.split_whitespace())
459 .map(|s| s.to_string())
462 let should_test = matches.opt_present("test");
463 let markdown_input = Path::new(input).extension()
464 .map_or(false, |e| e == "md" || e == "markdown");
466 let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
467 let css_file_extension = matches.opt_str("e").map(|s| PathBuf::from(&s));
468 let cfgs = matches.opt_strs("cfg");
470 if let Some(ref p) = css_file_extension {
472 diag.struct_err("option --extend-css argument must be a file").emit();
477 let mut themes = Vec::new();
478 if matches.opt_present("themes") {
479 let paths = theme::load_css_paths(include_bytes!("html/static/themes/light.css"));
481 for (theme_file, theme_s) in matches.opt_strs("themes")
483 .map(|s| (PathBuf::from(&s), s.to_owned())) {
484 if !theme_file.is_file() {
485 diag.struct_err("option --themes arguments must all be files").emit();
488 let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
489 if !success || !ret.is_empty() {
490 diag.struct_err(&format!("invalid theme: \"{}\"", theme_s))
491 .help("check what's wrong with the --theme-checker option")
495 themes.push(theme_file);
499 let mut id_map = html::markdown::IdMap::new();
500 id_map.populate(html::render::initial_ids());
501 let external_html = match ExternalHtml::load(
502 &matches.opt_strs("html-in-header"),
503 &matches.opt_strs("html-before-content"),
504 &matches.opt_strs("html-after-content"),
505 &matches.opt_strs("markdown-before-content"),
506 &matches.opt_strs("markdown-after-content"), &diag, &mut id_map) {
510 let crate_name = matches.opt_str("crate-name");
511 let playground_url = matches.opt_str("playground-url");
512 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
513 let display_warnings = matches.opt_present("display-warnings");
514 let linker = matches.opt_str("linker").map(PathBuf::from);
515 let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
516 let resource_suffix = matches.opt_str("resource-suffix");
517 let enable_minification = !matches.opt_present("disable-minification");
519 let edition = matches.opt_str("edition").unwrap_or("2015".to_string());
520 let edition = match edition.parse() {
523 diag.struct_err("could not parse edition").emit();
528 let cg = build_codegen_options(&matches, ErrorOutputType::default());
530 match (should_test, markdown_input) {
532 return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot,
533 display_warnings, linker, edition, cg, &diag)
536 return test::run(Path::new(input), cfgs, libs, externs, test_args, crate_name,
537 maybe_sysroot, display_warnings, linker, edition, cg)
539 (false, true) => return markdown::render(Path::new(input),
540 output.unwrap_or(PathBuf::from("doc")),
541 &matches, &external_html,
542 !matches.opt_present("markdown-no-toc"), &diag),
546 let output_format = matches.opt_str("w");
548 let res = acquire_input(PathBuf::from(input), externs, edition, cg, &matches, error_format,
550 let Output { krate, passes, renderinfo } = out;
551 let diag = core::new_handler(error_format, None);
552 info!("going to format");
553 match output_format.as_ref().map(|s| &**s) {
554 Some("html") | None => {
555 html::render::run(krate, &external_html, playground_url,
556 output.unwrap_or(PathBuf::from("doc")),
557 resource_suffix.unwrap_or(String::new()),
558 passes.into_iter().collect(),
561 sort_modules_alphabetically,
563 enable_minification, id_map)
564 .expect("failed to generate documentation");
568 diag.struct_err(&format!("unknown output format: {}", s)).emit();
573 res.unwrap_or_else(|s| {
574 diag.struct_err(&format!("input error: {}", s)).emit();
579 /// Looks inside the command line arguments to extract the relevant input format
580 /// and files and then generates the necessary rustdoc output for formatting.
581 fn acquire_input<R, F>(input: PathBuf,
585 matches: &getopts::Matches,
586 error_format: ErrorOutputType,
589 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
590 match matches.opt_str("r").as_ref().map(|s| &**s) {
591 Some("rust") => Ok(rust_input(input, externs, edition, cg, matches, error_format, f)),
592 Some(s) => Err(format!("unknown input format: {}", s)),
593 None => Ok(rust_input(input, externs, edition, cg, matches, error_format, f))
597 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
598 /// returns a map mapping crate names to their paths or else an
600 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
601 let mut externs = BTreeMap::new();
602 for arg in &matches.opt_strs("extern") {
603 let mut parts = arg.splitn(2, '=');
604 let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
605 let location = parts.next()
606 .ok_or("--extern value must be of the format `foo=bar`"
608 let name = name.to_string();
609 externs.entry(name).or_insert_with(BTreeSet::new).insert(location.to_string());
611 Ok(Externs::new(externs))
614 /// Interprets the input file as a rust source file, passing it through the
615 /// compiler all the way through the analysis passes. The rustdoc output is then
616 /// generated from the cleaned AST of the crate.
618 /// This form of input will run all of the plug/cleaning passes
619 fn rust_input<R, F>(cratefile: PathBuf,
623 matches: &getopts::Matches,
624 error_format: ErrorOutputType,
626 where R: 'static + Send,
627 F: 'static + Send + FnOnce(Output) -> R
629 let default_passes = if matches.opt_present("no-defaults") {
630 passes::DefaultPassOption::None
631 } else if matches.opt_present("document-private-items") {
632 passes::DefaultPassOption::Private
634 passes::DefaultPassOption::Default
637 let manual_passes = matches.opt_strs("passes");
638 let plugins = matches.opt_strs("plugins");
640 // First, parse the crate and extract all relevant information.
641 let mut paths = SearchPaths::new();
642 for s in &matches.opt_strs("L") {
643 paths.add_path(s, ErrorOutputType::default());
645 let cfgs = matches.opt_strs("cfg");
646 let triple = matches.opt_str("target").map(|target| {
647 if target.ends_with(".json") {
648 TargetTriple::TargetPath(PathBuf::from(target))
650 TargetTriple::TargetTriple(target)
653 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
654 let crate_name = matches.opt_str("crate-name");
655 let crate_version = matches.opt_str("crate-version");
656 let plugin_path = matches.opt_str("plugin-path");
658 info!("starting to run rustc");
659 let display_warnings = matches.opt_present("display-warnings");
661 let force_unstable_if_unmarked = matches.opt_strs("Z").iter().any(|x| {
662 *x == "force-unstable-if-unmarked"
665 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
667 let (tx, rx) = channel();
669 let result = rustc_driver::monitor(move || syntax::with_globals(move || {
670 use rustc::session::config::Input;
672 let (mut krate, renderinfo, passes) =
673 core::run_core(paths, cfgs, externs, Input::File(cratefile), triple, maybe_sysroot,
674 display_warnings, crate_name.clone(),
675 force_unstable_if_unmarked, edition, cg, error_format,
676 lint_opts, lint_cap, describe_lints, manual_passes, default_passes);
678 info!("finished with rustc");
680 if let Some(name) = crate_name {
684 krate.version = crate_version;
686 if !plugins.is_empty() {
687 eprintln!("WARNING: --plugins no longer functions; see CVE-2018-1000622");
690 if !plugin_path.is_none() {
691 eprintln!("WARNING: --plugin-path no longer functions; see CVE-2018-1000622");
694 info!("Executing passes");
696 for pass in &passes {
697 // determine if we know about this pass
698 let pass = match passes::find_pass(pass) {
699 Some(pass) => if let Some(pass) = pass.late_fn() {
702 // not a late pass, but still valid so don't report the error
706 error!("unknown pass {}, skipping", *pass);
716 tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes })).unwrap();
720 Ok(()) => rx.recv().unwrap(),
721 Err(_) => panic::resume_unwind(Box::new(errors::FatalErrorMarker)),
725 /// Prints deprecation warnings for deprecated options
726 fn check_deprecated_options(matches: &getopts::Matches, diag: &errors::Handler) {
727 let deprecated_flags = [
734 for flag in deprecated_flags.into_iter() {
735 if matches.opt_present(flag) {
736 let mut err = diag.struct_warn(&format!("the '{}' flag is considered deprecated",
738 err.warn("please see https://github.com/rust-lang/rust/issues/44136");
740 if *flag == "no-defaults" {
741 err.help("you may want to use --document-private-items");