2 html_root_url = "https://doc.rust-lang.org/nightly/",
3 html_playground_url = "https://play.rust-lang.org/"
5 #![feature(rustc_private)]
6 #![feature(array_methods)]
7 #![feature(box_patterns)]
8 #![feature(box_syntax)]
9 #![feature(in_band_lifetimes)]
11 #![cfg_attr(bootstrap, feature(or_patterns))]
13 #![feature(crate_visibility_modifier)]
14 #![feature(never_type)]
15 #![feature(once_cell)]
16 #![feature(type_ascription)]
17 #![feature(iter_intersperse)]
18 #![recursion_limit = "256"]
19 #![deny(rustc::internal)]
22 extern crate lazy_static;
26 // N.B. these need `extern crate` even in 2018 edition
27 // because they're loaded implicitly from the sysroot.
28 // The reason they're loaded from the sysroot is because
29 // the rustdoc artifacts aren't stored in rustc's cargo target directory.
30 // So if `rustc` was specified in Cargo.toml, this would spuriously rebuild crates.
32 // Dependencies listed in Cargo.toml do not need `extern crate`.
34 extern crate rustc_ast;
35 extern crate rustc_ast_lowering;
36 extern crate rustc_ast_pretty;
37 extern crate rustc_attr;
38 extern crate rustc_data_structures;
39 extern crate rustc_driver;
40 extern crate rustc_errors;
41 extern crate rustc_expand;
42 extern crate rustc_feature;
43 extern crate rustc_hir;
44 extern crate rustc_hir_pretty;
45 extern crate rustc_index;
46 extern crate rustc_infer;
47 extern crate rustc_interface;
48 extern crate rustc_lexer;
49 extern crate rustc_lint;
50 extern crate rustc_lint_defs;
51 extern crate rustc_metadata;
52 extern crate rustc_middle;
53 extern crate rustc_mir;
54 extern crate rustc_parse;
55 extern crate rustc_passes;
56 extern crate rustc_resolve;
57 extern crate rustc_session;
58 extern crate rustc_span as rustc_span;
59 extern crate rustc_target;
60 extern crate rustc_trait_selection;
61 extern crate rustc_typeck;
62 extern crate test as testing;
64 #[cfg(feature = "jemalloc")]
65 extern crate tikv_jemalloc_sys;
66 #[cfg(feature = "jemalloc")]
67 use tikv_jemalloc_sys as jemalloc_sys;
68 #[cfg(feature = "jemalloc")]
69 extern crate tikv_jemallocator;
70 #[cfg(feature = "jemalloc")]
71 use tikv_jemallocator as jemallocator;
73 use std::default::Default;
77 use rustc_driver::{abort_on_err, describe_lints};
78 use rustc_errors::ErrorReported;
79 use rustc_interface::interface;
80 use rustc_middle::ty::TyCtxt;
81 use rustc_session::config::{make_crate_type_option, ErrorOutputType, RustcOptGroup};
82 use rustc_session::getopts;
83 use rustc_session::{early_error, early_warn};
85 /// A macro to create a FxHashMap.
90 /// let letters = map!{"a" => "b", "c" => "d"};
93 /// Trailing commas are allowed.
94 /// Commas between elements are required (even if the expression is a block).
96 ($( $key: expr => $val: expr ),* $(,)*) => {{
97 let mut map = ::rustc_data_structures::fx::FxHashMap::default();
98 $( map.insert($key, $val); )*
116 // used by the error-index generator, so it needs to be public
126 // See docs in https://github.com/rust-lang/rust/blob/master/compiler/rustc/src/main.rs
127 // about jemallocator
128 #[cfg(feature = "jemalloc")]
130 static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
133 // See docs in https://github.com/rust-lang/rust/blob/master/compiler/rustc/src/main.rs
134 // about jemalloc-sys
135 #[cfg(feature = "jemalloc")]
137 use std::os::raw::{c_int, c_void};
140 static _F1: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::calloc;
142 static _F2: unsafe extern "C" fn(*mut *mut c_void, usize, usize) -> c_int =
143 jemalloc_sys::posix_memalign;
145 static _F3: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::aligned_alloc;
147 static _F4: unsafe extern "C" fn(usize) -> *mut c_void = jemalloc_sys::malloc;
149 static _F5: unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void = jemalloc_sys::realloc;
151 static _F6: unsafe extern "C" fn(*mut c_void) = jemalloc_sys::free;
153 // On OSX, jemalloc doesn't directly override malloc/free, but instead
154 // registers itself with the allocator's zone APIs in a ctor. However,
155 // the linker doesn't seem to consider ctors as "used" when statically
156 // linking, so we need to explicitly depend on the function.
157 #[cfg(target_os = "macos")]
160 fn _rjem_je_zone_register();
164 static _F7: unsafe extern "C" fn() = _rjem_je_zone_register;
168 rustc_driver::set_sigpipe_handler();
169 rustc_driver::install_ice_hook();
171 // When using CI artifacts (with `download_stage1 = true`), tracing is unconditionally built
172 // with `--features=static_max_level_info`, which disables almost all rustdoc logging. To avoid
173 // this, compile our own version of `tracing` that logs all levels.
174 // NOTE: this compiles both versions of tracing unconditionally, because
175 // - The compile time hit is not that bad, especially compared to rustdoc's incremental times, and
176 // - Otherwise, there's no warning that logging is being ignored when `download_stage1 = true`.
177 // NOTE: The reason this doesn't show double logging when `download_stage1 = false` and
178 // `debug_logging = true` is because all rustc logging goes to its version of tracing (the one
179 // in the sysroot), and all of rustdoc's logging goes to its version (the one in Cargo.toml).
181 rustc_driver::init_env_logger("RUSTDOC_LOG");
183 let exit_code = rustc_driver::catch_with_exit_code(|| match get_args() {
184 Some(args) => main_args(&args),
185 _ => Err(ErrorReported),
187 process::exit(exit_code);
193 // FIXME remove these and use winapi 0.3 instead
194 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs, rustc_driver/lib.rs
196 fn stdout_isatty() -> bool {
198 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
202 fn stdout_isatty() -> bool {
204 use winapi::um::consoleapi::GetConsoleMode;
205 use winapi::um::processenv::GetStdHandle;
206 use winapi::um::winbase::STD_OUTPUT_HANDLE;
209 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
211 GetConsoleMode(handle, &mut out) != 0
215 let color_logs = match std::env::var("RUSTDOC_LOG_COLOR") {
216 Ok(value) => match value.as_ref() {
219 "auto" => stdout_isatty(),
221 ErrorOutputType::default(),
223 "invalid log color value '{}': expected one of always, never, or auto",
228 Err(std::env::VarError::NotPresent) => stdout_isatty(),
229 Err(std::env::VarError::NotUnicode(_value)) => early_error(
230 ErrorOutputType::default(),
231 "non-Unicode log color value: expected one of always, never, or auto",
234 let filter = tracing_subscriber::EnvFilter::from_env("RUSTDOC_LOG");
235 let layer = tracing_tree::HierarchicalLayer::default()
236 .with_writer(io::stderr)
237 .with_indent_lines(true)
238 .with_ansi(color_logs)
241 .with_verbose_exit(true)
242 .with_verbose_entry(true)
243 .with_indent_amount(2);
244 #[cfg(parallel_compiler)]
245 let layer = layer.with_thread_ids(true).with_thread_names(true);
247 use tracing_subscriber::layer::SubscriberExt;
248 let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
249 tracing::subscriber::set_global_default(subscriber).unwrap();
252 fn get_args() -> Option<Vec<String>> {
259 ErrorOutputType::default(),
260 &format!("Argument {} is not valid Unicode: {:?}", i, arg),
268 fn opts() -> Vec<RustcOptGroup> {
269 let stable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::stable;
270 let unstable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::unstable;
272 stable("h", |o| o.optflag("h", "help", "show this help message")),
273 stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
274 stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
276 o.optopt("r", "input-format", "the input type of the specified file", "[rust]")
278 stable("w", |o| o.optopt("w", "output-format", "the output type to write", "[html]")),
279 stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
280 stable("crate-name", |o| {
281 o.optopt("", "crate-name", "specify the name of this crate", "NAME")
283 make_crate_type_option(),
285 o.optmulti("L", "library-path", "directory to add to crate search path", "DIR")
287 stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
288 stable("extern", |o| o.optmulti("", "extern", "pass an --extern to rustc", "NAME[=PATH]")),
289 unstable("extern-html-root-url", |o| {
290 o.optmulti("", "extern-html-root-url", "base URL to use for dependencies", "NAME=URL")
292 stable("plugin-path", |o| o.optmulti("", "plugin-path", "removed", "DIR")),
294 o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
296 stable("passes", |o| {
300 "list of passes to also run, you might want to pass it multiple times; a value of \
301 `list` will print available passes",
305 stable("plugins", |o| o.optmulti("", "plugins", "removed", "PLUGINS")),
306 stable("no-default", |o| o.optflag("", "no-defaults", "don't run the default passes")),
307 stable("document-private-items", |o| {
308 o.optflag("", "document-private-items", "document private items")
310 unstable("document-hidden-items", |o| {
311 o.optflag("", "document-hidden-items", "document items that have doc(hidden)")
313 stable("test", |o| o.optflag("", "test", "run code examples as tests")),
314 stable("test-args", |o| {
315 o.optmulti("", "test-args", "arguments to pass to the test runner", "ARGS")
317 unstable("test-run-directory", |o| {
320 "test-run-directory",
321 "The working directory in which to run tests",
325 stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
326 stable("markdown-css", |o| {
330 "CSS files to include via <link> in a rendered Markdown file",
334 stable("html-in-header", |o| {
338 "files to include inline in the <head> section of a rendered Markdown file \
339 or generated documentation",
343 stable("html-before-content", |o| {
346 "html-before-content",
347 "files to include inline between <body> and the content of a rendered \
348 Markdown file or generated documentation",
352 stable("html-after-content", |o| {
355 "html-after-content",
356 "files to include inline between the content and </body> of a rendered \
357 Markdown file or generated documentation",
361 unstable("markdown-before-content", |o| {
364 "markdown-before-content",
365 "files to include inline between <body> and the content of a rendered \
366 Markdown file or generated documentation",
370 unstable("markdown-after-content", |o| {
373 "markdown-after-content",
374 "files to include inline between the content and </body> of a rendered \
375 Markdown file or generated documentation",
379 stable("markdown-playground-url", |o| {
380 o.optopt("", "markdown-playground-url", "URL to send code snippets to", "URL")
382 stable("markdown-no-toc", |o| {
383 o.optflag("", "markdown-no-toc", "don't include table of contents")
389 "To add some CSS rules with a given file to generate doc with your \
390 own theme. However, your theme might break if the rustdoc's generated HTML \
391 changes, so be careful!",
396 o.optmulti("Z", "", "internal and debugging options (only on nightly build)", "FLAG")
398 stable("sysroot", |o| o.optopt("", "sysroot", "Override the system root", "PATH")),
399 unstable("playground-url", |o| {
403 "URL to send code snippets to, may be reset by --markdown-playground-url \
404 or `#![doc(html_playground_url=...)]`",
408 unstable("display-warnings", |o| {
409 o.optflag("", "display-warnings", "to print code warnings when testing doc")
411 stable("crate-version", |o| {
412 o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
414 unstable("sort-modules-by-appearance", |o| {
417 "sort-modules-by-appearance",
418 "sort modules by where they appear in the program, rather than alphabetically",
421 stable("default-theme", |o| {
425 "Set the default theme. THEME should be the theme name, generally lowercase. \
426 If an unknown default theme is specified, the builtin default is used. \
427 The set of themes, and the rustdoc built-in default, are not stable.",
431 unstable("default-setting", |o| {
435 "Default value for a rustdoc setting (used when \"rustdoc-SETTING\" is absent \
436 from web browser Local Storage). If VALUE is not supplied, \"true\" is used. \
437 Supported SETTINGs and VALUEs are not documented and not stable.",
441 stable("theme", |o| {
445 "additional themes which will be added to the generated docs",
449 stable("check-theme", |o| {
450 o.optmulti("", "check-theme", "check if given theme is valid", "FILES")
452 unstable("resource-suffix", |o| {
456 "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
457 \"light-suffix.css\"",
461 stable("edition", |o| {
465 "edition to use when compiling rust code (default: 2015)",
469 stable("color", |o| {
473 "Configure coloring of output:
474 auto = colorize, if output goes to a tty (default);
475 always = always colorize output;
476 never = never colorize output",
480 stable("error-format", |o| {
484 "How errors and other messages are produced",
489 o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
491 unstable("disable-minification", |o| {
492 o.optflag("", "disable-minification", "Disable minification applied on JS files")
494 stable("warn", |o| o.optmulti("W", "warn", "Set lint warnings", "OPT")),
495 stable("allow", |o| o.optmulti("A", "allow", "Set lint allowed", "OPT")),
496 stable("deny", |o| o.optmulti("D", "deny", "Set lint denied", "OPT")),
497 stable("forbid", |o| o.optmulti("F", "forbid", "Set lint forbidden", "OPT")),
498 stable("cap-lints", |o| {
502 "Set the most restrictive lint level. \
503 More restrictive lints are capped at this \
504 level. By default, it is at `forbid` level.",
508 unstable("index-page", |o| {
509 o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
511 unstable("enable-index-page", |o| {
512 o.optflag("", "enable-index-page", "To enable generation of the index page")
514 unstable("static-root-path", |o| {
518 "Path string to force loading static files from in output pages. \
519 If not set, uses combinations of '../' to reach the documentation root.",
523 unstable("disable-per-crate-search", |o| {
526 "disable-per-crate-search",
527 "disables generating the crate selector on the search box",
530 unstable("persist-doctests", |o| {
534 "Directory to persist doctest executables into",
538 unstable("show-coverage", |o| {
542 "calculate percentage of public items with documentation",
545 unstable("enable-per-target-ignores", |o| {
548 "enable-per-target-ignores",
549 "parse ignore-foo for ignoring doctests on a per-target basis",
552 unstable("runtool", |o| {
557 "The tool to run tests with when building for a different target than host",
560 unstable("runtool-arg", |o| {
565 "One (of possibly many) arguments to pass to the runtool",
568 unstable("test-builder", |o| {
569 o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH")
571 unstable("check", |o| o.optflag("", "check", "Run rustdoc checks")),
572 unstable("generate-redirect-map", |o| {
575 "generate-redirect-map",
576 "Generate JSON file at the top level instead of generating HTML redirection files",
579 unstable("print", |o| {
580 o.optmulti("", "print", "Rustdoc information to print on stdout", "[unversioned-files]")
582 unstable("emit", |o| {
586 "Comma separated list of types of output for rustdoc to emit",
587 "[unversioned-shared-resources,toolchain-shared-resources,invocation-specific]",
593 fn usage(argv0: &str) {
594 let mut options = getopts::Options::new();
595 for option in opts() {
596 (option.apply)(&mut options);
598 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
599 println!(" @path Read newline separated options from `path`\n");
600 println!("More information available at https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html")
603 /// A result type used by several functions under `main()`.
604 type MainResult = Result<(), ErrorReported>;
606 fn main_args(at_args: &[String]) -> MainResult {
607 let args = rustc_driver::args::arg_expand_all(at_args);
609 let mut options = getopts::Options::new();
610 for option in opts() {
611 (option.apply)(&mut options);
613 let matches = match options.parse(&args[1..]) {
616 early_error(ErrorOutputType::default(), &err.to_string());
620 // Note that we discard any distinction between different non-zero exit
621 // codes from `from_matches` here.
622 let options = match config::Options::from_matches(&matches) {
624 Err(code) => return if code == 0 { Ok(()) } else { Err(ErrorReported) },
626 rustc_interface::util::setup_callbacks_and_run_in_thread_pool_with_globals(
628 1, // this runs single-threaded, even in a parallel compiler
630 move || main_options(options),
634 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
638 diag.struct_err(&err).emit();
644 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
646 renderopts: config::RenderOptions,
647 cache: formats::cache::Cache,
648 diag: &rustc_errors::Handler,
649 edition: rustc_span::edition::Edition,
652 match formats::run_format::<T>(krate, renderopts, cache, &diag, edition, tcx) {
655 let mut msg = diag.struct_err(&format!("couldn't generate documentation: {}", e.error));
656 let file = e.file.display().to_string();
660 msg.note(&format!("failed to create or modify \"{}\"", file)).emit()
667 fn main_options(options: config::Options) -> MainResult {
668 let diag = core::new_handler(options.error_format, None, &options.debugging_opts);
670 match (options.should_test, options.markdown_input()) {
671 (true, true) => return wrap_return(&diag, markdown::test(options)),
672 (true, false) => return doctest::run(options),
676 markdown::render(&options.input, options.render_options, options.edition),
682 // need to move these items separately because we lose them by the time the closure is called,
683 // but we can't create the Handler ahead of time because it's not Send
684 let diag_opts = (options.error_format, options.edition, options.debugging_opts.clone());
685 let show_coverage = options.show_coverage;
686 let run_check = options.run_check;
688 // First, parse the crate and extract all relevant information.
689 info!("starting to run rustc");
691 // Interpret the input file as a rust source file, passing it through the
692 // compiler all the way through the analysis passes. The rustdoc output is
693 // then generated from the cleaned AST of the crate. This runs all the
694 // plug/cleaning passes.
695 let crate_version = options.crate_version.clone();
697 let default_passes = options.default_passes;
698 let output_format = options.output_format;
699 // FIXME: fix this clone (especially render_options)
700 let manual_passes = options.manual_passes.clone();
701 let render_options = options.render_options.clone();
702 let config = core::create_config(options);
704 interface::create_compiler_and_run(config, |compiler| {
705 compiler.enter(|queries| {
706 let sess = compiler.session();
708 if sess.opts.describe_lints {
709 let (_, lint_store) = &*queries.register_plugins()?.peek();
710 describe_lints(sess, lint_store, true);
714 // We need to hold on to the complete resolver, so we cause everything to be
715 // cloned for the analysis passes to use. Suboptimal, but necessary in the
716 // current architecture.
717 let resolver = core::create_resolver(queries, &sess);
719 if sess.has_errors() {
720 sess.fatal("Compilation failed, aborting rustdoc");
723 let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).peek_mut();
725 global_ctxt.enter(|tcx| {
726 let (krate, render_opts, mut cache) = sess.time("run_global_ctxt", || {
727 core::run_global_ctxt(
736 info!("finished with rustc");
738 cache.crate_version = crate_version;
741 // if we ran coverage, bail early, we don't need to also generate docs at this point
742 // (also we didn't load in any of the useful passes)
744 } else if run_check {
745 // Since we're in "check" mode, no need to generate anything beyond this point.
749 info!("going to format");
750 let (error_format, edition, debugging_options) = diag_opts;
751 let diag = core::new_handler(error_format, None, &debugging_options);
752 match output_format {
753 config::OutputFormat::Html => sess.time("render_html", || {
754 run_renderer::<html::render::Context<'_>>(
763 config::OutputFormat::Json => sess.time("render_json", || {
764 run_renderer::<json::JsonRenderer<'_>>(