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(box_patterns)]
9 #![feature(control_flow_enum)]
10 #![feature(drain_filter)]
11 #![feature(let_chains)]
13 #![feature(never_type)]
14 #![feature(once_cell)]
15 #![feature(type_ascription)]
16 #![feature(iter_intersperse)]
17 #![feature(type_alias_impl_trait)]
18 #![recursion_limit = "256"]
19 #![warn(rustc::internal)]
20 #![allow(clippy::collapsible_if, clippy::collapsible_else_if)]
21 #![allow(rustc::potential_query_instability)]
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_pretty;
36 extern crate rustc_attr;
37 extern crate rustc_const_eval;
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_analysis;
45 extern crate rustc_hir_pretty;
46 extern crate rustc_index;
47 extern crate rustc_infer;
48 extern crate rustc_interface;
49 extern crate rustc_lexer;
50 extern crate rustc_lint;
51 extern crate rustc_lint_defs;
52 extern crate rustc_macros;
53 extern crate rustc_metadata;
54 extern crate rustc_middle;
55 extern crate rustc_parse;
56 extern crate rustc_passes;
57 extern crate rustc_resolve;
58 extern crate rustc_serialize;
59 extern crate rustc_session;
60 extern crate rustc_span;
61 extern crate rustc_target;
62 extern crate rustc_trait_selection;
65 // See docs in https://github.com/rust-lang/rust/blob/master/compiler/rustc/src/main.rs
67 #[cfg(feature = "jemalloc")]
68 extern crate jemalloc_sys;
70 use std::default::Default;
71 use std::env::{self, VarError};
75 use rustc_driver::abort_on_err;
76 use rustc_errors::ErrorGuaranteed;
77 use rustc_interface::interface;
78 use rustc_middle::ty::TyCtxt;
79 use rustc_session::config::{make_crate_type_option, ErrorOutputType, RustcOptGroup};
80 use rustc_session::getopts;
81 use rustc_session::{early_error, early_warn};
83 use crate::clean::utils::DOC_RUST_LANG_ORG_CHANNEL;
84 use crate::passes::collect_intra_doc_links;
86 /// A macro to create a FxHashMap.
90 /// ```ignore(cannot-test-this-because-non-exported-macro)
91 /// let letters = map!{"a" => "b", "c" => "d"};
94 /// Trailing commas are allowed.
95 /// Commas between elements are required (even if the expression is a block).
97 ($( $key: expr => $val: expr ),* $(,)*) => {{
98 let mut map = ::rustc_data_structures::fx::FxHashMap::default();
99 $( map.insert($key, $val); )*
113 // 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
128 #[cfg(feature = "jemalloc")]
130 use std::os::raw::{c_int, c_void};
133 static _F1: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::calloc;
135 static _F2: unsafe extern "C" fn(*mut *mut c_void, usize, usize) -> c_int =
136 jemalloc_sys::posix_memalign;
138 static _F3: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::aligned_alloc;
140 static _F4: unsafe extern "C" fn(usize) -> *mut c_void = jemalloc_sys::malloc;
142 static _F5: unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void = jemalloc_sys::realloc;
144 static _F6: unsafe extern "C" fn(*mut c_void) = jemalloc_sys::free;
146 #[cfg(target_os = "macos")]
149 fn _rjem_je_zone_register();
153 static _F7: unsafe extern "C" fn() = _rjem_je_zone_register;
157 rustc_driver::set_sigpipe_handler();
158 rustc_driver::install_ice_hook();
160 // When using CI artifacts (with `download_stage1 = true`), tracing is unconditionally built
161 // with `--features=static_max_level_info`, which disables almost all rustdoc logging. To avoid
162 // this, compile our own version of `tracing` that logs all levels.
163 // NOTE: this compiles both versions of tracing unconditionally, because
164 // - The compile time hit is not that bad, especially compared to rustdoc's incremental times, and
165 // - Otherwise, there's no warning that logging is being ignored when `download_stage1 = true`.
166 // NOTE: The reason this doesn't show double logging when `download_stage1 = false` and
167 // `debug_logging = true` is because all rustc logging goes to its version of tracing (the one
168 // in the sysroot), and all of rustdoc's logging goes to its version (the one in Cargo.toml).
170 rustc_driver::init_env_logger("RUSTDOC_LOG");
172 let exit_code = rustc_driver::catch_with_exit_code(|| match get_args() {
173 Some(args) => main_args(&args),
174 _ => Err(ErrorGuaranteed::unchecked_claim_error_was_emitted()),
176 process::exit(exit_code);
180 let color_logs = match std::env::var("RUSTDOC_LOG_COLOR").as_deref() {
181 Ok("always") => true,
182 Ok("never") => false,
183 Ok("auto") | Err(VarError::NotPresent) => atty::is(atty::Stream::Stdout),
184 Ok(value) => early_error(
185 ErrorOutputType::default(),
186 &format!("invalid log color value '{}': expected one of always, never, or auto", value),
188 Err(VarError::NotUnicode(value)) => early_error(
189 ErrorOutputType::default(),
191 "invalid log color value '{}': expected one of always, never, or auto",
192 value.to_string_lossy()
196 let filter = tracing_subscriber::EnvFilter::from_env("RUSTDOC_LOG");
197 let layer = tracing_tree::HierarchicalLayer::default()
198 .with_writer(io::stderr)
199 .with_indent_lines(true)
200 .with_ansi(color_logs)
203 .with_verbose_exit(true)
204 .with_verbose_entry(true)
205 .with_indent_amount(2);
206 #[cfg(parallel_compiler)]
207 let layer = layer.with_thread_ids(true).with_thread_names(true);
209 use tracing_subscriber::layer::SubscriberExt;
210 let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
211 tracing::subscriber::set_global_default(subscriber).unwrap();
214 fn get_args() -> Option<Vec<String>> {
221 ErrorOutputType::default(),
222 &format!("Argument {} is not valid Unicode: {:?}", i, arg),
230 fn opts() -> Vec<RustcOptGroup> {
231 let stable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::stable;
232 let unstable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::unstable;
234 stable("h", |o| o.optflagmulti("h", "help", "show this help message")),
235 stable("V", |o| o.optflagmulti("V", "version", "print rustdoc's version")),
236 stable("v", |o| o.optflagmulti("v", "verbose", "use verbose output")),
237 stable("w", |o| o.optopt("w", "output-format", "the output type to write", "[html]")),
238 stable("output", |o| {
242 "Which directory to place the output. \
243 This option is deprecated, use --out-dir instead.",
247 stable("o", |o| o.optopt("o", "out-dir", "which directory to place the output", "PATH")),
248 stable("crate-name", |o| {
249 o.optopt("", "crate-name", "specify the name of this crate", "NAME")
251 make_crate_type_option(),
253 o.optmulti("L", "library-path", "directory to add to crate search path", "DIR")
255 stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
256 unstable("check-cfg", |o| o.optmulti("", "check-cfg", "pass a --check-cfg to rustc", "")),
257 stable("extern", |o| o.optmulti("", "extern", "pass an --extern to rustc", "NAME[=PATH]")),
258 unstable("extern-html-root-url", |o| {
261 "extern-html-root-url",
262 "base URL to use for dependencies; for example, \
263 \"std=/doc\" links std::vec::Vec to /doc/std/vec/struct.Vec.html",
267 unstable("extern-html-root-takes-precedence", |o| {
270 "extern-html-root-takes-precedence",
271 "give precedence to `--extern-html-root-url`, not `html_root_url`",
275 o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
277 stable("document-private-items", |o| {
278 o.optflagmulti("", "document-private-items", "document private items")
280 unstable("document-hidden-items", |o| {
281 o.optflagmulti("", "document-hidden-items", "document items that have doc(hidden)")
283 stable("test", |o| o.optflagmulti("", "test", "run code examples as tests")),
284 stable("test-args", |o| {
285 o.optmulti("", "test-args", "arguments to pass to the test runner", "ARGS")
287 unstable("test-run-directory", |o| {
290 "test-run-directory",
291 "The working directory in which to run tests",
295 stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
296 stable("markdown-css", |o| {
300 "CSS files to include via <link> in a rendered Markdown file",
304 stable("html-in-header", |o| {
308 "files to include inline in the <head> section of a rendered Markdown file \
309 or generated documentation",
313 stable("html-before-content", |o| {
316 "html-before-content",
317 "files to include inline between <body> and the content of a rendered \
318 Markdown file or generated documentation",
322 stable("html-after-content", |o| {
325 "html-after-content",
326 "files to include inline between the content and </body> of a rendered \
327 Markdown file or generated documentation",
331 unstable("markdown-before-content", |o| {
334 "markdown-before-content",
335 "files to include inline between <body> and the content of a rendered \
336 Markdown file or generated documentation",
340 unstable("markdown-after-content", |o| {
343 "markdown-after-content",
344 "files to include inline between the content and </body> of a rendered \
345 Markdown file or generated documentation",
349 stable("markdown-playground-url", |o| {
350 o.optopt("", "markdown-playground-url", "URL to send code snippets to", "URL")
352 stable("markdown-no-toc", |o| {
353 o.optflagmulti("", "markdown-no-toc", "don't include table of contents")
359 "To add some CSS rules with a given file to generate doc with your \
360 own theme. However, your theme might break if the rustdoc's generated HTML \
361 changes, so be careful!",
366 o.optmulti("Z", "", "unstable / perma-unstable options (only on nightly build)", "FLAG")
368 stable("sysroot", |o| o.optopt("", "sysroot", "Override the system root", "PATH")),
369 unstable("playground-url", |o| {
373 "URL to send code snippets to, may be reset by --markdown-playground-url \
374 or `#![doc(html_playground_url=...)]`",
378 unstable("display-doctest-warnings", |o| {
381 "display-doctest-warnings",
382 "show warnings that originate in doctests",
385 stable("crate-version", |o| {
386 o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
388 unstable("sort-modules-by-appearance", |o| {
391 "sort-modules-by-appearance",
392 "sort modules by where they appear in the program, rather than alphabetically",
395 stable("default-theme", |o| {
399 "Set the default theme. THEME should be the theme name, generally lowercase. \
400 If an unknown default theme is specified, the builtin default is used. \
401 The set of themes, and the rustdoc built-in default, are not stable.",
405 unstable("default-setting", |o| {
409 "Default value for a rustdoc setting (used when \"rustdoc-SETTING\" is absent \
410 from web browser Local Storage). If VALUE is not supplied, \"true\" is used. \
411 Supported SETTINGs and VALUEs are not documented and not stable.",
415 stable("theme", |o| {
419 "additional themes which will be added to the generated docs",
423 stable("check-theme", |o| {
424 o.optmulti("", "check-theme", "check if given theme is valid", "FILES")
426 unstable("resource-suffix", |o| {
430 "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
431 \"light-suffix.css\"",
435 stable("edition", |o| {
439 "edition to use when compiling rust code (default: 2015)",
443 stable("color", |o| {
447 "Configure coloring of output:
448 auto = colorize, if output goes to a tty (default);
449 always = always colorize output;
450 never = never colorize output",
454 stable("error-format", |o| {
458 "How errors and other messages are produced",
462 stable("diagnostic-width", |o| {
466 "Provide width of the output for truncated error messages",
471 o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
473 unstable("disable-minification", |o| {
474 o.optflagmulti("", "disable-minification", "Disable minification applied on JS files")
476 stable("allow", |o| o.optmulti("A", "allow", "Set lint allowed", "LINT")),
477 stable("warn", |o| o.optmulti("W", "warn", "Set lint warnings", "LINT")),
478 stable("force-warn", |o| o.optmulti("", "force-warn", "Set lint force-warn", "LINT")),
479 stable("deny", |o| o.optmulti("D", "deny", "Set lint denied", "LINT")),
480 stable("forbid", |o| o.optmulti("F", "forbid", "Set lint forbidden", "LINT")),
481 stable("cap-lints", |o| {
485 "Set the most restrictive lint level. \
486 More restrictive lints are capped at this \
487 level. By default, it is at `forbid` level.",
491 unstable("index-page", |o| {
492 o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
494 unstable("enable-index-page", |o| {
495 o.optflagmulti("", "enable-index-page", "To enable generation of the index page")
497 unstable("static-root-path", |o| {
501 "Path string to force loading static files from in output pages. \
502 If not set, uses combinations of '../' to reach the documentation root.",
506 unstable("disable-per-crate-search", |o| {
509 "disable-per-crate-search",
510 "disables generating the crate selector on the search box",
513 unstable("persist-doctests", |o| {
517 "Directory to persist doctest executables into",
521 unstable("show-coverage", |o| {
525 "calculate percentage of public items with documentation",
528 unstable("enable-per-target-ignores", |o| {
531 "enable-per-target-ignores",
532 "parse ignore-foo for ignoring doctests on a per-target basis",
535 unstable("runtool", |o| {
540 "The tool to run tests with when building for a different target than host",
543 unstable("runtool-arg", |o| {
548 "One (of possibly many) arguments to pass to the runtool",
551 unstable("test-builder", |o| {
552 o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH")
554 unstable("check", |o| o.optflagmulti("", "check", "Run rustdoc checks")),
555 unstable("generate-redirect-map", |o| {
558 "generate-redirect-map",
559 "Generate JSON file at the top level instead of generating HTML redirection files",
562 unstable("emit", |o| {
566 "Comma separated list of types of output for rustdoc to emit",
567 "[unversioned-shared-resources,toolchain-shared-resources,invocation-specific]",
570 unstable("no-run", |o| {
571 o.optflagmulti("", "no-run", "Compile doctests without running them")
573 unstable("show-type-layout", |o| {
574 o.optflagmulti("", "show-type-layout", "Include the memory layout of types in the docs")
576 unstable("nocapture", |o| {
577 o.optflag("", "nocapture", "Don't capture stdout and stderr of tests")
579 unstable("generate-link-to-definition", |o| {
582 "generate-link-to-definition",
583 "Make the identifiers in the HTML source code pages navigable",
586 unstable("scrape-examples-output-path", |o| {
589 "scrape-examples-output-path",
591 "collect function call information and output at the given path",
594 unstable("scrape-examples-target-crate", |o| {
597 "scrape-examples-target-crate",
599 "collect function call information for functions from the target crate",
602 unstable("scrape-tests", |o| {
603 o.optflag("", "scrape-tests", "Include test code when scraping examples")
605 unstable("with-examples", |o| {
610 "path to function call information (for displaying examples in the documentation)",
613 // deprecated / removed options
614 stable("plugin-path", |o| {
618 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
619 for more information",
623 stable("passes", |o| {
627 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
628 for more information",
632 stable("plugins", |o| {
636 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
637 for more information",
641 stable("no-default", |o| {
645 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
646 for more information",
653 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
654 for more information",
661 fn usage(argv0: &str) {
662 let mut options = getopts::Options::new();
663 for option in opts() {
664 (option.apply)(&mut options);
666 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
667 println!(" @path Read newline separated options from `path`\n");
669 "More information available at {}/rustdoc/what-is-rustdoc.html",
670 DOC_RUST_LANG_ORG_CHANNEL
674 /// A result type used by several functions under `main()`.
675 type MainResult = Result<(), ErrorGuaranteed>;
677 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
681 let reported = diag.struct_err(&err).emit();
687 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
689 renderopts: config::RenderOptions,
690 cache: formats::cache::Cache,
693 match formats::run_format::<T>(krate, renderopts, cache, tcx) {
697 tcx.sess.struct_err(&format!("couldn't generate documentation: {}", e.error));
698 let file = e.file.display().to_string();
699 if !file.is_empty() {
700 msg.note(&format!("failed to create or modify \"{}\"", file));
707 fn main_args(at_args: &[String]) -> MainResult {
708 let args = rustc_driver::args::arg_expand_all(at_args);
710 let mut options = getopts::Options::new();
711 for option in opts() {
712 (option.apply)(&mut options);
714 let matches = match options.parse(&args[1..]) {
717 early_error(ErrorOutputType::default(), &err.to_string());
721 // Note that we discard any distinction between different non-zero exit
722 // codes from `from_matches` here.
723 let (options, render_options) = match config::Options::from_matches(&matches, args) {
726 return if code == 0 {
729 Err(ErrorGuaranteed::unchecked_claim_error_was_emitted())
734 let diag = core::new_handler(
735 options.error_format,
737 options.diagnostic_width,
738 &options.unstable_opts,
741 match (options.should_test, options.markdown_input()) {
742 (true, true) => return wrap_return(&diag, markdown::test(options)),
743 (true, false) => return doctest::run(options),
745 let input = options.input.clone();
746 let edition = options.edition;
747 let config = core::create_config(options);
749 // `markdown::render` can invoke `doctest::make_test`, which
750 // requires session globals and a thread pool, so we use
754 interface::run_compiler(config, |_compiler| {
755 markdown::render(&input, render_options, edition)
762 // need to move these items separately because we lose them by the time the closure is called,
763 // but we can't create the Handler ahead of time because it's not Send
764 let show_coverage = options.show_coverage;
765 let run_check = options.run_check;
767 // First, parse the crate and extract all relevant information.
768 info!("starting to run rustc");
770 // Interpret the input file as a rust source file, passing it through the
771 // compiler all the way through the analysis passes. The rustdoc output is
772 // then generated from the cleaned AST of the crate. This runs all the
773 // plug/cleaning passes.
774 let crate_version = options.crate_version.clone();
776 let output_format = options.output_format;
777 let externs = options.externs.clone();
778 let scrape_examples_options = options.scrape_examples_options.clone();
780 let config = core::create_config(options);
782 interface::run_compiler(config, |compiler| {
783 let sess = compiler.session();
785 if sess.opts.describe_lints {
786 let mut lint_store = rustc_lint::new_lint_store(
787 sess.opts.unstable_opts.no_interleave_lints,
788 sess.enable_internal_lints(),
790 let registered_lints = if let Some(register_lints) = compiler.register_lints() {
791 register_lints(sess, &mut lint_store);
796 rustc_driver::describe_lints(sess, &lint_store, registered_lints);
800 compiler.enter(|queries| {
801 // We need to hold on to the complete resolver, so we cause everything to be
802 // cloned for the analysis passes to use. Suboptimal, but necessary in the
803 // current architecture.
804 // FIXME(#83761): Resolver cloning can lead to inconsistencies between data in the
805 // two copies because one of the copies can be modified after `TyCtxt` construction.
806 let (resolver, resolver_caches) = {
807 let (krate, resolver, _) = &*abort_on_err(queries.expansion(), sess).peek();
808 let resolver_caches = resolver.borrow_mut().access(|resolver| {
809 collect_intra_doc_links::early_resolve_intra_doc_links(
814 render_options.document_private,
817 (resolver.clone(), resolver_caches)
820 if sess.diagnostic().has_errors_or_lint_errors().is_some() {
821 sess.fatal("Compilation failed, aborting rustdoc");
824 let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).peek_mut();
826 global_ctxt.enter(|tcx| {
827 let (krate, render_opts, mut cache) = sess.time("run_global_ctxt", || {
828 core::run_global_ctxt(
837 info!("finished with rustc");
839 if let Some(options) = scrape_examples_options {
840 return scrape_examples::run(krate, render_opts, cache, tcx, options);
843 cache.crate_version = crate_version;
846 // if we ran coverage, bail early, we don't need to also generate docs at this point
847 // (also we didn't load in any of the useful passes)
849 } else if run_check {
850 // Since we're in "check" mode, no need to generate anything beyond this point.
854 info!("going to format");
855 match output_format {
856 config::OutputFormat::Html => sess.time("render_html", || {
857 run_renderer::<html::render::Context<'_>>(krate, render_opts, cache, tcx)
859 config::OutputFormat::Json => sess.time("render_json", || {
860 run_renderer::<json::JsonRenderer<'_>>(krate, render_opts, cache, tcx)