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)]
29 // N.B. these need `extern crate` even in 2018 edition
30 // because they're loaded implicitly from the sysroot.
31 // The reason they're loaded from the sysroot is because
32 // the rustdoc artifacts aren't stored in rustc's cargo target directory.
33 // So if `rustc` was specified in Cargo.toml, this would spuriously rebuild crates.
35 // Dependencies listed in Cargo.toml do not need `extern crate`.
37 extern crate rustc_ast;
38 extern crate rustc_ast_lowering;
39 extern crate rustc_ast_pretty;
40 extern crate rustc_attr;
41 extern crate rustc_const_eval;
42 extern crate rustc_data_structures;
43 extern crate rustc_driver;
44 extern crate rustc_errors;
45 extern crate rustc_expand;
46 extern crate rustc_feature;
47 extern crate rustc_hir;
48 extern crate rustc_hir_pretty;
49 extern crate rustc_index;
50 extern crate rustc_infer;
51 extern crate rustc_interface;
52 extern crate rustc_lexer;
53 extern crate rustc_lint;
54 extern crate rustc_lint_defs;
55 extern crate rustc_macros;
56 extern crate rustc_metadata;
57 extern crate rustc_middle;
58 extern crate rustc_parse;
59 extern crate rustc_passes;
60 extern crate rustc_resolve;
61 extern crate rustc_serialize;
62 extern crate rustc_session;
63 extern crate rustc_span;
64 extern crate rustc_target;
65 extern crate rustc_trait_selection;
66 extern crate rustc_typeck;
69 // See docs in https://github.com/rust-lang/rust/blob/master/compiler/rustc/src/main.rs
71 #[cfg(feature = "jemalloc")]
72 extern crate tikv_jemalloc_sys;
73 #[cfg(feature = "jemalloc")]
74 use tikv_jemalloc_sys as jemalloc_sys;
76 use std::default::Default;
77 use std::env::{self, VarError};
81 use rustc_driver::{abort_on_err, describe_lints};
82 use rustc_errors::ErrorReported;
83 use rustc_interface::interface;
84 use rustc_middle::ty::TyCtxt;
85 use rustc_session::config::{make_crate_type_option, ErrorOutputType, RustcOptGroup};
86 use rustc_session::getopts;
87 use rustc_session::{early_error, early_warn};
89 use crate::clean::utils::DOC_RUST_LANG_ORG_CHANNEL;
90 use crate::passes::collect_intra_doc_links;
92 /// A macro to create a FxHashMap.
97 /// let letters = map!{"a" => "b", "c" => "d"};
100 /// Trailing commas are allowed.
101 /// Commas between elements are required (even if the expression is a block).
103 ($( $key: expr => $val: expr ),* $(,)*) => {{
104 let mut map = ::rustc_data_structures::fx::FxHashMap::default();
105 $( map.insert($key, $val); )*
119 // used by the error-index generator, so it needs to be public
132 // See docs in https://github.com/rust-lang/rust/blob/master/compiler/rustc/src/main.rs
134 #[cfg(feature = "jemalloc")]
136 use std::os::raw::{c_int, c_void};
139 static _F1: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::calloc;
141 static _F2: unsafe extern "C" fn(*mut *mut c_void, usize, usize) -> c_int =
142 jemalloc_sys::posix_memalign;
144 static _F3: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::aligned_alloc;
146 static _F4: unsafe extern "C" fn(usize) -> *mut c_void = jemalloc_sys::malloc;
148 static _F5: unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void = jemalloc_sys::realloc;
150 static _F6: unsafe extern "C" fn(*mut c_void) = jemalloc_sys::free;
152 #[cfg(target_os = "macos")]
155 fn _rjem_je_zone_register();
159 static _F7: unsafe extern "C" fn() = _rjem_je_zone_register;
163 rustc_driver::set_sigpipe_handler();
164 rustc_driver::install_ice_hook();
166 // When using CI artifacts (with `download_stage1 = true`), tracing is unconditionally built
167 // with `--features=static_max_level_info`, which disables almost all rustdoc logging. To avoid
168 // this, compile our own version of `tracing` that logs all levels.
169 // NOTE: this compiles both versions of tracing unconditionally, because
170 // - The compile time hit is not that bad, especially compared to rustdoc's incremental times, and
171 // - Otherwise, there's no warning that logging is being ignored when `download_stage1 = true`.
172 // NOTE: The reason this doesn't show double logging when `download_stage1 = false` and
173 // `debug_logging = true` is because all rustc logging goes to its version of tracing (the one
174 // in the sysroot), and all of rustdoc's logging goes to its version (the one in Cargo.toml).
176 rustc_driver::init_env_logger("RUSTDOC_LOG");
178 let exit_code = rustc_driver::catch_with_exit_code(|| match get_args() {
179 Some(args) => main_args(&args),
180 _ => Err(ErrorReported),
182 process::exit(exit_code);
186 let color_logs = match std::env::var("RUSTDOC_LOG_COLOR").as_deref() {
187 Ok("always") => true,
188 Ok("never") => false,
189 Ok("auto") | Err(VarError::NotPresent) => atty::is(atty::Stream::Stdout),
190 Ok(value) => early_error(
191 ErrorOutputType::default(),
192 &format!("invalid log color value '{}': expected one of always, never, or auto", value),
194 Err(VarError::NotUnicode(value)) => early_error(
195 ErrorOutputType::default(),
197 "invalid log color value '{}': expected one of always, never, or auto",
198 value.to_string_lossy()
202 let filter = tracing_subscriber::EnvFilter::from_env("RUSTDOC_LOG");
203 let layer = tracing_tree::HierarchicalLayer::default()
204 .with_writer(io::stderr)
205 .with_indent_lines(true)
206 .with_ansi(color_logs)
209 .with_verbose_exit(true)
210 .with_verbose_entry(true)
211 .with_indent_amount(2);
212 #[cfg(parallel_compiler)]
213 let layer = layer.with_thread_ids(true).with_thread_names(true);
215 use tracing_subscriber::layer::SubscriberExt;
216 let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
217 tracing::subscriber::set_global_default(subscriber).unwrap();
220 fn get_args() -> Option<Vec<String>> {
227 ErrorOutputType::default(),
228 &format!("Argument {} is not valid Unicode: {:?}", i, arg),
236 fn opts() -> Vec<RustcOptGroup> {
237 let stable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::stable;
238 let unstable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::unstable;
240 stable("h", |o| o.optflagmulti("h", "help", "show this help message")),
241 stable("V", |o| o.optflagmulti("V", "version", "print rustdoc's version")),
242 stable("v", |o| o.optflagmulti("v", "verbose", "use verbose output")),
243 stable("w", |o| o.optopt("w", "output-format", "the output type to write", "[html]")),
244 stable("output", |o| {
248 "Which directory to place the output. \
249 This option is deprecated, use --out-dir instead.",
253 stable("o", |o| o.optopt("o", "out-dir", "which directory to place the output", "PATH")),
254 stable("crate-name", |o| {
255 o.optopt("", "crate-name", "specify the name of this crate", "NAME")
257 make_crate_type_option(),
259 o.optmulti("L", "library-path", "directory to add to crate search path", "DIR")
261 stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
262 stable("extern", |o| o.optmulti("", "extern", "pass an --extern to rustc", "NAME[=PATH]")),
263 unstable("extern-html-root-url", |o| {
266 "extern-html-root-url",
267 "base URL to use for dependencies; for example, \
268 \"std=/doc\" links std::vec::Vec to /doc/std/vec/struct.Vec.html",
272 unstable("extern-html-root-takes-precedence", |o| {
275 "extern-html-root-takes-precedence",
276 "give precedence to `--extern-html-root-url`, not `html_root_url`",
280 o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
282 stable("document-private-items", |o| {
283 o.optflagmulti("", "document-private-items", "document private items")
285 unstable("document-hidden-items", |o| {
286 o.optflagmulti("", "document-hidden-items", "document items that have doc(hidden)")
288 stable("test", |o| o.optflagmulti("", "test", "run code examples as tests")),
289 stable("test-args", |o| {
290 o.optmulti("", "test-args", "arguments to pass to the test runner", "ARGS")
292 unstable("test-run-directory", |o| {
295 "test-run-directory",
296 "The working directory in which to run tests",
300 stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
301 stable("markdown-css", |o| {
305 "CSS files to include via <link> in a rendered Markdown file",
309 stable("html-in-header", |o| {
313 "files to include inline in the <head> section of a rendered Markdown file \
314 or generated documentation",
318 stable("html-before-content", |o| {
321 "html-before-content",
322 "files to include inline between <body> and the content of a rendered \
323 Markdown file or generated documentation",
327 stable("html-after-content", |o| {
330 "html-after-content",
331 "files to include inline between the content and </body> of a rendered \
332 Markdown file or generated documentation",
336 unstable("markdown-before-content", |o| {
339 "markdown-before-content",
340 "files to include inline between <body> and the content of a rendered \
341 Markdown file or generated documentation",
345 unstable("markdown-after-content", |o| {
348 "markdown-after-content",
349 "files to include inline between the content and </body> of a rendered \
350 Markdown file or generated documentation",
354 stable("markdown-playground-url", |o| {
355 o.optopt("", "markdown-playground-url", "URL to send code snippets to", "URL")
357 stable("markdown-no-toc", |o| {
358 o.optflagmulti("", "markdown-no-toc", "don't include table of contents")
364 "To add some CSS rules with a given file to generate doc with your \
365 own theme. However, your theme might break if the rustdoc's generated HTML \
366 changes, so be careful!",
371 o.optmulti("Z", "", "internal and debugging options (only on nightly build)", "FLAG")
373 stable("sysroot", |o| o.optopt("", "sysroot", "Override the system root", "PATH")),
374 unstable("playground-url", |o| {
378 "URL to send code snippets to, may be reset by --markdown-playground-url \
379 or `#![doc(html_playground_url=...)]`",
383 unstable("display-doctest-warnings", |o| {
386 "display-doctest-warnings",
387 "show warnings that originate in doctests",
390 stable("crate-version", |o| {
391 o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
393 unstable("sort-modules-by-appearance", |o| {
396 "sort-modules-by-appearance",
397 "sort modules by where they appear in the program, rather than alphabetically",
400 stable("default-theme", |o| {
404 "Set the default theme. THEME should be the theme name, generally lowercase. \
405 If an unknown default theme is specified, the builtin default is used. \
406 The set of themes, and the rustdoc built-in default, are not stable.",
410 unstable("default-setting", |o| {
414 "Default value for a rustdoc setting (used when \"rustdoc-SETTING\" is absent \
415 from web browser Local Storage). If VALUE is not supplied, \"true\" is used. \
416 Supported SETTINGs and VALUEs are not documented and not stable.",
420 stable("theme", |o| {
424 "additional themes which will be added to the generated docs",
428 stable("check-theme", |o| {
429 o.optmulti("", "check-theme", "check if given theme is valid", "FILES")
431 unstable("resource-suffix", |o| {
435 "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
436 \"light-suffix.css\"",
440 stable("edition", |o| {
444 "edition to use when compiling rust code (default: 2015)",
448 stable("color", |o| {
452 "Configure coloring of output:
453 auto = colorize, if output goes to a tty (default);
454 always = always colorize output;
455 never = never colorize output",
459 stable("error-format", |o| {
463 "How errors and other messages are produced",
468 o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
470 unstable("disable-minification", |o| {
471 o.optflagmulti("", "disable-minification", "Disable minification applied on JS files")
473 stable("allow", |o| o.optmulti("A", "allow", "Set lint allowed", "LINT")),
474 stable("warn", |o| o.optmulti("W", "warn", "Set lint warnings", "LINT")),
475 stable("force-warn", |o| o.optmulti("", "force-warn", "Set lint force-warn", "LINT")),
476 stable("deny", |o| o.optmulti("D", "deny", "Set lint denied", "LINT")),
477 stable("forbid", |o| o.optmulti("F", "forbid", "Set lint forbidden", "LINT")),
478 stable("cap-lints", |o| {
482 "Set the most restrictive lint level. \
483 More restrictive lints are capped at this \
484 level. By default, it is at `forbid` level.",
488 unstable("index-page", |o| {
489 o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
491 unstable("enable-index-page", |o| {
492 o.optflagmulti("", "enable-index-page", "To enable generation of the index page")
494 unstable("static-root-path", |o| {
498 "Path string to force loading static files from in output pages. \
499 If not set, uses combinations of '../' to reach the documentation root.",
503 unstable("disable-per-crate-search", |o| {
506 "disable-per-crate-search",
507 "disables generating the crate selector on the search box",
510 unstable("persist-doctests", |o| {
514 "Directory to persist doctest executables into",
518 unstable("show-coverage", |o| {
522 "calculate percentage of public items with documentation",
525 unstable("enable-per-target-ignores", |o| {
528 "enable-per-target-ignores",
529 "parse ignore-foo for ignoring doctests on a per-target basis",
532 unstable("runtool", |o| {
537 "The tool to run tests with when building for a different target than host",
540 unstable("runtool-arg", |o| {
545 "One (of possibly many) arguments to pass to the runtool",
548 unstable("test-builder", |o| {
549 o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH")
551 unstable("check", |o| o.optflagmulti("", "check", "Run rustdoc checks")),
552 unstable("generate-redirect-map", |o| {
555 "generate-redirect-map",
556 "Generate JSON file at the top level instead of generating HTML redirection files",
559 unstable("emit", |o| {
563 "Comma separated list of types of output for rustdoc to emit",
564 "[unversioned-shared-resources,toolchain-shared-resources,invocation-specific]",
567 unstable("no-run", |o| {
568 o.optflagmulti("", "no-run", "Compile doctests without running them")
570 unstable("show-type-layout", |o| {
571 o.optflagmulti("", "show-type-layout", "Include the memory layout of types in the docs")
573 unstable("nocapture", |o| {
574 o.optflag("", "nocapture", "Don't capture stdout and stderr of tests")
576 unstable("generate-link-to-definition", |o| {
579 "generate-link-to-definition",
580 "Make the identifiers in the HTML source code pages navigable",
583 unstable("scrape-examples-output-path", |o| {
586 "scrape-examples-output-path",
588 "collect function call information and output at the given path",
591 unstable("scrape-examples-target-crate", |o| {
594 "scrape-examples-target-crate",
596 "collect function call information for functions from the target crate",
599 unstable("with-examples", |o| {
604 "path to function call information (for displaying examples in the documentation)",
607 // deprecated / removed options
608 stable("plugin-path", |o| {
612 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
613 for more information",
617 stable("passes", |o| {
621 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
622 for more information",
626 stable("plugins", |o| {
630 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
631 for more information",
635 stable("no-default", |o| {
639 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
640 for more information",
647 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
648 for more information",
655 fn usage(argv0: &str) {
656 let mut options = getopts::Options::new();
657 for option in opts() {
658 (option.apply)(&mut options);
660 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
661 println!(" @path Read newline separated options from `path`\n");
663 "More information available at {}/rustdoc/what-is-rustdoc.html",
664 DOC_RUST_LANG_ORG_CHANNEL
668 /// A result type used by several functions under `main()`.
669 type MainResult = Result<(), ErrorReported>;
671 fn main_args(at_args: &[String]) -> MainResult {
672 let args = rustc_driver::args::arg_expand_all(at_args);
674 let mut options = getopts::Options::new();
675 for option in opts() {
676 (option.apply)(&mut options);
678 let matches = match options.parse(&args[1..]) {
681 early_error(ErrorOutputType::default(), &err.to_string());
685 // Note that we discard any distinction between different non-zero exit
686 // codes from `from_matches` here.
687 let options = match config::Options::from_matches(&matches) {
689 Err(code) => return if code == 0 { Ok(()) } else { Err(ErrorReported) },
691 rustc_interface::util::run_in_thread_pool_with_globals(
693 1, // this runs single-threaded, even in a parallel compiler
695 move || main_options(options),
699 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
703 diag.struct_err(&err).emit();
709 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
711 renderopts: config::RenderOptions,
712 cache: formats::cache::Cache,
715 match formats::run_format::<T>(krate, renderopts, cache, tcx) {
719 tcx.sess.struct_err(&format!("couldn't generate documentation: {}", e.error));
720 let file = e.file.display().to_string();
724 msg.note(&format!("failed to create or modify \"{}\"", file)).emit()
731 fn main_options(options: config::Options) -> MainResult {
732 let diag = core::new_handler(options.error_format, None, &options.debugging_opts);
734 match (options.should_test, options.markdown_input()) {
735 (true, true) => return wrap_return(&diag, markdown::test(options)),
736 (true, false) => return doctest::run(options),
740 markdown::render(&options.input, options.render_options, options.edition),
746 // need to move these items separately because we lose them by the time the closure is called,
747 // but we can't create the Handler ahead of time because it's not Send
748 let show_coverage = options.show_coverage;
749 let run_check = options.run_check;
751 // First, parse the crate and extract all relevant information.
752 info!("starting to run rustc");
754 // Interpret the input file as a rust source file, passing it through the
755 // compiler all the way through the analysis passes. The rustdoc output is
756 // then generated from the cleaned AST of the crate. This runs all the
757 // plug/cleaning passes.
758 let crate_version = options.crate_version.clone();
760 let output_format = options.output_format;
761 // FIXME: fix this clone (especially render_options)
762 let externs = options.externs.clone();
763 let render_options = options.render_options.clone();
764 let scrape_examples_options = options.scrape_examples_options.clone();
765 let config = core::create_config(options);
767 interface::create_compiler_and_run(config, |compiler| {
768 compiler.enter(|queries| {
769 let sess = compiler.session();
771 if sess.opts.describe_lints {
772 let (_, lint_store) = &*queries.register_plugins()?.peek();
773 describe_lints(sess, lint_store, true);
777 // We need to hold on to the complete resolver, so we cause everything to be
778 // cloned for the analysis passes to use. Suboptimal, but necessary in the
779 // current architecture.
780 // FIXME(#83761): Resolver cloning can lead to inconsistencies between data in the
781 // two copies because one of the copies can be modified after `TyCtxt` construction.
782 let (resolver, resolver_caches) = {
783 let (krate, resolver, _) = &*abort_on_err(queries.expansion(), sess).peek();
784 let resolver_caches = resolver.borrow_mut().access(|resolver| {
785 collect_intra_doc_links::early_resolve_intra_doc_links(resolver, krate, externs)
787 (resolver.clone(), resolver_caches)
790 if sess.diagnostic().has_errors_or_lint_errors() {
791 sess.fatal("Compilation failed, aborting rustdoc");
794 let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).peek_mut();
796 global_ctxt.enter(|tcx| {
797 let (krate, render_opts, mut cache) = sess.time("run_global_ctxt", || {
798 core::run_global_ctxt(
807 info!("finished with rustc");
809 if let Some(options) = scrape_examples_options {
810 return scrape_examples::run(krate, render_opts, cache, tcx, options);
813 cache.crate_version = crate_version;
816 // if we ran coverage, bail early, we don't need to also generate docs at this point
817 // (also we didn't load in any of the useful passes)
819 } else if run_check {
820 // Since we're in "check" mode, no need to generate anything beyond this point.
824 info!("going to format");
825 match output_format {
826 config::OutputFormat::Html => sess.time("render_html", || {
827 run_renderer::<html::render::Context<'_>>(krate, render_opts, cache, tcx)
829 config::OutputFormat::Json => sess.time("render_json", || {
830 run_renderer::<json::JsonRenderer<'_>>(krate, render_opts, cache, tcx)