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 use crate::clean::utils::doc_rust_lang_org_channel;
87 /// A macro to create a FxHashMap.
92 /// let letters = map!{"a" => "b", "c" => "d"};
95 /// Trailing commas are allowed.
96 /// Commas between elements are required (even if the expression is a block).
98 ($( $key: expr => $val: expr ),* $(,)*) => {{
99 let mut map = ::rustc_data_structures::fx::FxHashMap::default();
100 $( map.insert($key, $val); )*
118 // used by the error-index generator, so it needs to be public
128 // See docs in https://github.com/rust-lang/rust/blob/master/compiler/rustc/src/main.rs
129 // about jemallocator
130 #[cfg(feature = "jemalloc")]
132 static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
135 // See docs in https://github.com/rust-lang/rust/blob/master/compiler/rustc/src/main.rs
136 // about jemalloc-sys
137 #[cfg(feature = "jemalloc")]
139 use std::os::raw::{c_int, c_void};
142 static _F1: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::calloc;
144 static _F2: unsafe extern "C" fn(*mut *mut c_void, usize, usize) -> c_int =
145 jemalloc_sys::posix_memalign;
147 static _F3: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::aligned_alloc;
149 static _F4: unsafe extern "C" fn(usize) -> *mut c_void = jemalloc_sys::malloc;
151 static _F5: unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void = jemalloc_sys::realloc;
153 static _F6: unsafe extern "C" fn(*mut c_void) = jemalloc_sys::free;
155 // On OSX, jemalloc doesn't directly override malloc/free, but instead
156 // registers itself with the allocator's zone APIs in a ctor. However,
157 // the linker doesn't seem to consider ctors as "used" when statically
158 // linking, so we need to explicitly depend on the function.
159 #[cfg(target_os = "macos")]
162 fn _rjem_je_zone_register();
166 static _F7: unsafe extern "C" fn() = _rjem_je_zone_register;
170 rustc_driver::set_sigpipe_handler();
171 rustc_driver::install_ice_hook();
173 // When using CI artifacts (with `download_stage1 = true`), tracing is unconditionally built
174 // with `--features=static_max_level_info`, which disables almost all rustdoc logging. To avoid
175 // this, compile our own version of `tracing` that logs all levels.
176 // NOTE: this compiles both versions of tracing unconditionally, because
177 // - The compile time hit is not that bad, especially compared to rustdoc's incremental times, and
178 // - Otherwise, there's no warning that logging is being ignored when `download_stage1 = true`.
179 // NOTE: The reason this doesn't show double logging when `download_stage1 = false` and
180 // `debug_logging = true` is because all rustc logging goes to its version of tracing (the one
181 // in the sysroot), and all of rustdoc's logging goes to its version (the one in Cargo.toml).
183 rustc_driver::init_env_logger("RUSTDOC_LOG");
185 let exit_code = rustc_driver::catch_with_exit_code(|| match get_args() {
186 Some(args) => main_args(&args),
187 _ => Err(ErrorReported),
189 process::exit(exit_code);
195 // FIXME remove these and use winapi 0.3 instead
196 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs, rustc_driver/lib.rs
198 fn stdout_isatty() -> bool {
200 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
204 fn stdout_isatty() -> bool {
206 use winapi::um::consoleapi::GetConsoleMode;
207 use winapi::um::processenv::GetStdHandle;
208 use winapi::um::winbase::STD_OUTPUT_HANDLE;
211 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
213 GetConsoleMode(handle, &mut out) != 0
217 let color_logs = match std::env::var("RUSTDOC_LOG_COLOR") {
218 Ok(value) => match value.as_ref() {
221 "auto" => stdout_isatty(),
223 ErrorOutputType::default(),
225 "invalid log color value '{}': expected one of always, never, or auto",
230 Err(std::env::VarError::NotPresent) => stdout_isatty(),
231 Err(std::env::VarError::NotUnicode(_value)) => early_error(
232 ErrorOutputType::default(),
233 "non-Unicode log color value: expected one of always, never, or auto",
236 let filter = tracing_subscriber::EnvFilter::from_env("RUSTDOC_LOG");
237 let layer = tracing_tree::HierarchicalLayer::default()
238 .with_writer(io::stderr)
239 .with_indent_lines(true)
240 .with_ansi(color_logs)
243 .with_verbose_exit(true)
244 .with_verbose_entry(true)
245 .with_indent_amount(2);
246 #[cfg(parallel_compiler)]
247 let layer = layer.with_thread_ids(true).with_thread_names(true);
249 use tracing_subscriber::layer::SubscriberExt;
250 let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
251 tracing::subscriber::set_global_default(subscriber).unwrap();
254 fn get_args() -> Option<Vec<String>> {
261 ErrorOutputType::default(),
262 &format!("Argument {} is not valid Unicode: {:?}", i, arg),
270 fn opts() -> Vec<RustcOptGroup> {
271 let stable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::stable;
272 let unstable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::unstable;
274 stable("h", |o| o.optflag("h", "help", "show this help message")),
275 stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
276 stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
278 o.optopt("r", "input-format", "the input type of the specified file", "[rust]")
280 stable("w", |o| o.optopt("w", "output-format", "the output type to write", "[html]")),
281 stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
282 stable("crate-name", |o| {
283 o.optopt("", "crate-name", "specify the name of this crate", "NAME")
285 make_crate_type_option(),
287 o.optmulti("L", "library-path", "directory to add to crate search path", "DIR")
289 stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
290 stable("extern", |o| o.optmulti("", "extern", "pass an --extern to rustc", "NAME[=PATH]")),
291 unstable("extern-html-root-url", |o| {
294 "extern-html-root-url",
295 "base URL to use for dependencies; for example, \
296 \"std=/doc\" links std::vec::Vec to /doc/std/vec/struct.Vec.html",
300 stable("plugin-path", |o| o.optmulti("", "plugin-path", "removed", "DIR")),
302 o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
304 stable("passes", |o| {
308 "list of passes to also run, you might want to pass it multiple times; a value of \
309 `list` will print available passes",
313 stable("plugins", |o| o.optmulti("", "plugins", "removed", "PLUGINS")),
314 stable("no-default", |o| o.optflag("", "no-defaults", "don't run the default passes")),
315 stable("document-private-items", |o| {
316 o.optflag("", "document-private-items", "document private items")
318 unstable("document-hidden-items", |o| {
319 o.optflag("", "document-hidden-items", "document items that have doc(hidden)")
321 stable("test", |o| o.optflag("", "test", "run code examples as tests")),
322 stable("test-args", |o| {
323 o.optmulti("", "test-args", "arguments to pass to the test runner", "ARGS")
325 unstable("test-run-directory", |o| {
328 "test-run-directory",
329 "The working directory in which to run tests",
333 stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
334 stable("markdown-css", |o| {
338 "CSS files to include via <link> in a rendered Markdown file",
342 stable("html-in-header", |o| {
346 "files to include inline in the <head> section of a rendered Markdown file \
347 or generated documentation",
351 stable("html-before-content", |o| {
354 "html-before-content",
355 "files to include inline between <body> and the content of a rendered \
356 Markdown file or generated documentation",
360 stable("html-after-content", |o| {
363 "html-after-content",
364 "files to include inline between the content and </body> of a rendered \
365 Markdown file or generated documentation",
369 unstable("markdown-before-content", |o| {
372 "markdown-before-content",
373 "files to include inline between <body> and the content of a rendered \
374 Markdown file or generated documentation",
378 unstable("markdown-after-content", |o| {
381 "markdown-after-content",
382 "files to include inline between the content and </body> of a rendered \
383 Markdown file or generated documentation",
387 stable("markdown-playground-url", |o| {
388 o.optopt("", "markdown-playground-url", "URL to send code snippets to", "URL")
390 stable("markdown-no-toc", |o| {
391 o.optflag("", "markdown-no-toc", "don't include table of contents")
397 "To add some CSS rules with a given file to generate doc with your \
398 own theme. However, your theme might break if the rustdoc's generated HTML \
399 changes, so be careful!",
404 o.optmulti("Z", "", "internal and debugging options (only on nightly build)", "FLAG")
406 stable("sysroot", |o| o.optopt("", "sysroot", "Override the system root", "PATH")),
407 unstable("playground-url", |o| {
411 "URL to send code snippets to, may be reset by --markdown-playground-url \
412 or `#![doc(html_playground_url=...)]`",
416 unstable("display-warnings", |o| {
417 o.optflag("", "display-warnings", "to print code warnings when testing doc")
419 stable("crate-version", |o| {
420 o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
422 unstable("sort-modules-by-appearance", |o| {
425 "sort-modules-by-appearance",
426 "sort modules by where they appear in the program, rather than alphabetically",
429 stable("default-theme", |o| {
433 "Set the default theme. THEME should be the theme name, generally lowercase. \
434 If an unknown default theme is specified, the builtin default is used. \
435 The set of themes, and the rustdoc built-in default, are not stable.",
439 unstable("default-setting", |o| {
443 "Default value for a rustdoc setting (used when \"rustdoc-SETTING\" is absent \
444 from web browser Local Storage). If VALUE is not supplied, \"true\" is used. \
445 Supported SETTINGs and VALUEs are not documented and not stable.",
449 stable("theme", |o| {
453 "additional themes which will be added to the generated docs",
457 stable("check-theme", |o| {
458 o.optmulti("", "check-theme", "check if given theme is valid", "FILES")
460 unstable("resource-suffix", |o| {
464 "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
465 \"light-suffix.css\"",
469 stable("edition", |o| {
473 "edition to use when compiling rust code (default: 2015)",
477 stable("color", |o| {
481 "Configure coloring of output:
482 auto = colorize, if output goes to a tty (default);
483 always = always colorize output;
484 never = never colorize output",
488 stable("error-format", |o| {
492 "How errors and other messages are produced",
497 o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
499 unstable("disable-minification", |o| {
500 o.optflag("", "disable-minification", "Disable minification applied on JS files")
502 stable("warn", |o| o.optmulti("W", "warn", "Set lint warnings", "OPT")),
503 stable("allow", |o| o.optmulti("A", "allow", "Set lint allowed", "OPT")),
504 stable("deny", |o| o.optmulti("D", "deny", "Set lint denied", "OPT")),
505 stable("forbid", |o| o.optmulti("F", "forbid", "Set lint forbidden", "OPT")),
506 stable("cap-lints", |o| {
510 "Set the most restrictive lint level. \
511 More restrictive lints are capped at this \
512 level. By default, it is at `forbid` level.",
516 unstable("index-page", |o| {
517 o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
519 unstable("enable-index-page", |o| {
520 o.optflag("", "enable-index-page", "To enable generation of the index page")
522 unstable("static-root-path", |o| {
526 "Path string to force loading static files from in output pages. \
527 If not set, uses combinations of '../' to reach the documentation root.",
531 unstable("disable-per-crate-search", |o| {
534 "disable-per-crate-search",
535 "disables generating the crate selector on the search box",
538 unstable("persist-doctests", |o| {
542 "Directory to persist doctest executables into",
546 unstable("show-coverage", |o| {
550 "calculate percentage of public items with documentation",
553 unstable("enable-per-target-ignores", |o| {
556 "enable-per-target-ignores",
557 "parse ignore-foo for ignoring doctests on a per-target basis",
560 unstable("runtool", |o| {
565 "The tool to run tests with when building for a different target than host",
568 unstable("runtool-arg", |o| {
573 "One (of possibly many) arguments to pass to the runtool",
576 unstable("test-builder", |o| {
577 o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH")
579 unstable("check", |o| o.optflag("", "check", "Run rustdoc checks")),
580 unstable("generate-redirect-map", |o| {
583 "generate-redirect-map",
584 "Generate JSON file at the top level instead of generating HTML redirection files",
587 unstable("print", |o| {
588 o.optmulti("", "print", "Rustdoc information to print on stdout", "[unversioned-files]")
590 unstable("emit", |o| {
594 "Comma separated list of types of output for rustdoc to emit",
595 "[unversioned-shared-resources,toolchain-shared-resources,invocation-specific]",
601 fn usage(argv0: &str) {
602 let mut options = getopts::Options::new();
603 for option in opts() {
604 (option.apply)(&mut options);
606 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
607 println!(" @path Read newline separated options from `path`\n");
609 "More information available at https://doc.rust-lang.org/{}/rustdoc/what-is-rustdoc.html",
610 doc_rust_lang_org_channel()
614 /// A result type used by several functions under `main()`.
615 type MainResult = Result<(), ErrorReported>;
617 fn main_args(at_args: &[String]) -> MainResult {
618 let args = rustc_driver::args::arg_expand_all(at_args);
620 let mut options = getopts::Options::new();
621 for option in opts() {
622 (option.apply)(&mut options);
624 let matches = match options.parse(&args[1..]) {
627 early_error(ErrorOutputType::default(), &err.to_string());
631 // Note that we discard any distinction between different non-zero exit
632 // codes from `from_matches` here.
633 let options = match config::Options::from_matches(&matches) {
635 Err(code) => return if code == 0 { Ok(()) } else { Err(ErrorReported) },
637 rustc_interface::util::setup_callbacks_and_run_in_thread_pool_with_globals(
639 1, // this runs single-threaded, even in a parallel compiler
641 move || main_options(options),
645 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
649 diag.struct_err(&err).emit();
655 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
657 renderopts: config::RenderOptions,
658 cache: formats::cache::Cache,
661 match formats::run_format::<T>(krate, renderopts, cache, tcx) {
665 tcx.sess.struct_err(&format!("couldn't generate documentation: {}", e.error));
666 let file = e.file.display().to_string();
670 msg.note(&format!("failed to create or modify \"{}\"", file)).emit()
677 fn main_options(options: config::Options) -> MainResult {
678 let diag = core::new_handler(options.error_format, None, &options.debugging_opts);
680 match (options.should_test, options.markdown_input()) {
681 (true, true) => return wrap_return(&diag, markdown::test(options)),
682 (true, false) => return doctest::run(options),
686 markdown::render(&options.input, options.render_options, options.edition),
692 // need to move these items separately because we lose them by the time the closure is called,
693 // but we can't create the Handler ahead of time because it's not Send
694 let show_coverage = options.show_coverage;
695 let run_check = options.run_check;
697 // First, parse the crate and extract all relevant information.
698 info!("starting to run rustc");
700 // Interpret the input file as a rust source file, passing it through the
701 // compiler all the way through the analysis passes. The rustdoc output is
702 // then generated from the cleaned AST of the crate. This runs all the
703 // plug/cleaning passes.
704 let crate_version = options.crate_version.clone();
706 let default_passes = options.default_passes;
707 let output_format = options.output_format;
708 // FIXME: fix this clone (especially render_options)
709 let manual_passes = options.manual_passes.clone();
710 let render_options = options.render_options.clone();
711 let config = core::create_config(options);
713 interface::create_compiler_and_run(config, |compiler| {
714 compiler.enter(|queries| {
715 let sess = compiler.session();
717 if sess.opts.describe_lints {
718 let (_, lint_store) = &*queries.register_plugins()?.peek();
719 describe_lints(sess, lint_store, true);
723 // We need to hold on to the complete resolver, so we cause everything to be
724 // cloned for the analysis passes to use. Suboptimal, but necessary in the
725 // current architecture.
726 let resolver = core::create_resolver(queries, &sess);
728 if sess.has_errors() {
729 sess.fatal("Compilation failed, aborting rustdoc");
732 let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).peek_mut();
734 global_ctxt.enter(|tcx| {
735 let (krate, render_opts, mut cache) = sess.time("run_global_ctxt", || {
736 core::run_global_ctxt(
745 info!("finished with rustc");
747 cache.crate_version = crate_version;
750 // if we ran coverage, bail early, we don't need to also generate docs at this point
751 // (also we didn't load in any of the useful passes)
753 } else if run_check {
754 // Since we're in "check" mode, no need to generate anything beyond this point.
758 info!("going to format");
759 match output_format {
760 config::OutputFormat::Html => sess.time("render_html", || {
761 run_renderer::<html::render::Context<'_>>(krate, render_opts, cache, tcx)
763 config::OutputFormat::Json => sess.time("render_json", || {
764 run_renderer::<json::JsonRenderer<'_>>(krate, render_opts, cache, tcx)