]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Rollup merge of #100930 - cuviper:podman-keep-id, r=jyn514
[rust.git] / src / librustdoc / lib.rs
1 #![doc(
2     html_root_url = "https://doc.rust-lang.org/nightly/",
3     html_playground_url = "https://play.rust-lang.org/"
4 )]
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_else)]
12 #![feature(test)]
13 #![feature(never_type)]
14 #![feature(once_cell)]
15 #![feature(type_ascription)]
16 #![feature(iter_intersperse)]
17 #![feature(type_alias_impl_trait)]
18 #![feature(generic_associated_types)]
19 #![recursion_limit = "256"]
20 #![warn(rustc::internal)]
21 #![allow(clippy::collapsible_if, clippy::collapsible_else_if)]
22 #![allow(rustc::potential_query_instability)]
23
24 #[macro_use]
25 extern crate tracing;
26
27 // N.B. these need `extern crate` even in 2018 edition
28 // because they're loaded implicitly from the sysroot.
29 // The reason they're loaded from the sysroot is because
30 // the rustdoc artifacts aren't stored in rustc's cargo target directory.
31 // So if `rustc` was specified in Cargo.toml, this would spuriously rebuild crates.
32 //
33 // Dependencies listed in Cargo.toml do not need `extern crate`.
34
35 extern crate rustc_ast;
36 extern crate rustc_ast_pretty;
37 extern crate rustc_attr;
38 extern crate rustc_const_eval;
39 extern crate rustc_data_structures;
40 extern crate rustc_driver;
41 extern crate rustc_errors;
42 extern crate rustc_expand;
43 extern crate rustc_feature;
44 extern crate rustc_hir;
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;
63 extern crate rustc_typeck;
64 extern crate test;
65
66 // See docs in https://github.com/rust-lang/rust/blob/master/compiler/rustc/src/main.rs
67 // about jemalloc.
68 #[cfg(feature = "jemalloc")]
69 extern crate jemalloc_sys;
70
71 use std::default::Default;
72 use std::env::{self, VarError};
73 use std::io;
74 use std::process;
75
76 use rustc_driver::abort_on_err;
77 use rustc_errors::ErrorGuaranteed;
78 use rustc_interface::interface;
79 use rustc_middle::ty::TyCtxt;
80 use rustc_session::config::{make_crate_type_option, ErrorOutputType, RustcOptGroup};
81 use rustc_session::getopts;
82 use rustc_session::{early_error, early_warn};
83
84 use crate::clean::utils::DOC_RUST_LANG_ORG_CHANNEL;
85 use crate::passes::collect_intra_doc_links;
86
87 /// A macro to create a FxHashMap.
88 ///
89 /// Example:
90 ///
91 /// ```ignore(cannot-test-this-because-non-exported-macro)
92 /// let letters = map!{"a" => "b", "c" => "d"};
93 /// ```
94 ///
95 /// Trailing commas are allowed.
96 /// Commas between elements are required (even if the expression is a block).
97 macro_rules! map {
98     ($( $key: expr => $val: expr ),* $(,)*) => {{
99         let mut map = ::rustc_data_structures::fx::FxHashMap::default();
100         $( map.insert($key, $val); )*
101         map
102     }}
103 }
104
105 mod clean;
106 mod config;
107 mod core;
108 mod docfs;
109 mod doctest;
110 mod error;
111 mod externalfiles;
112 mod fold;
113 mod formats;
114 // used by the error-index generator, so it needs to be public
115 pub mod html;
116 mod json;
117 pub(crate) mod lint;
118 mod markdown;
119 mod passes;
120 mod scrape_examples;
121 mod theme;
122 mod visit;
123 mod visit_ast;
124 mod visit_lib;
125
126 pub fn main() {
127     // See docs in https://github.com/rust-lang/rust/blob/master/compiler/rustc/src/main.rs
128     // about jemalloc.
129     #[cfg(feature = "jemalloc")]
130     {
131         use std::os::raw::{c_int, c_void};
132
133         #[used]
134         static _F1: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::calloc;
135         #[used]
136         static _F2: unsafe extern "C" fn(*mut *mut c_void, usize, usize) -> c_int =
137             jemalloc_sys::posix_memalign;
138         #[used]
139         static _F3: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::aligned_alloc;
140         #[used]
141         static _F4: unsafe extern "C" fn(usize) -> *mut c_void = jemalloc_sys::malloc;
142         #[used]
143         static _F5: unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void = jemalloc_sys::realloc;
144         #[used]
145         static _F6: unsafe extern "C" fn(*mut c_void) = jemalloc_sys::free;
146
147         #[cfg(target_os = "macos")]
148         {
149             extern "C" {
150                 fn _rjem_je_zone_register();
151             }
152
153             #[used]
154             static _F7: unsafe extern "C" fn() = _rjem_je_zone_register;
155         }
156     }
157
158     rustc_driver::set_sigpipe_handler();
159     rustc_driver::install_ice_hook();
160
161     // When using CI artifacts (with `download_stage1 = true`), tracing is unconditionally built
162     // with `--features=static_max_level_info`, which disables almost all rustdoc logging. To avoid
163     // this, compile our own version of `tracing` that logs all levels.
164     // NOTE: this compiles both versions of tracing unconditionally, because
165     // - The compile time hit is not that bad, especially compared to rustdoc's incremental times, and
166     // - Otherwise, there's no warning that logging is being ignored when `download_stage1 = true`.
167     // NOTE: The reason this doesn't show double logging when `download_stage1 = false` and
168     // `debug_logging = true` is because all rustc logging goes to its version of tracing (the one
169     // in the sysroot), and all of rustdoc's logging goes to its version (the one in Cargo.toml).
170     init_logging();
171     rustc_driver::init_env_logger("RUSTDOC_LOG");
172
173     let exit_code = rustc_driver::catch_with_exit_code(|| match get_args() {
174         Some(args) => main_args(&args),
175         _ => Err(ErrorGuaranteed::unchecked_claim_error_was_emitted()),
176     });
177     process::exit(exit_code);
178 }
179
180 fn init_logging() {
181     let color_logs = match std::env::var("RUSTDOC_LOG_COLOR").as_deref() {
182         Ok("always") => true,
183         Ok("never") => false,
184         Ok("auto") | Err(VarError::NotPresent) => atty::is(atty::Stream::Stdout),
185         Ok(value) => early_error(
186             ErrorOutputType::default(),
187             &format!("invalid log color value '{}': expected one of always, never, or auto", value),
188         ),
189         Err(VarError::NotUnicode(value)) => early_error(
190             ErrorOutputType::default(),
191             &format!(
192                 "invalid log color value '{}': expected one of always, never, or auto",
193                 value.to_string_lossy()
194             ),
195         ),
196     };
197     let filter = tracing_subscriber::EnvFilter::from_env("RUSTDOC_LOG");
198     let layer = tracing_tree::HierarchicalLayer::default()
199         .with_writer(io::stderr)
200         .with_indent_lines(true)
201         .with_ansi(color_logs)
202         .with_targets(true)
203         .with_wraparound(10)
204         .with_verbose_exit(true)
205         .with_verbose_entry(true)
206         .with_indent_amount(2);
207     #[cfg(parallel_compiler)]
208     let layer = layer.with_thread_ids(true).with_thread_names(true);
209
210     use tracing_subscriber::layer::SubscriberExt;
211     let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
212     tracing::subscriber::set_global_default(subscriber).unwrap();
213 }
214
215 fn get_args() -> Option<Vec<String>> {
216     env::args_os()
217         .enumerate()
218         .map(|(i, arg)| {
219             arg.into_string()
220                 .map_err(|arg| {
221                     early_warn(
222                         ErrorOutputType::default(),
223                         &format!("Argument {} is not valid Unicode: {:?}", i, arg),
224                     );
225                 })
226                 .ok()
227         })
228         .collect()
229 }
230
231 fn opts() -> Vec<RustcOptGroup> {
232     let stable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::stable;
233     let unstable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::unstable;
234     vec![
235         stable("h", |o| o.optflagmulti("h", "help", "show this help message")),
236         stable("V", |o| o.optflagmulti("V", "version", "print rustdoc's version")),
237         stable("v", |o| o.optflagmulti("v", "verbose", "use verbose output")),
238         stable("w", |o| o.optopt("w", "output-format", "the output type to write", "[html]")),
239         stable("output", |o| {
240             o.optopt(
241                 "",
242                 "output",
243                 "Which directory to place the output. \
244                  This option is deprecated, use --out-dir instead.",
245                 "PATH",
246             )
247         }),
248         stable("o", |o| o.optopt("o", "out-dir", "which directory to place the output", "PATH")),
249         stable("crate-name", |o| {
250             o.optopt("", "crate-name", "specify the name of this crate", "NAME")
251         }),
252         make_crate_type_option(),
253         stable("L", |o| {
254             o.optmulti("L", "library-path", "directory to add to crate search path", "DIR")
255         }),
256         stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
257         unstable("check-cfg", |o| o.optmulti("", "check-cfg", "pass a --check-cfg to rustc", "")),
258         stable("extern", |o| o.optmulti("", "extern", "pass an --extern to rustc", "NAME[=PATH]")),
259         unstable("extern-html-root-url", |o| {
260             o.optmulti(
261                 "",
262                 "extern-html-root-url",
263                 "base URL to use for dependencies; for example, \
264                  \"std=/doc\" links std::vec::Vec to /doc/std/vec/struct.Vec.html",
265                 "NAME=URL",
266             )
267         }),
268         unstable("extern-html-root-takes-precedence", |o| {
269             o.optflagmulti(
270                 "",
271                 "extern-html-root-takes-precedence",
272                 "give precedence to `--extern-html-root-url`, not `html_root_url`",
273             )
274         }),
275         stable("C", |o| {
276             o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
277         }),
278         stable("document-private-items", |o| {
279             o.optflagmulti("", "document-private-items", "document private items")
280         }),
281         unstable("document-hidden-items", |o| {
282             o.optflagmulti("", "document-hidden-items", "document items that have doc(hidden)")
283         }),
284         stable("test", |o| o.optflagmulti("", "test", "run code examples as tests")),
285         stable("test-args", |o| {
286             o.optmulti("", "test-args", "arguments to pass to the test runner", "ARGS")
287         }),
288         unstable("test-run-directory", |o| {
289             o.optopt(
290                 "",
291                 "test-run-directory",
292                 "The working directory in which to run tests",
293                 "PATH",
294             )
295         }),
296         stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
297         stable("markdown-css", |o| {
298             o.optmulti(
299                 "",
300                 "markdown-css",
301                 "CSS files to include via <link> in a rendered Markdown file",
302                 "FILES",
303             )
304         }),
305         stable("html-in-header", |o| {
306             o.optmulti(
307                 "",
308                 "html-in-header",
309                 "files to include inline in the <head> section of a rendered Markdown file \
310                  or generated documentation",
311                 "FILES",
312             )
313         }),
314         stable("html-before-content", |o| {
315             o.optmulti(
316                 "",
317                 "html-before-content",
318                 "files to include inline between <body> and the content of a rendered \
319                  Markdown file or generated documentation",
320                 "FILES",
321             )
322         }),
323         stable("html-after-content", |o| {
324             o.optmulti(
325                 "",
326                 "html-after-content",
327                 "files to include inline between the content and </body> of a rendered \
328                  Markdown file or generated documentation",
329                 "FILES",
330             )
331         }),
332         unstable("markdown-before-content", |o| {
333             o.optmulti(
334                 "",
335                 "markdown-before-content",
336                 "files to include inline between <body> and the content of a rendered \
337                  Markdown file or generated documentation",
338                 "FILES",
339             )
340         }),
341         unstable("markdown-after-content", |o| {
342             o.optmulti(
343                 "",
344                 "markdown-after-content",
345                 "files to include inline between the content and </body> of a rendered \
346                  Markdown file or generated documentation",
347                 "FILES",
348             )
349         }),
350         stable("markdown-playground-url", |o| {
351             o.optopt("", "markdown-playground-url", "URL to send code snippets to", "URL")
352         }),
353         stable("markdown-no-toc", |o| {
354             o.optflagmulti("", "markdown-no-toc", "don't include table of contents")
355         }),
356         stable("e", |o| {
357             o.optopt(
358                 "e",
359                 "extend-css",
360                 "To add some CSS rules with a given file to generate doc with your \
361                  own theme. However, your theme might break if the rustdoc's generated HTML \
362                  changes, so be careful!",
363                 "PATH",
364             )
365         }),
366         unstable("Z", |o| {
367             o.optmulti("Z", "", "unstable / perma-unstable options (only on nightly build)", "FLAG")
368         }),
369         stable("sysroot", |o| o.optopt("", "sysroot", "Override the system root", "PATH")),
370         unstable("playground-url", |o| {
371             o.optopt(
372                 "",
373                 "playground-url",
374                 "URL to send code snippets to, may be reset by --markdown-playground-url \
375                  or `#![doc(html_playground_url=...)]`",
376                 "URL",
377             )
378         }),
379         unstable("display-doctest-warnings", |o| {
380             o.optflagmulti(
381                 "",
382                 "display-doctest-warnings",
383                 "show warnings that originate in doctests",
384             )
385         }),
386         stable("crate-version", |o| {
387             o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
388         }),
389         unstable("sort-modules-by-appearance", |o| {
390             o.optflagmulti(
391                 "",
392                 "sort-modules-by-appearance",
393                 "sort modules by where they appear in the program, rather than alphabetically",
394             )
395         }),
396         stable("default-theme", |o| {
397             o.optopt(
398                 "",
399                 "default-theme",
400                 "Set the default theme. THEME should be the theme name, generally lowercase. \
401                  If an unknown default theme is specified, the builtin default is used. \
402                  The set of themes, and the rustdoc built-in default, are not stable.",
403                 "THEME",
404             )
405         }),
406         unstable("default-setting", |o| {
407             o.optmulti(
408                 "",
409                 "default-setting",
410                 "Default value for a rustdoc setting (used when \"rustdoc-SETTING\" is absent \
411                  from web browser Local Storage). If VALUE is not supplied, \"true\" is used. \
412                  Supported SETTINGs and VALUEs are not documented and not stable.",
413                 "SETTING[=VALUE]",
414             )
415         }),
416         stable("theme", |o| {
417             o.optmulti(
418                 "",
419                 "theme",
420                 "additional themes which will be added to the generated docs",
421                 "FILES",
422             )
423         }),
424         stable("check-theme", |o| {
425             o.optmulti("", "check-theme", "check if given theme is valid", "FILES")
426         }),
427         unstable("resource-suffix", |o| {
428             o.optopt(
429                 "",
430                 "resource-suffix",
431                 "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
432                  \"light-suffix.css\"",
433                 "PATH",
434             )
435         }),
436         stable("edition", |o| {
437             o.optopt(
438                 "",
439                 "edition",
440                 "edition to use when compiling rust code (default: 2015)",
441                 "EDITION",
442             )
443         }),
444         stable("color", |o| {
445             o.optopt(
446                 "",
447                 "color",
448                 "Configure coloring of output:
449                                           auto   = colorize, if output goes to a tty (default);
450                                           always = always colorize output;
451                                           never  = never colorize output",
452                 "auto|always|never",
453             )
454         }),
455         stable("error-format", |o| {
456             o.optopt(
457                 "",
458                 "error-format",
459                 "How errors and other messages are produced",
460                 "human|json|short",
461             )
462         }),
463         unstable("diagnostic-width", |o| {
464             o.optopt(
465                 "",
466                 "diagnostic-width",
467                 "Provide width of the output for truncated error messages",
468                 "WIDTH",
469             )
470         }),
471         stable("json", |o| {
472             o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
473         }),
474         unstable("disable-minification", |o| {
475             o.optflagmulti("", "disable-minification", "Disable minification applied on JS files")
476         }),
477         stable("allow", |o| o.optmulti("A", "allow", "Set lint allowed", "LINT")),
478         stable("warn", |o| o.optmulti("W", "warn", "Set lint warnings", "LINT")),
479         stable("force-warn", |o| o.optmulti("", "force-warn", "Set lint force-warn", "LINT")),
480         stable("deny", |o| o.optmulti("D", "deny", "Set lint denied", "LINT")),
481         stable("forbid", |o| o.optmulti("F", "forbid", "Set lint forbidden", "LINT")),
482         stable("cap-lints", |o| {
483             o.optmulti(
484                 "",
485                 "cap-lints",
486                 "Set the most restrictive lint level. \
487                  More restrictive lints are capped at this \
488                  level. By default, it is at `forbid` level.",
489                 "LEVEL",
490             )
491         }),
492         unstable("index-page", |o| {
493             o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
494         }),
495         unstable("enable-index-page", |o| {
496             o.optflagmulti("", "enable-index-page", "To enable generation of the index page")
497         }),
498         unstable("static-root-path", |o| {
499             o.optopt(
500                 "",
501                 "static-root-path",
502                 "Path string to force loading static files from in output pages. \
503                  If not set, uses combinations of '../' to reach the documentation root.",
504                 "PATH",
505             )
506         }),
507         unstable("disable-per-crate-search", |o| {
508             o.optflagmulti(
509                 "",
510                 "disable-per-crate-search",
511                 "disables generating the crate selector on the search box",
512             )
513         }),
514         unstable("persist-doctests", |o| {
515             o.optopt(
516                 "",
517                 "persist-doctests",
518                 "Directory to persist doctest executables into",
519                 "PATH",
520             )
521         }),
522         unstable("show-coverage", |o| {
523             o.optflagmulti(
524                 "",
525                 "show-coverage",
526                 "calculate percentage of public items with documentation",
527             )
528         }),
529         unstable("enable-per-target-ignores", |o| {
530             o.optflagmulti(
531                 "",
532                 "enable-per-target-ignores",
533                 "parse ignore-foo for ignoring doctests on a per-target basis",
534             )
535         }),
536         unstable("runtool", |o| {
537             o.optopt(
538                 "",
539                 "runtool",
540                 "",
541                 "The tool to run tests with when building for a different target than host",
542             )
543         }),
544         unstable("runtool-arg", |o| {
545             o.optmulti(
546                 "",
547                 "runtool-arg",
548                 "",
549                 "One (of possibly many) arguments to pass to the runtool",
550             )
551         }),
552         unstable("test-builder", |o| {
553             o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH")
554         }),
555         unstable("check", |o| o.optflagmulti("", "check", "Run rustdoc checks")),
556         unstable("generate-redirect-map", |o| {
557             o.optflagmulti(
558                 "",
559                 "generate-redirect-map",
560                 "Generate JSON file at the top level instead of generating HTML redirection files",
561             )
562         }),
563         unstable("emit", |o| {
564             o.optmulti(
565                 "",
566                 "emit",
567                 "Comma separated list of types of output for rustdoc to emit",
568                 "[unversioned-shared-resources,toolchain-shared-resources,invocation-specific]",
569             )
570         }),
571         unstable("no-run", |o| {
572             o.optflagmulti("", "no-run", "Compile doctests without running them")
573         }),
574         unstable("show-type-layout", |o| {
575             o.optflagmulti("", "show-type-layout", "Include the memory layout of types in the docs")
576         }),
577         unstable("nocapture", |o| {
578             o.optflag("", "nocapture", "Don't capture stdout and stderr of tests")
579         }),
580         unstable("generate-link-to-definition", |o| {
581             o.optflag(
582                 "",
583                 "generate-link-to-definition",
584                 "Make the identifiers in the HTML source code pages navigable",
585             )
586         }),
587         unstable("scrape-examples-output-path", |o| {
588             o.optopt(
589                 "",
590                 "scrape-examples-output-path",
591                 "",
592                 "collect function call information and output at the given path",
593             )
594         }),
595         unstable("scrape-examples-target-crate", |o| {
596             o.optmulti(
597                 "",
598                 "scrape-examples-target-crate",
599                 "",
600                 "collect function call information for functions from the target crate",
601             )
602         }),
603         unstable("scrape-tests", |o| {
604             o.optflag("", "scrape-tests", "Include test code when scraping examples")
605         }),
606         unstable("with-examples", |o| {
607             o.optmulti(
608                 "",
609                 "with-examples",
610                 "",
611                 "path to function call information (for displaying examples in the documentation)",
612             )
613         }),
614         // deprecated / removed options
615         stable("plugin-path", |o| {
616             o.optmulti(
617                 "",
618                 "plugin-path",
619                 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
620                 for more information",
621                 "DIR",
622             )
623         }),
624         stable("passes", |o| {
625             o.optmulti(
626                 "",
627                 "passes",
628                 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
629                 for more information",
630                 "PASSES",
631             )
632         }),
633         stable("plugins", |o| {
634             o.optmulti(
635                 "",
636                 "plugins",
637                 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
638                 for more information",
639                 "PLUGINS",
640             )
641         }),
642         stable("no-default", |o| {
643             o.optflagmulti(
644                 "",
645                 "no-defaults",
646                 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
647                 for more information",
648             )
649         }),
650         stable("r", |o| {
651             o.optopt(
652                 "r",
653                 "input-format",
654                 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
655                 for more information",
656                 "[rust]",
657             )
658         }),
659     ]
660 }
661
662 fn usage(argv0: &str) {
663     let mut options = getopts::Options::new();
664     for option in opts() {
665         (option.apply)(&mut options);
666     }
667     println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
668     println!("    @path               Read newline separated options from `path`\n");
669     println!(
670         "More information available at {}/rustdoc/what-is-rustdoc.html",
671         DOC_RUST_LANG_ORG_CHANNEL
672     );
673 }
674
675 /// A result type used by several functions under `main()`.
676 type MainResult = Result<(), ErrorGuaranteed>;
677
678 fn main_args(at_args: &[String]) -> MainResult {
679     let args = rustc_driver::args::arg_expand_all(at_args);
680
681     let mut options = getopts::Options::new();
682     for option in opts() {
683         (option.apply)(&mut options);
684     }
685     let matches = match options.parse(&args[1..]) {
686         Ok(m) => m,
687         Err(err) => {
688             early_error(ErrorOutputType::default(), &err.to_string());
689         }
690     };
691
692     // Note that we discard any distinction between different non-zero exit
693     // codes from `from_matches` here.
694     let options = match config::Options::from_matches(&matches, args) {
695         Ok(opts) => opts,
696         Err(code) => {
697             return if code == 0 {
698                 Ok(())
699             } else {
700                 Err(ErrorGuaranteed::unchecked_claim_error_was_emitted())
701             };
702         }
703     };
704     rustc_interface::util::run_in_thread_pool_with_globals(
705         options.edition,
706         1, // this runs single-threaded, even in a parallel compiler
707         move || main_options(options),
708     )
709 }
710
711 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
712     match res {
713         Ok(()) => Ok(()),
714         Err(err) => {
715             let reported = diag.struct_err(&err).emit();
716             Err(reported)
717         }
718     }
719 }
720
721 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
722     krate: clean::Crate,
723     renderopts: config::RenderOptions,
724     cache: formats::cache::Cache,
725     tcx: TyCtxt<'tcx>,
726 ) -> MainResult {
727     match formats::run_format::<T>(krate, renderopts, cache, tcx) {
728         Ok(_) => Ok(()),
729         Err(e) => {
730             let mut msg =
731                 tcx.sess.struct_err(&format!("couldn't generate documentation: {}", e.error));
732             let file = e.file.display().to_string();
733             if !file.is_empty() {
734                 msg.note(&format!("failed to create or modify \"{}\"", file));
735             }
736             Err(msg.emit())
737         }
738     }
739 }
740
741 fn main_options(options: config::Options) -> MainResult {
742     let diag = core::new_handler(
743         options.error_format,
744         None,
745         options.diagnostic_width,
746         &options.unstable_opts,
747     );
748
749     match (options.should_test, options.markdown_input()) {
750         (true, true) => return wrap_return(&diag, markdown::test(options)),
751         (true, false) => return doctest::run(options),
752         (false, true) => {
753             return wrap_return(
754                 &diag,
755                 markdown::render(&options.input, options.render_options, options.edition),
756             );
757         }
758         (false, false) => {}
759     }
760
761     // need to move these items separately because we lose them by the time the closure is called,
762     // but we can't create the Handler ahead of time because it's not Send
763     let show_coverage = options.show_coverage;
764     let run_check = options.run_check;
765
766     // First, parse the crate and extract all relevant information.
767     info!("starting to run rustc");
768
769     // Interpret the input file as a rust source file, passing it through the
770     // compiler all the way through the analysis passes. The rustdoc output is
771     // then generated from the cleaned AST of the crate. This runs all the
772     // plug/cleaning passes.
773     let crate_version = options.crate_version.clone();
774
775     let output_format = options.output_format;
776     // FIXME: fix this clone (especially render_options)
777     let externs = options.externs.clone();
778     let render_options = options.render_options.clone();
779     let scrape_examples_options = options.scrape_examples_options.clone();
780     let document_private = options.render_options.document_private;
781     let config = core::create_config(options);
782
783     interface::create_compiler_and_run(config, |compiler| {
784         let sess = compiler.session();
785
786         if sess.opts.describe_lints {
787             let mut lint_store = rustc_lint::new_lint_store(
788                 sess.opts.unstable_opts.no_interleave_lints,
789                 sess.enable_internal_lints(),
790             );
791             let registered_lints = if let Some(register_lints) = compiler.register_lints() {
792                 register_lints(sess, &mut lint_store);
793                 true
794             } else {
795                 false
796             };
797             rustc_driver::describe_lints(sess, &lint_store, registered_lints);
798             return Ok(());
799         }
800
801         compiler.enter(|queries| {
802             // We need to hold on to the complete resolver, so we cause everything to be
803             // cloned for the analysis passes to use. Suboptimal, but necessary in the
804             // current architecture.
805             // FIXME(#83761): Resolver cloning can lead to inconsistencies between data in the
806             // two copies because one of the copies can be modified after `TyCtxt` construction.
807             let (resolver, resolver_caches) = {
808                 let (krate, resolver, _) = &*abort_on_err(queries.expansion(), sess).peek();
809                 let resolver_caches = resolver.borrow_mut().access(|resolver| {
810                     collect_intra_doc_links::early_resolve_intra_doc_links(
811                         resolver,
812                         sess,
813                         krate,
814                         externs,
815                         document_private,
816                     )
817                 });
818                 (resolver.clone(), resolver_caches)
819             };
820
821             if sess.diagnostic().has_errors_or_lint_errors().is_some() {
822                 sess.fatal("Compilation failed, aborting rustdoc");
823             }
824
825             let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).peek_mut();
826
827             global_ctxt.enter(|tcx| {
828                 let (krate, render_opts, mut cache) = sess.time("run_global_ctxt", || {
829                     core::run_global_ctxt(
830                         tcx,
831                         resolver,
832                         resolver_caches,
833                         show_coverage,
834                         render_options,
835                         output_format,
836                     )
837                 });
838                 info!("finished with rustc");
839
840                 if let Some(options) = scrape_examples_options {
841                     return scrape_examples::run(krate, render_opts, cache, tcx, options);
842                 }
843
844                 cache.crate_version = crate_version;
845
846                 if show_coverage {
847                     // if we ran coverage, bail early, we don't need to also generate docs at this point
848                     // (also we didn't load in any of the useful passes)
849                     return Ok(());
850                 } else if run_check {
851                     // Since we're in "check" mode, no need to generate anything beyond this point.
852                     return Ok(());
853                 }
854
855                 info!("going to format");
856                 match output_format {
857                     config::OutputFormat::Html => sess.time("render_html", || {
858                         run_renderer::<html::render::Context<'_>>(krate, render_opts, cache, tcx)
859                     }),
860                     config::OutputFormat::Json => sess.time("render_json", || {
861                         run_renderer::<json::JsonRenderer<'_>>(krate, render_opts, cache, tcx)
862                     }),
863                 }
864             })
865         })
866     })
867 }