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(assert_matches)]
8 #![feature(bool_to_option)]
9 #![feature(box_patterns)]
10 #![feature(control_flow_enum)]
11 #![feature(box_syntax)]
15 #![feature(crate_visibility_modifier)]
16 #![feature(never_type)]
17 #![feature(once_cell)]
18 #![feature(type_ascription)]
19 #![feature(iter_intersperse)]
20 #![feature(type_alias_impl_trait)]
21 #![feature(generic_associated_types)]
22 #![recursion_limit = "256"]
23 #![warn(rustc::internal)]
24 #![allow(clippy::collapsible_if, clippy::collapsible_else_if)]
25 #![allow(rustc::potential_query_instability)]
30 // N.B. these need `extern crate` even in 2018 edition
31 // because they're loaded implicitly from the sysroot.
32 // The reason they're loaded from the sysroot is because
33 // the rustdoc artifacts aren't stored in rustc's cargo target directory.
34 // So if `rustc` was specified in Cargo.toml, this would spuriously rebuild crates.
36 // Dependencies listed in Cargo.toml do not need `extern crate`.
38 extern crate rustc_ast;
39 extern crate rustc_ast_lowering;
40 extern crate rustc_ast_pretty;
41 extern crate rustc_attr;
42 extern crate rustc_const_eval;
43 extern crate rustc_data_structures;
44 extern crate rustc_driver;
45 extern crate rustc_errors;
46 extern crate rustc_expand;
47 extern crate rustc_feature;
48 extern crate rustc_hir;
49 extern crate rustc_hir_pretty;
50 extern crate rustc_index;
51 extern crate rustc_infer;
52 extern crate rustc_interface;
53 extern crate rustc_lexer;
54 extern crate rustc_lint;
55 extern crate rustc_lint_defs;
56 extern crate rustc_macros;
57 extern crate rustc_metadata;
58 extern crate rustc_middle;
59 extern crate rustc_parse;
60 extern crate rustc_passes;
61 extern crate rustc_resolve;
62 extern crate rustc_serialize;
63 extern crate rustc_session;
64 extern crate rustc_span;
65 extern crate rustc_target;
66 extern crate rustc_trait_selection;
67 extern crate rustc_typeck;
70 // See docs in https://github.com/rust-lang/rust/blob/master/compiler/rustc/src/main.rs
72 #[cfg(feature = "jemalloc")]
73 extern crate tikv_jemalloc_sys;
74 #[cfg(feature = "jemalloc")]
75 use tikv_jemalloc_sys as jemalloc_sys;
77 use std::default::Default;
78 use std::env::{self, VarError};
82 use rustc_driver::{abort_on_err, describe_lints};
83 use rustc_errors::ErrorGuaranteed;
84 use rustc_interface::interface;
85 use rustc_middle::ty::TyCtxt;
86 use rustc_session::config::{make_crate_type_option, ErrorOutputType, RustcOptGroup};
87 use rustc_session::getopts;
88 use rustc_session::{early_error, early_warn};
90 use crate::clean::utils::DOC_RUST_LANG_ORG_CHANNEL;
91 use crate::passes::collect_intra_doc_links;
93 /// A macro to create a FxHashMap.
98 /// let letters = map!{"a" => "b", "c" => "d"};
101 /// Trailing commas are allowed.
102 /// Commas between elements are required (even if the expression is a block).
104 ($( $key: expr => $val: expr ),* $(,)*) => {{
105 let mut map = ::rustc_data_structures::fx::FxHashMap::default();
106 $( map.insert($key, $val); )*
120 // used by the error-index generator, so it needs to be public
133 // See docs in https://github.com/rust-lang/rust/blob/master/compiler/rustc/src/main.rs
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 #[cfg(target_os = "macos")]
156 fn _rjem_je_zone_register();
160 static _F7: unsafe extern "C" fn() = _rjem_je_zone_register;
164 rustc_driver::set_sigpipe_handler();
165 rustc_driver::install_ice_hook();
167 // When using CI artifacts (with `download_stage1 = true`), tracing is unconditionally built
168 // with `--features=static_max_level_info`, which disables almost all rustdoc logging. To avoid
169 // this, compile our own version of `tracing` that logs all levels.
170 // NOTE: this compiles both versions of tracing unconditionally, because
171 // - The compile time hit is not that bad, especially compared to rustdoc's incremental times, and
172 // - Otherwise, there's no warning that logging is being ignored when `download_stage1 = true`.
173 // NOTE: The reason this doesn't show double logging when `download_stage1 = false` and
174 // `debug_logging = true` is because all rustc logging goes to its version of tracing (the one
175 // in the sysroot), and all of rustdoc's logging goes to its version (the one in Cargo.toml).
177 rustc_driver::init_env_logger("RUSTDOC_LOG");
179 let exit_code = rustc_driver::catch_with_exit_code(|| match get_args() {
180 Some(args) => main_args(&args),
181 _ => Err(ErrorGuaranteed),
183 process::exit(exit_code);
187 let color_logs = match std::env::var("RUSTDOC_LOG_COLOR").as_deref() {
188 Ok("always") => true,
189 Ok("never") => false,
190 Ok("auto") | Err(VarError::NotPresent) => atty::is(atty::Stream::Stdout),
191 Ok(value) => early_error(
192 ErrorOutputType::default(),
193 &format!("invalid log color value '{}': expected one of always, never, or auto", value),
195 Err(VarError::NotUnicode(value)) => early_error(
196 ErrorOutputType::default(),
198 "invalid log color value '{}': expected one of always, never, or auto",
199 value.to_string_lossy()
203 let filter = tracing_subscriber::EnvFilter::from_env("RUSTDOC_LOG");
204 let layer = tracing_tree::HierarchicalLayer::default()
205 .with_writer(io::stderr)
206 .with_indent_lines(true)
207 .with_ansi(color_logs)
210 .with_verbose_exit(true)
211 .with_verbose_entry(true)
212 .with_indent_amount(2);
213 #[cfg(parallel_compiler)]
214 let layer = layer.with_thread_ids(true).with_thread_names(true);
216 use tracing_subscriber::layer::SubscriberExt;
217 let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
218 tracing::subscriber::set_global_default(subscriber).unwrap();
221 fn get_args() -> Option<Vec<String>> {
228 ErrorOutputType::default(),
229 &format!("Argument {} is not valid Unicode: {:?}", i, arg),
237 fn opts() -> Vec<RustcOptGroup> {
238 let stable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::stable;
239 let unstable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::unstable;
241 stable("h", |o| o.optflagmulti("h", "help", "show this help message")),
242 stable("V", |o| o.optflagmulti("V", "version", "print rustdoc's version")),
243 stable("v", |o| o.optflagmulti("v", "verbose", "use verbose output")),
244 stable("w", |o| o.optopt("w", "output-format", "the output type to write", "[html]")),
245 stable("output", |o| {
249 "Which directory to place the output. \
250 This option is deprecated, use --out-dir instead.",
254 stable("o", |o| o.optopt("o", "out-dir", "which directory to place the output", "PATH")),
255 stable("crate-name", |o| {
256 o.optopt("", "crate-name", "specify the name of this crate", "NAME")
258 make_crate_type_option(),
260 o.optmulti("L", "library-path", "directory to add to crate search path", "DIR")
262 stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
263 unstable("check-cfg", |o| o.optmulti("", "check-cfg", "pass a --check-cfg to rustc", "")),
264 stable("extern", |o| o.optmulti("", "extern", "pass an --extern to rustc", "NAME[=PATH]")),
265 unstable("extern-html-root-url", |o| {
268 "extern-html-root-url",
269 "base URL to use for dependencies; for example, \
270 \"std=/doc\" links std::vec::Vec to /doc/std/vec/struct.Vec.html",
274 unstable("extern-html-root-takes-precedence", |o| {
277 "extern-html-root-takes-precedence",
278 "give precedence to `--extern-html-root-url`, not `html_root_url`",
282 o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
284 stable("document-private-items", |o| {
285 o.optflagmulti("", "document-private-items", "document private items")
287 unstable("document-hidden-items", |o| {
288 o.optflagmulti("", "document-hidden-items", "document items that have doc(hidden)")
290 stable("test", |o| o.optflagmulti("", "test", "run code examples as tests")),
291 stable("test-args", |o| {
292 o.optmulti("", "test-args", "arguments to pass to the test runner", "ARGS")
294 unstable("test-run-directory", |o| {
297 "test-run-directory",
298 "The working directory in which to run tests",
302 stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
303 stable("markdown-css", |o| {
307 "CSS files to include via <link> in a rendered Markdown file",
311 stable("html-in-header", |o| {
315 "files to include inline in the <head> section of a rendered Markdown file \
316 or generated documentation",
320 stable("html-before-content", |o| {
323 "html-before-content",
324 "files to include inline between <body> and the content of a rendered \
325 Markdown file or generated documentation",
329 stable("html-after-content", |o| {
332 "html-after-content",
333 "files to include inline between the content and </body> of a rendered \
334 Markdown file or generated documentation",
338 unstable("markdown-before-content", |o| {
341 "markdown-before-content",
342 "files to include inline between <body> and the content of a rendered \
343 Markdown file or generated documentation",
347 unstable("markdown-after-content", |o| {
350 "markdown-after-content",
351 "files to include inline between the content and </body> of a rendered \
352 Markdown file or generated documentation",
356 stable("markdown-playground-url", |o| {
357 o.optopt("", "markdown-playground-url", "URL to send code snippets to", "URL")
359 stable("markdown-no-toc", |o| {
360 o.optflagmulti("", "markdown-no-toc", "don't include table of contents")
366 "To add some CSS rules with a given file to generate doc with your \
367 own theme. However, your theme might break if the rustdoc's generated HTML \
368 changes, so be careful!",
373 o.optmulti("Z", "", "internal and debugging options (only on nightly build)", "FLAG")
375 stable("sysroot", |o| o.optopt("", "sysroot", "Override the system root", "PATH")),
376 unstable("playground-url", |o| {
380 "URL to send code snippets to, may be reset by --markdown-playground-url \
381 or `#![doc(html_playground_url=...)]`",
385 unstable("display-doctest-warnings", |o| {
388 "display-doctest-warnings",
389 "show warnings that originate in doctests",
392 stable("crate-version", |o| {
393 o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
395 unstable("sort-modules-by-appearance", |o| {
398 "sort-modules-by-appearance",
399 "sort modules by where they appear in the program, rather than alphabetically",
402 stable("default-theme", |o| {
406 "Set the default theme. THEME should be the theme name, generally lowercase. \
407 If an unknown default theme is specified, the builtin default is used. \
408 The set of themes, and the rustdoc built-in default, are not stable.",
412 unstable("default-setting", |o| {
416 "Default value for a rustdoc setting (used when \"rustdoc-SETTING\" is absent \
417 from web browser Local Storage). If VALUE is not supplied, \"true\" is used. \
418 Supported SETTINGs and VALUEs are not documented and not stable.",
422 stable("theme", |o| {
426 "additional themes which will be added to the generated docs",
430 stable("check-theme", |o| {
431 o.optmulti("", "check-theme", "check if given theme is valid", "FILES")
433 unstable("resource-suffix", |o| {
437 "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
438 \"light-suffix.css\"",
442 stable("edition", |o| {
446 "edition to use when compiling rust code (default: 2015)",
450 stable("color", |o| {
454 "Configure coloring of output:
455 auto = colorize, if output goes to a tty (default);
456 always = always colorize output;
457 never = never colorize output",
461 stable("error-format", |o| {
465 "How errors and other messages are produced",
470 o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
472 unstable("disable-minification", |o| {
473 o.optflagmulti("", "disable-minification", "Disable minification applied on JS files")
475 stable("allow", |o| o.optmulti("A", "allow", "Set lint allowed", "LINT")),
476 stable("warn", |o| o.optmulti("W", "warn", "Set lint warnings", "LINT")),
477 stable("force-warn", |o| o.optmulti("", "force-warn", "Set lint force-warn", "LINT")),
478 stable("deny", |o| o.optmulti("D", "deny", "Set lint denied", "LINT")),
479 stable("forbid", |o| o.optmulti("F", "forbid", "Set lint forbidden", "LINT")),
480 stable("cap-lints", |o| {
484 "Set the most restrictive lint level. \
485 More restrictive lints are capped at this \
486 level. By default, it is at `forbid` level.",
490 unstable("index-page", |o| {
491 o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
493 unstable("enable-index-page", |o| {
494 o.optflagmulti("", "enable-index-page", "To enable generation of the index page")
496 unstable("static-root-path", |o| {
500 "Path string to force loading static files from in output pages. \
501 If not set, uses combinations of '../' to reach the documentation root.",
505 unstable("disable-per-crate-search", |o| {
508 "disable-per-crate-search",
509 "disables generating the crate selector on the search box",
512 unstable("persist-doctests", |o| {
516 "Directory to persist doctest executables into",
520 unstable("show-coverage", |o| {
524 "calculate percentage of public items with documentation",
527 unstable("enable-per-target-ignores", |o| {
530 "enable-per-target-ignores",
531 "parse ignore-foo for ignoring doctests on a per-target basis",
534 unstable("runtool", |o| {
539 "The tool to run tests with when building for a different target than host",
542 unstable("runtool-arg", |o| {
547 "One (of possibly many) arguments to pass to the runtool",
550 unstable("test-builder", |o| {
551 o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH")
553 unstable("check", |o| o.optflagmulti("", "check", "Run rustdoc checks")),
554 unstable("generate-redirect-map", |o| {
557 "generate-redirect-map",
558 "Generate JSON file at the top level instead of generating HTML redirection files",
561 unstable("emit", |o| {
565 "Comma separated list of types of output for rustdoc to emit",
566 "[unversioned-shared-resources,toolchain-shared-resources,invocation-specific]",
569 unstable("no-run", |o| {
570 o.optflagmulti("", "no-run", "Compile doctests without running them")
572 unstable("show-type-layout", |o| {
573 o.optflagmulti("", "show-type-layout", "Include the memory layout of types in the docs")
575 unstable("nocapture", |o| {
576 o.optflag("", "nocapture", "Don't capture stdout and stderr of tests")
578 unstable("generate-link-to-definition", |o| {
581 "generate-link-to-definition",
582 "Make the identifiers in the HTML source code pages navigable",
585 unstable("scrape-examples-output-path", |o| {
588 "scrape-examples-output-path",
590 "collect function call information and output at the given path",
593 unstable("scrape-examples-target-crate", |o| {
596 "scrape-examples-target-crate",
598 "collect function call information for functions from the target crate",
601 unstable("scrape-tests", |o| {
602 o.optflag("", "scrape-tests", "Include test code when scraping examples")
604 unstable("with-examples", |o| {
609 "path to function call information (for displaying examples in the documentation)",
612 // deprecated / removed options
613 stable("plugin-path", |o| {
617 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
618 for more information",
622 stable("passes", |o| {
626 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
627 for more information",
631 stable("plugins", |o| {
635 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
636 for more information",
640 stable("no-default", |o| {
644 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
645 for more information",
652 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
653 for more information",
660 fn usage(argv0: &str) {
661 let mut options = getopts::Options::new();
662 for option in opts() {
663 (option.apply)(&mut options);
665 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
666 println!(" @path Read newline separated options from `path`\n");
668 "More information available at {}/rustdoc/what-is-rustdoc.html",
669 DOC_RUST_LANG_ORG_CHANNEL
673 /// A result type used by several functions under `main()`.
674 type MainResult = Result<(), ErrorGuaranteed>;
676 fn main_args(at_args: &[String]) -> MainResult {
677 let args = rustc_driver::args::arg_expand_all(at_args);
679 let mut options = getopts::Options::new();
680 for option in opts() {
681 (option.apply)(&mut options);
683 let matches = match options.parse(&args[1..]) {
686 early_error(ErrorOutputType::default(), &err.to_string());
690 // Note that we discard any distinction between different non-zero exit
691 // codes from `from_matches` here.
692 let options = match config::Options::from_matches(&matches) {
694 Err(code) => return if code == 0 { Ok(()) } else { Err(ErrorGuaranteed) },
696 rustc_interface::util::run_in_thread_pool_with_globals(
698 1, // this runs single-threaded, even in a parallel compiler
699 move || main_options(options),
703 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
707 diag.struct_err(&err).emit();
713 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
715 renderopts: config::RenderOptions,
716 cache: formats::cache::Cache,
719 match formats::run_format::<T>(krate, renderopts, cache, tcx) {
723 tcx.sess.struct_err(&format!("couldn't generate documentation: {}", e.error));
724 let file = e.file.display().to_string();
725 if !file.is_empty() {
726 msg.note(&format!("failed to create or modify \"{}\"", file));
733 fn main_options(options: config::Options) -> MainResult {
734 let diag = core::new_handler(options.error_format, None, &options.debugging_opts);
736 match (options.should_test, options.markdown_input()) {
737 (true, true) => return wrap_return(&diag, markdown::test(options)),
738 (true, false) => return doctest::run(options),
742 markdown::render(&options.input, options.render_options, options.edition),
748 // need to move these items separately because we lose them by the time the closure is called,
749 // but we can't create the Handler ahead of time because it's not Send
750 let show_coverage = options.show_coverage;
751 let run_check = options.run_check;
753 // First, parse the crate and extract all relevant information.
754 info!("starting to run rustc");
756 // Interpret the input file as a rust source file, passing it through the
757 // compiler all the way through the analysis passes. The rustdoc output is
758 // then generated from the cleaned AST of the crate. This runs all the
759 // plug/cleaning passes.
760 let crate_version = options.crate_version.clone();
762 let output_format = options.output_format;
763 // FIXME: fix this clone (especially render_options)
764 let externs = options.externs.clone();
765 let render_options = options.render_options.clone();
766 let scrape_examples_options = options.scrape_examples_options.clone();
767 let config = core::create_config(options);
769 interface::create_compiler_and_run(config, |compiler| {
770 compiler.enter(|queries| {
771 let sess = compiler.session();
773 if sess.opts.describe_lints {
774 let (_, lint_store) = &*queries.register_plugins()?.peek();
775 describe_lints(sess, lint_store, true);
779 // We need to hold on to the complete resolver, so we cause everything to be
780 // cloned for the analysis passes to use. Suboptimal, but necessary in the
781 // current architecture.
782 // FIXME(#83761): Resolver cloning can lead to inconsistencies between data in the
783 // two copies because one of the copies can be modified after `TyCtxt` construction.
784 let (resolver, resolver_caches) = {
785 let (krate, resolver, _) = &*abort_on_err(queries.expansion(), sess).peek();
786 let resolver_caches = resolver.borrow_mut().access(|resolver| {
787 collect_intra_doc_links::early_resolve_intra_doc_links(resolver, krate, externs)
789 (resolver.clone(), resolver_caches)
792 if sess.diagnostic().has_errors_or_lint_errors() {
793 sess.fatal("Compilation failed, aborting rustdoc");
796 let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).peek_mut();
798 global_ctxt.enter(|tcx| {
799 let (krate, render_opts, mut cache) = sess.time("run_global_ctxt", || {
800 core::run_global_ctxt(
809 info!("finished with rustc");
811 if let Some(options) = scrape_examples_options {
812 return scrape_examples::run(krate, render_opts, cache, tcx, options);
815 cache.crate_version = crate_version;
818 // if we ran coverage, bail early, we don't need to also generate docs at this point
819 // (also we didn't load in any of the useful passes)
821 } else if run_check {
822 // Since we're in "check" mode, no need to generate anything beyond this point.
826 info!("going to format");
827 match output_format {
828 config::OutputFormat::Html => sess.time("render_html", || {
829 run_renderer::<html::render::Context<'_>>(krate, render_opts, cache, tcx)
831 config::OutputFormat::Json => sess.time("render_json", || {
832 run_renderer::<json::JsonRenderer<'_>>(krate, render_opts, cache, tcx)