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(box_syntax)]
14 #![feature(crate_visibility_modifier)]
15 #![feature(never_type)]
16 #![feature(once_cell)]
17 #![feature(type_ascription)]
18 #![feature(iter_intersperse)]
19 #![feature(type_alias_impl_trait)]
20 #![feature(generic_associated_types)]
21 #![recursion_limit = "256"]
22 #![warn(rustc::internal)]
23 #![allow(clippy::collapsible_if, clippy::collapsible_else_if)]
28 // N.B. these need `extern crate` even in 2018 edition
29 // because they're loaded implicitly from the sysroot.
30 // The reason they're loaded from the sysroot is because
31 // the rustdoc artifacts aren't stored in rustc's cargo target directory.
32 // So if `rustc` was specified in Cargo.toml, this would spuriously rebuild crates.
34 // Dependencies listed in Cargo.toml do not need `extern crate`.
36 extern crate rustc_ast;
37 extern crate rustc_ast_lowering;
38 extern crate rustc_ast_pretty;
39 extern crate rustc_attr;
40 extern crate rustc_const_eval;
41 extern crate rustc_data_structures;
42 extern crate rustc_driver;
43 extern crate rustc_errors;
44 extern crate rustc_expand;
45 extern crate rustc_feature;
46 extern crate rustc_hir;
47 extern crate rustc_hir_pretty;
48 extern crate rustc_index;
49 extern crate rustc_infer;
50 extern crate rustc_interface;
51 extern crate rustc_lexer;
52 extern crate rustc_lint;
53 extern crate rustc_lint_defs;
54 extern crate rustc_macros;
55 extern crate rustc_metadata;
56 extern crate rustc_middle;
57 extern crate rustc_parse;
58 extern crate rustc_passes;
59 extern crate rustc_resolve;
60 extern crate rustc_serialize;
61 extern crate rustc_session;
62 extern crate rustc_span;
63 extern crate rustc_target;
64 extern crate rustc_trait_selection;
65 extern crate rustc_typeck;
68 // See docs in https://github.com/rust-lang/rust/blob/master/compiler/rustc/src/main.rs
70 #[cfg(feature = "jemalloc")]
71 extern crate tikv_jemalloc_sys;
72 #[cfg(feature = "jemalloc")]
73 use tikv_jemalloc_sys as jemalloc_sys;
75 use std::default::Default;
76 use std::env::{self, VarError};
80 use rustc_driver::{abort_on_err, describe_lints};
81 use rustc_errors::ErrorReported;
82 use rustc_interface::interface;
83 use rustc_middle::ty::TyCtxt;
84 use rustc_session::config::{make_crate_type_option, ErrorOutputType, RustcOptGroup};
85 use rustc_session::getopts;
86 use rustc_session::{early_error, early_warn};
88 use crate::clean::utils::DOC_RUST_LANG_ORG_CHANNEL;
89 use crate::passes::collect_intra_doc_links;
91 /// A macro to create a FxHashMap.
96 /// let letters = map!{"a" => "b", "c" => "d"};
99 /// Trailing commas are allowed.
100 /// Commas between elements are required (even if the expression is a block).
102 ($( $key: expr => $val: expr ),* $(,)*) => {{
103 let mut map = ::rustc_data_structures::fx::FxHashMap::default();
104 $( map.insert($key, $val); )*
118 // used by the error-index generator, so it needs to be public
131 // See docs in https://github.com/rust-lang/rust/blob/master/compiler/rustc/src/main.rs
133 #[cfg(feature = "jemalloc")]
135 use std::os::raw::{c_int, c_void};
138 static _F1: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::calloc;
140 static _F2: unsafe extern "C" fn(*mut *mut c_void, usize, usize) -> c_int =
141 jemalloc_sys::posix_memalign;
143 static _F3: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::aligned_alloc;
145 static _F4: unsafe extern "C" fn(usize) -> *mut c_void = jemalloc_sys::malloc;
147 static _F5: unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void = jemalloc_sys::realloc;
149 static _F6: unsafe extern "C" fn(*mut c_void) = jemalloc_sys::free;
151 #[cfg(target_os = "macos")]
154 fn _rjem_je_zone_register();
158 static _F7: unsafe extern "C" fn() = _rjem_je_zone_register;
162 rustc_driver::set_sigpipe_handler();
163 rustc_driver::install_ice_hook();
165 // When using CI artifacts (with `download_stage1 = true`), tracing is unconditionally built
166 // with `--features=static_max_level_info`, which disables almost all rustdoc logging. To avoid
167 // this, compile our own version of `tracing` that logs all levels.
168 // NOTE: this compiles both versions of tracing unconditionally, because
169 // - The compile time hit is not that bad, especially compared to rustdoc's incremental times, and
170 // - Otherwise, there's no warning that logging is being ignored when `download_stage1 = true`.
171 // NOTE: The reason this doesn't show double logging when `download_stage1 = false` and
172 // `debug_logging = true` is because all rustc logging goes to its version of tracing (the one
173 // in the sysroot), and all of rustdoc's logging goes to its version (the one in Cargo.toml).
175 rustc_driver::init_env_logger("RUSTDOC_LOG");
177 let exit_code = rustc_driver::catch_with_exit_code(|| match get_args() {
178 Some(args) => main_args(&args),
179 _ => Err(ErrorReported),
181 process::exit(exit_code);
185 let color_logs = match std::env::var("RUSTDOC_LOG_COLOR").as_deref() {
186 Ok("always") => true,
187 Ok("never") => false,
188 Ok("auto") | Err(VarError::NotPresent) => atty::is(atty::Stream::Stdout),
189 Ok(value) => early_error(
190 ErrorOutputType::default(),
191 &format!("invalid log color value '{}': expected one of always, never, or auto", value),
193 Err(VarError::NotUnicode(value)) => early_error(
194 ErrorOutputType::default(),
196 "invalid log color value '{}': expected one of always, never, or auto",
197 value.to_string_lossy()
201 let filter = tracing_subscriber::EnvFilter::from_env("RUSTDOC_LOG");
202 let layer = tracing_tree::HierarchicalLayer::default()
203 .with_writer(io::stderr)
204 .with_indent_lines(true)
205 .with_ansi(color_logs)
208 .with_verbose_exit(true)
209 .with_verbose_entry(true)
210 .with_indent_amount(2);
211 #[cfg(parallel_compiler)]
212 let layer = layer.with_thread_ids(true).with_thread_names(true);
214 use tracing_subscriber::layer::SubscriberExt;
215 let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
216 tracing::subscriber::set_global_default(subscriber).unwrap();
219 fn get_args() -> Option<Vec<String>> {
226 ErrorOutputType::default(),
227 &format!("Argument {} is not valid Unicode: {:?}", i, arg),
235 fn opts() -> Vec<RustcOptGroup> {
236 let stable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::stable;
237 let unstable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::unstable;
239 stable("h", |o| o.optflagmulti("h", "help", "show this help message")),
240 stable("V", |o| o.optflagmulti("V", "version", "print rustdoc's version")),
241 stable("v", |o| o.optflagmulti("v", "verbose", "use verbose output")),
242 stable("w", |o| o.optopt("w", "output-format", "the output type to write", "[html]")),
243 stable("output", |o| {
247 "Which directory to place the output. \
248 This option is deprecated, use --out-dir instead.",
252 stable("o", |o| o.optopt("o", "out-dir", "which directory to place the output", "PATH")),
253 stable("crate-name", |o| {
254 o.optopt("", "crate-name", "specify the name of this crate", "NAME")
256 make_crate_type_option(),
258 o.optmulti("L", "library-path", "directory to add to crate search path", "DIR")
260 stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
261 stable("extern", |o| o.optmulti("", "extern", "pass an --extern to rustc", "NAME[=PATH]")),
262 unstable("extern-html-root-url", |o| {
265 "extern-html-root-url",
266 "base URL to use for dependencies; for example, \
267 \"std=/doc\" links std::vec::Vec to /doc/std/vec/struct.Vec.html",
271 unstable("extern-html-root-takes-precedence", |o| {
274 "extern-html-root-takes-precedence",
275 "give precedence to `--extern-html-root-url`, not `html_root_url`",
279 o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
281 stable("document-private-items", |o| {
282 o.optflagmulti("", "document-private-items", "document private items")
284 unstable("document-hidden-items", |o| {
285 o.optflagmulti("", "document-hidden-items", "document items that have doc(hidden)")
287 stable("test", |o| o.optflagmulti("", "test", "run code examples as tests")),
288 stable("test-args", |o| {
289 o.optmulti("", "test-args", "arguments to pass to the test runner", "ARGS")
291 unstable("test-run-directory", |o| {
294 "test-run-directory",
295 "The working directory in which to run tests",
299 stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
300 stable("markdown-css", |o| {
304 "CSS files to include via <link> in a rendered Markdown file",
308 stable("html-in-header", |o| {
312 "files to include inline in the <head> section of a rendered Markdown file \
313 or generated documentation",
317 stable("html-before-content", |o| {
320 "html-before-content",
321 "files to include inline between <body> and the content of a rendered \
322 Markdown file or generated documentation",
326 stable("html-after-content", |o| {
329 "html-after-content",
330 "files to include inline between the content and </body> of a rendered \
331 Markdown file or generated documentation",
335 unstable("markdown-before-content", |o| {
338 "markdown-before-content",
339 "files to include inline between <body> and the content of a rendered \
340 Markdown file or generated documentation",
344 unstable("markdown-after-content", |o| {
347 "markdown-after-content",
348 "files to include inline between the content and </body> of a rendered \
349 Markdown file or generated documentation",
353 stable("markdown-playground-url", |o| {
354 o.optopt("", "markdown-playground-url", "URL to send code snippets to", "URL")
356 stable("markdown-no-toc", |o| {
357 o.optflagmulti("", "markdown-no-toc", "don't include table of contents")
363 "To add some CSS rules with a given file to generate doc with your \
364 own theme. However, your theme might break if the rustdoc's generated HTML \
365 changes, so be careful!",
370 o.optmulti("Z", "", "internal and debugging options (only on nightly build)", "FLAG")
372 stable("sysroot", |o| o.optopt("", "sysroot", "Override the system root", "PATH")),
373 unstable("playground-url", |o| {
377 "URL to send code snippets to, may be reset by --markdown-playground-url \
378 or `#![doc(html_playground_url=...)]`",
382 unstable("display-doctest-warnings", |o| {
385 "display-doctest-warnings",
386 "show warnings that originate in doctests",
389 stable("crate-version", |o| {
390 o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
392 unstable("sort-modules-by-appearance", |o| {
395 "sort-modules-by-appearance",
396 "sort modules by where they appear in the program, rather than alphabetically",
399 stable("default-theme", |o| {
403 "Set the default theme. THEME should be the theme name, generally lowercase. \
404 If an unknown default theme is specified, the builtin default is used. \
405 The set of themes, and the rustdoc built-in default, are not stable.",
409 unstable("default-setting", |o| {
413 "Default value for a rustdoc setting (used when \"rustdoc-SETTING\" is absent \
414 from web browser Local Storage). If VALUE is not supplied, \"true\" is used. \
415 Supported SETTINGs and VALUEs are not documented and not stable.",
419 stable("theme", |o| {
423 "additional themes which will be added to the generated docs",
427 stable("check-theme", |o| {
428 o.optmulti("", "check-theme", "check if given theme is valid", "FILES")
430 unstable("resource-suffix", |o| {
434 "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
435 \"light-suffix.css\"",
439 stable("edition", |o| {
443 "edition to use when compiling rust code (default: 2015)",
447 stable("color", |o| {
451 "Configure coloring of output:
452 auto = colorize, if output goes to a tty (default);
453 always = always colorize output;
454 never = never colorize output",
458 stable("error-format", |o| {
462 "How errors and other messages are produced",
467 o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
469 unstable("disable-minification", |o| {
470 o.optflagmulti("", "disable-minification", "Disable minification applied on JS files")
472 stable("allow", |o| o.optmulti("A", "allow", "Set lint allowed", "LINT")),
473 stable("warn", |o| o.optmulti("W", "warn", "Set lint warnings", "LINT")),
474 stable("force-warn", |o| o.optmulti("", "force-warn", "Set lint force-warn", "LINT")),
475 stable("deny", |o| o.optmulti("D", "deny", "Set lint denied", "LINT")),
476 stable("forbid", |o| o.optmulti("F", "forbid", "Set lint forbidden", "LINT")),
477 stable("cap-lints", |o| {
481 "Set the most restrictive lint level. \
482 More restrictive lints are capped at this \
483 level. By default, it is at `forbid` level.",
487 unstable("index-page", |o| {
488 o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
490 unstable("enable-index-page", |o| {
491 o.optflagmulti("", "enable-index-page", "To enable generation of the index page")
493 unstable("static-root-path", |o| {
497 "Path string to force loading static files from in output pages. \
498 If not set, uses combinations of '../' to reach the documentation root.",
502 unstable("disable-per-crate-search", |o| {
505 "disable-per-crate-search",
506 "disables generating the crate selector on the search box",
509 unstable("persist-doctests", |o| {
513 "Directory to persist doctest executables into",
517 unstable("show-coverage", |o| {
521 "calculate percentage of public items with documentation",
524 unstable("enable-per-target-ignores", |o| {
527 "enable-per-target-ignores",
528 "parse ignore-foo for ignoring doctests on a per-target basis",
531 unstable("runtool", |o| {
536 "The tool to run tests with when building for a different target than host",
539 unstable("runtool-arg", |o| {
544 "One (of possibly many) arguments to pass to the runtool",
547 unstable("test-builder", |o| {
548 o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH")
550 unstable("check", |o| o.optflagmulti("", "check", "Run rustdoc checks")),
551 unstable("generate-redirect-map", |o| {
554 "generate-redirect-map",
555 "Generate JSON file at the top level instead of generating HTML redirection files",
558 unstable("emit", |o| {
562 "Comma separated list of types of output for rustdoc to emit",
563 "[unversioned-shared-resources,toolchain-shared-resources,invocation-specific]",
566 unstable("no-run", |o| {
567 o.optflagmulti("", "no-run", "Compile doctests without running them")
569 unstable("show-type-layout", |o| {
570 o.optflagmulti("", "show-type-layout", "Include the memory layout of types in the docs")
572 unstable("nocapture", |o| {
573 o.optflag("", "nocapture", "Don't capture stdout and stderr of tests")
575 unstable("generate-link-to-definition", |o| {
578 "generate-link-to-definition",
579 "Make the identifiers in the HTML source code pages navigable",
582 unstable("scrape-examples-output-path", |o| {
585 "scrape-examples-output-path",
587 "collect function call information and output at the given path",
590 unstable("scrape-examples-target-crate", |o| {
593 "scrape-examples-target-crate",
595 "collect function call information for functions from the target crate",
598 unstable("with-examples", |o| {
603 "path to function call information (for displaying examples in the documentation)",
606 // deprecated / removed options
607 stable("plugin-path", |o| {
611 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
612 for more information",
616 stable("passes", |o| {
620 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
621 for more information",
625 stable("plugins", |o| {
629 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
630 for more information",
634 stable("no-default", |o| {
638 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
639 for more information",
646 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
647 for more information",
654 fn usage(argv0: &str) {
655 let mut options = getopts::Options::new();
656 for option in opts() {
657 (option.apply)(&mut options);
659 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
660 println!(" @path Read newline separated options from `path`\n");
662 "More information available at {}/rustdoc/what-is-rustdoc.html",
663 DOC_RUST_LANG_ORG_CHANNEL
667 /// A result type used by several functions under `main()`.
668 type MainResult = Result<(), ErrorReported>;
670 fn main_args(at_args: &[String]) -> MainResult {
671 let args = rustc_driver::args::arg_expand_all(at_args);
673 let mut options = getopts::Options::new();
674 for option in opts() {
675 (option.apply)(&mut options);
677 let matches = match options.parse(&args[1..]) {
680 early_error(ErrorOutputType::default(), &err.to_string());
684 // Note that we discard any distinction between different non-zero exit
685 // codes from `from_matches` here.
686 let options = match config::Options::from_matches(&matches) {
688 Err(code) => return if code == 0 { Ok(()) } else { Err(ErrorReported) },
690 rustc_interface::util::setup_callbacks_and_run_in_thread_pool_with_globals(
692 1, // this runs single-threaded, even in a parallel compiler
694 move || main_options(options),
698 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
702 diag.struct_err(&err).emit();
708 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
710 renderopts: config::RenderOptions,
711 cache: formats::cache::Cache,
714 match formats::run_format::<T>(krate, renderopts, cache, tcx) {
718 tcx.sess.struct_err(&format!("couldn't generate documentation: {}", e.error));
719 let file = e.file.display().to_string();
723 msg.note(&format!("failed to create or modify \"{}\"", file)).emit()
730 fn main_options(options: config::Options) -> MainResult {
731 let diag = core::new_handler(options.error_format, None, &options.debugging_opts);
733 match (options.should_test, options.markdown_input()) {
734 (true, true) => return wrap_return(&diag, markdown::test(options)),
735 (true, false) => return doctest::run(options),
739 markdown::render(&options.input, options.render_options, options.edition),
745 // need to move these items separately because we lose them by the time the closure is called,
746 // but we can't create the Handler ahead of time because it's not Send
747 let show_coverage = options.show_coverage;
748 let run_check = options.run_check;
750 // First, parse the crate and extract all relevant information.
751 info!("starting to run rustc");
753 // Interpret the input file as a rust source file, passing it through the
754 // compiler all the way through the analysis passes. The rustdoc output is
755 // then generated from the cleaned AST of the crate. This runs all the
756 // plug/cleaning passes.
757 let crate_version = options.crate_version.clone();
759 let output_format = options.output_format;
760 // FIXME: fix this clone (especially render_options)
761 let externs = options.externs.clone();
762 let render_options = options.render_options.clone();
763 let scrape_examples_options = options.scrape_examples_options.clone();
764 let config = core::create_config(options);
766 interface::create_compiler_and_run(config, |compiler| {
767 compiler.enter(|queries| {
768 let sess = compiler.session();
770 if sess.opts.describe_lints {
771 let (_, lint_store) = &*queries.register_plugins()?.peek();
772 describe_lints(sess, lint_store, true);
776 // We need to hold on to the complete resolver, so we cause everything to be
777 // cloned for the analysis passes to use. Suboptimal, but necessary in the
778 // current architecture.
779 // FIXME(#83761): Resolver cloning can lead to inconsistencies between data in the
780 // two copies because one of the copies can be modified after `TyCtxt` construction.
781 let (resolver, resolver_caches) = {
782 let (krate, resolver, _) = &*abort_on_err(queries.expansion(), sess).peek();
783 let resolver_caches = resolver.borrow_mut().access(|resolver| {
784 collect_intra_doc_links::early_resolve_intra_doc_links(resolver, krate, externs)
786 (resolver.clone(), resolver_caches)
789 if sess.diagnostic().has_errors_or_lint_errors() {
790 sess.fatal("Compilation failed, aborting rustdoc");
793 let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).peek_mut();
795 global_ctxt.enter(|tcx| {
796 let (krate, render_opts, mut cache) = sess.time("run_global_ctxt", || {
797 core::run_global_ctxt(
806 info!("finished with rustc");
808 if let Some(options) = scrape_examples_options {
809 return scrape_examples::run(krate, render_opts, cache, tcx, options);
812 cache.crate_version = crate_version;
815 // if we ran coverage, bail early, we don't need to also generate docs at this point
816 // (also we didn't load in any of the useful passes)
818 } else if run_check {
819 // Since we're in "check" mode, no need to generate anything beyond this point.
823 info!("going to format");
824 match output_format {
825 config::OutputFormat::Html => sess.time("render_html", || {
826 run_renderer::<html::render::Context<'_>>(krate, render_opts, cache, tcx)
828 config::OutputFormat::Json => sess.time("render_json", || {
829 run_renderer::<json::JsonRenderer<'_>>(krate, render_opts, cache, tcx)