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