]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Rollup merge of #92640 - compiler-errors:array-deref-on-newtype, r=lcnr
[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(box_syntax)]
11 #![feature(let_else)]
12 #![feature(nll)]
13 #![feature(test)]
14 #![feature(crate_visibility_modifier)]
15 #![feature(never_type)]
16 #![feature(once_cell)]
17 #![feature(type_ascription)]
18 #![feature(iter_intersperse)]
19 #![recursion_limit = "256"]
20 #![warn(rustc::internal)]
21 #![allow(clippy::collapsible_if, clippy::collapsible_else_if)]
22
23 #[macro_use]
24 extern crate tracing;
25
26 // N.B. these need `extern crate` even in 2018 edition
27 // because they're loaded implicitly from the sysroot.
28 // The reason they're loaded from the sysroot is because
29 // the rustdoc artifacts aren't stored in rustc's cargo target directory.
30 // So if `rustc` was specified in Cargo.toml, this would spuriously rebuild crates.
31 //
32 // Dependencies listed in Cargo.toml do not need `extern crate`.
33
34 extern crate rustc_ast;
35 extern crate rustc_ast_lowering;
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 tikv_jemalloc_sys;
70 #[cfg(feature = "jemalloc")]
71 use tikv_jemalloc_sys as jemalloc_sys;
72
73 use std::default::Default;
74 use std::env::{self, VarError};
75 use std::io;
76 use std::process;
77
78 use rustc_driver::{abort_on_err, describe_lints};
79 use rustc_errors::ErrorReported;
80 use rustc_interface::interface;
81 use rustc_middle::ty::TyCtxt;
82 use rustc_session::config::{make_crate_type_option, ErrorOutputType, RustcOptGroup};
83 use rustc_session::getopts;
84 use rustc_session::{early_error, early_warn};
85
86 use crate::clean::utils::DOC_RUST_LANG_ORG_CHANNEL;
87 use crate::passes::collect_intra_doc_links;
88
89 /// A macro to create a FxHashMap.
90 ///
91 /// Example:
92 ///
93 /// ```
94 /// let letters = map!{"a" => "b", "c" => "d"};
95 /// ```
96 ///
97 /// Trailing commas are allowed.
98 /// Commas between elements are required (even if the expression is a block).
99 macro_rules! map {
100     ($( $key: expr => $val: expr ),* $(,)*) => {{
101         let mut map = ::rustc_data_structures::fx::FxHashMap::default();
102         $( map.insert($key, $val); )*
103         map
104     }}
105 }
106
107 mod clean;
108 mod config;
109 mod core;
110 mod docfs;
111 mod doctest;
112 mod error;
113 mod externalfiles;
114 mod fold;
115 mod formats;
116 // used by the error-index generator, so it needs to be public
117 pub mod html;
118 mod json;
119 crate mod lint;
120 mod markdown;
121 mod passes;
122 mod scrape_examples;
123 mod theme;
124 mod visit;
125 mod visit_ast;
126 mod visit_lib;
127
128 pub fn main() {
129     // See docs in https://github.com/rust-lang/rust/blob/master/compiler/rustc/src/main.rs
130     // about jemalloc.
131     #[cfg(feature = "jemalloc")]
132     {
133         use std::os::raw::{c_int, c_void};
134
135         #[used]
136         static _F1: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::calloc;
137         #[used]
138         static _F2: unsafe extern "C" fn(*mut *mut c_void, usize, usize) -> c_int =
139             jemalloc_sys::posix_memalign;
140         #[used]
141         static _F3: unsafe extern "C" fn(usize, usize) -> *mut c_void = jemalloc_sys::aligned_alloc;
142         #[used]
143         static _F4: unsafe extern "C" fn(usize) -> *mut c_void = jemalloc_sys::malloc;
144         #[used]
145         static _F5: unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void = jemalloc_sys::realloc;
146         #[used]
147         static _F6: unsafe extern "C" fn(*mut c_void) = jemalloc_sys::free;
148
149         #[cfg(target_os = "macos")]
150         {
151             extern "C" {
152                 fn _rjem_je_zone_register();
153             }
154
155             #[used]
156             static _F7: unsafe extern "C" fn() = _rjem_je_zone_register;
157         }
158     }
159
160     rustc_driver::set_sigpipe_handler();
161     rustc_driver::install_ice_hook();
162
163     // When using CI artifacts (with `download_stage1 = true`), tracing is unconditionally built
164     // with `--features=static_max_level_info`, which disables almost all rustdoc logging. To avoid
165     // this, compile our own version of `tracing` that logs all levels.
166     // NOTE: this compiles both versions of tracing unconditionally, because
167     // - The compile time hit is not that bad, especially compared to rustdoc's incremental times, and
168     // - Otherwise, there's no warning that logging is being ignored when `download_stage1 = true`.
169     // NOTE: The reason this doesn't show double logging when `download_stage1 = false` and
170     // `debug_logging = true` is because all rustc logging goes to its version of tracing (the one
171     // in the sysroot), and all of rustdoc's logging goes to its version (the one in Cargo.toml).
172     init_logging();
173     rustc_driver::init_env_logger("RUSTDOC_LOG");
174
175     let exit_code = rustc_driver::catch_with_exit_code(|| match get_args() {
176         Some(args) => main_args(&args),
177         _ => Err(ErrorReported),
178     });
179     process::exit(exit_code);
180 }
181
182 fn init_logging() {
183     let color_logs = match std::env::var("RUSTDOC_LOG_COLOR").as_deref() {
184         Ok("always") => true,
185         Ok("never") => false,
186         Ok("auto") | Err(VarError::NotPresent) => atty::is(atty::Stream::Stdout),
187         Ok(value) => early_error(
188             ErrorOutputType::default(),
189             &format!("invalid log color value '{}': expected one of always, never, or auto", value),
190         ),
191         Err(VarError::NotUnicode(value)) => early_error(
192             ErrorOutputType::default(),
193             &format!(
194                 "invalid log color value '{}': expected one of always, never, or auto",
195                 value.to_string_lossy()
196             ),
197         ),
198     };
199     let filter = tracing_subscriber::EnvFilter::from_env("RUSTDOC_LOG");
200     let layer = tracing_tree::HierarchicalLayer::default()
201         .with_writer(io::stderr)
202         .with_indent_lines(true)
203         .with_ansi(color_logs)
204         .with_targets(true)
205         .with_wraparound(10)
206         .with_verbose_exit(true)
207         .with_verbose_entry(true)
208         .with_indent_amount(2);
209     #[cfg(parallel_compiler)]
210     let layer = layer.with_thread_ids(true).with_thread_names(true);
211
212     use tracing_subscriber::layer::SubscriberExt;
213     let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
214     tracing::subscriber::set_global_default(subscriber).unwrap();
215 }
216
217 fn get_args() -> Option<Vec<String>> {
218     env::args_os()
219         .enumerate()
220         .map(|(i, arg)| {
221             arg.into_string()
222                 .map_err(|arg| {
223                     early_warn(
224                         ErrorOutputType::default(),
225                         &format!("Argument {} is not valid Unicode: {:?}", i, arg),
226                     );
227                 })
228                 .ok()
229         })
230         .collect()
231 }
232
233 fn opts() -> Vec<RustcOptGroup> {
234     let stable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::stable;
235     let unstable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::unstable;
236     vec![
237         stable("h", |o| o.optflagmulti("h", "help", "show this help message")),
238         stable("V", |o| o.optflagmulti("V", "version", "print rustdoc's version")),
239         stable("v", |o| o.optflagmulti("v", "verbose", "use verbose output")),
240         stable("w", |o| o.optopt("w", "output-format", "the output type to write", "[html]")),
241         stable("output", |o| {
242             o.optopt(
243                 "",
244                 "output",
245                 "Which directory to place the output. \
246                  This option is deprecated, use --out-dir instead.",
247                 "PATH",
248             )
249         }),
250         stable("o", |o| o.optopt("o", "out-dir", "which directory to place the output", "PATH")),
251         stable("crate-name", |o| {
252             o.optopt("", "crate-name", "specify the name of this crate", "NAME")
253         }),
254         make_crate_type_option(),
255         stable("L", |o| {
256             o.optmulti("L", "library-path", "directory to add to crate search path", "DIR")
257         }),
258         stable("cfg", |o| o.optmulti("", "cfg", "pass a --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", "", "internal and debugging 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         stable("json", |o| {
465             o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
466         }),
467         unstable("disable-minification", |o| {
468             o.optflagmulti("", "disable-minification", "Disable minification applied on JS files")
469         }),
470         stable("allow", |o| o.optmulti("A", "allow", "Set lint allowed", "LINT")),
471         stable("warn", |o| o.optmulti("W", "warn", "Set lint warnings", "LINT")),
472         stable("force-warn", |o| o.optmulti("", "force-warn", "Set lint force-warn", "LINT")),
473         stable("deny", |o| o.optmulti("D", "deny", "Set lint denied", "LINT")),
474         stable("forbid", |o| o.optmulti("F", "forbid", "Set lint forbidden", "LINT")),
475         stable("cap-lints", |o| {
476             o.optmulti(
477                 "",
478                 "cap-lints",
479                 "Set the most restrictive lint level. \
480                  More restrictive lints are capped at this \
481                  level. By default, it is at `forbid` level.",
482                 "LEVEL",
483             )
484         }),
485         unstable("index-page", |o| {
486             o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
487         }),
488         unstable("enable-index-page", |o| {
489             o.optflagmulti("", "enable-index-page", "To enable generation of the index page")
490         }),
491         unstable("static-root-path", |o| {
492             o.optopt(
493                 "",
494                 "static-root-path",
495                 "Path string to force loading static files from in output pages. \
496                  If not set, uses combinations of '../' to reach the documentation root.",
497                 "PATH",
498             )
499         }),
500         unstable("disable-per-crate-search", |o| {
501             o.optflagmulti(
502                 "",
503                 "disable-per-crate-search",
504                 "disables generating the crate selector on the search box",
505             )
506         }),
507         unstable("persist-doctests", |o| {
508             o.optopt(
509                 "",
510                 "persist-doctests",
511                 "Directory to persist doctest executables into",
512                 "PATH",
513             )
514         }),
515         unstable("show-coverage", |o| {
516             o.optflagmulti(
517                 "",
518                 "show-coverage",
519                 "calculate percentage of public items with documentation",
520             )
521         }),
522         unstable("enable-per-target-ignores", |o| {
523             o.optflagmulti(
524                 "",
525                 "enable-per-target-ignores",
526                 "parse ignore-foo for ignoring doctests on a per-target basis",
527             )
528         }),
529         unstable("runtool", |o| {
530             o.optopt(
531                 "",
532                 "runtool",
533                 "",
534                 "The tool to run tests with when building for a different target than host",
535             )
536         }),
537         unstable("runtool-arg", |o| {
538             o.optmulti(
539                 "",
540                 "runtool-arg",
541                 "",
542                 "One (of possibly many) arguments to pass to the runtool",
543             )
544         }),
545         unstable("test-builder", |o| {
546             o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH")
547         }),
548         unstable("check", |o| o.optflagmulti("", "check", "Run rustdoc checks")),
549         unstable("generate-redirect-map", |o| {
550             o.optflagmulti(
551                 "",
552                 "generate-redirect-map",
553                 "Generate JSON file at the top level instead of generating HTML redirection files",
554             )
555         }),
556         unstable("emit", |o| {
557             o.optmulti(
558                 "",
559                 "emit",
560                 "Comma separated list of types of output for rustdoc to emit",
561                 "[unversioned-shared-resources,toolchain-shared-resources,invocation-specific]",
562             )
563         }),
564         unstable("no-run", |o| {
565             o.optflagmulti("", "no-run", "Compile doctests without running them")
566         }),
567         unstable("show-type-layout", |o| {
568             o.optflagmulti("", "show-type-layout", "Include the memory layout of types in the docs")
569         }),
570         unstable("nocapture", |o| {
571             o.optflag("", "nocapture", "Don't capture stdout and stderr of tests")
572         }),
573         unstable("generate-link-to-definition", |o| {
574             o.optflag(
575                 "",
576                 "generate-link-to-definition",
577                 "Make the identifiers in the HTML source code pages navigable",
578             )
579         }),
580         unstable("scrape-examples-output-path", |o| {
581             o.optopt(
582                 "",
583                 "scrape-examples-output-path",
584                 "",
585                 "collect function call information and output at the given path",
586             )
587         }),
588         unstable("scrape-examples-target-crate", |o| {
589             o.optmulti(
590                 "",
591                 "scrape-examples-target-crate",
592                 "",
593                 "collect function call information for functions from the target crate",
594             )
595         }),
596         unstable("with-examples", |o| {
597             o.optmulti(
598                 "",
599                 "with-examples",
600                 "",
601                 "path to function call information (for displaying examples in the documentation)",
602             )
603         }),
604         // deprecated / removed options
605         stable("plugin-path", |o| {
606             o.optmulti(
607                 "",
608                 "plugin-path",
609                 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
610                 for more information",
611                 "DIR",
612             )
613         }),
614         stable("passes", |o| {
615             o.optmulti(
616                 "",
617                 "passes",
618                 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
619                 for more information",
620                 "PASSES",
621             )
622         }),
623         stable("plugins", |o| {
624             o.optmulti(
625                 "",
626                 "plugins",
627                 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
628                 for more information",
629                 "PLUGINS",
630             )
631         }),
632         stable("no-default", |o| {
633             o.optflagmulti(
634                 "",
635                 "no-defaults",
636                 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
637                 for more information",
638             )
639         }),
640         stable("r", |o| {
641             o.optopt(
642                 "r",
643                 "input-format",
644                 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
645                 for more information",
646                 "[rust]",
647             )
648         }),
649     ]
650 }
651
652 fn usage(argv0: &str) {
653     let mut options = getopts::Options::new();
654     for option in opts() {
655         (option.apply)(&mut options);
656     }
657     println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
658     println!("    @path               Read newline separated options from `path`\n");
659     println!(
660         "More information available at {}/rustdoc/what-is-rustdoc.html",
661         DOC_RUST_LANG_ORG_CHANNEL
662     );
663 }
664
665 /// A result type used by several functions under `main()`.
666 type MainResult = Result<(), ErrorReported>;
667
668 fn main_args(at_args: &[String]) -> MainResult {
669     let args = rustc_driver::args::arg_expand_all(at_args);
670
671     let mut options = getopts::Options::new();
672     for option in opts() {
673         (option.apply)(&mut options);
674     }
675     let matches = match options.parse(&args[1..]) {
676         Ok(m) => m,
677         Err(err) => {
678             early_error(ErrorOutputType::default(), &err.to_string());
679         }
680     };
681
682     // Note that we discard any distinction between different non-zero exit
683     // codes from `from_matches` here.
684     let options = match config::Options::from_matches(&matches) {
685         Ok(opts) => opts,
686         Err(code) => return if code == 0 { Ok(()) } else { Err(ErrorReported) },
687     };
688     rustc_interface::util::setup_callbacks_and_run_in_thread_pool_with_globals(
689         options.edition,
690         1, // this runs single-threaded, even in a parallel compiler
691         &None,
692         move || main_options(options),
693     )
694 }
695
696 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
697     match res {
698         Ok(()) => Ok(()),
699         Err(err) => {
700             diag.struct_err(&err).emit();
701             Err(ErrorReported)
702         }
703     }
704 }
705
706 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
707     krate: clean::Crate,
708     renderopts: config::RenderOptions,
709     cache: formats::cache::Cache,
710     tcx: TyCtxt<'tcx>,
711 ) -> MainResult {
712     match formats::run_format::<T>(krate, renderopts, cache, tcx) {
713         Ok(_) => Ok(()),
714         Err(e) => {
715             let mut msg =
716                 tcx.sess.struct_err(&format!("couldn't generate documentation: {}", e.error));
717             let file = e.file.display().to_string();
718             if file.is_empty() {
719                 msg.emit()
720             } else {
721                 msg.note(&format!("failed to create or modify \"{}\"", file)).emit()
722             }
723             Err(ErrorReported)
724         }
725     }
726 }
727
728 fn main_options(options: config::Options) -> MainResult {
729     let diag = core::new_handler(options.error_format, None, &options.debugging_opts);
730
731     match (options.should_test, options.markdown_input()) {
732         (true, true) => return wrap_return(&diag, markdown::test(options)),
733         (true, false) => return doctest::run(options),
734         (false, true) => {
735             return wrap_return(
736                 &diag,
737                 markdown::render(&options.input, options.render_options, options.edition),
738             );
739         }
740         (false, false) => {}
741     }
742
743     // need to move these items separately because we lose them by the time the closure is called,
744     // but we can't create the Handler ahead of time because it's not Send
745     let show_coverage = options.show_coverage;
746     let run_check = options.run_check;
747
748     // First, parse the crate and extract all relevant information.
749     info!("starting to run rustc");
750
751     // Interpret the input file as a rust source file, passing it through the
752     // compiler all the way through the analysis passes. The rustdoc output is
753     // then generated from the cleaned AST of the crate. This runs all the
754     // plug/cleaning passes.
755     let crate_version = options.crate_version.clone();
756
757     let output_format = options.output_format;
758     // FIXME: fix this clone (especially render_options)
759     let externs = options.externs.clone();
760     let render_options = options.render_options.clone();
761     let scrape_examples_options = options.scrape_examples_options.clone();
762     let config = core::create_config(options);
763
764     interface::create_compiler_and_run(config, |compiler| {
765         compiler.enter(|queries| {
766             let sess = compiler.session();
767
768             if sess.opts.describe_lints {
769                 let (_, lint_store) = &*queries.register_plugins()?.peek();
770                 describe_lints(sess, lint_store, true);
771                 return Ok(());
772             }
773
774             // We need to hold on to the complete resolver, so we cause everything to be
775             // cloned for the analysis passes to use. Suboptimal, but necessary in the
776             // current architecture.
777             // FIXME(#83761): Resolver cloning can lead to inconsistencies between data in the
778             // two copies because one of the copies can be modified after `TyCtxt` construction.
779             let (resolver, resolver_caches) = {
780                 let (krate, resolver, _) = &*abort_on_err(queries.expansion(), sess).peek();
781                 let resolver_caches = resolver.borrow_mut().access(|resolver| {
782                     collect_intra_doc_links::early_resolve_intra_doc_links(resolver, krate, externs)
783                 });
784                 (resolver.clone(), resolver_caches)
785             };
786
787             if sess.diagnostic().has_errors_or_lint_errors() {
788                 sess.fatal("Compilation failed, aborting rustdoc");
789             }
790
791             let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).peek_mut();
792
793             global_ctxt.enter(|tcx| {
794                 let (krate, render_opts, mut cache) = sess.time("run_global_ctxt", || {
795                     core::run_global_ctxt(
796                         tcx,
797                         resolver,
798                         resolver_caches,
799                         show_coverage,
800                         render_options,
801                         output_format,
802                     )
803                 });
804                 info!("finished with rustc");
805
806                 if let Some(options) = scrape_examples_options {
807                     return scrape_examples::run(krate, render_opts, cache, tcx, options);
808                 }
809
810                 cache.crate_version = crate_version;
811
812                 if show_coverage {
813                     // if we ran coverage, bail early, we don't need to also generate docs at this point
814                     // (also we didn't load in any of the useful passes)
815                     return Ok(());
816                 } else if run_check {
817                     // Since we're in "check" mode, no need to generate anything beyond this point.
818                     return Ok(());
819                 }
820
821                 info!("going to format");
822                 match output_format {
823                     config::OutputFormat::Html => sess.time("render_html", || {
824                         run_renderer::<html::render::Context<'_>>(krate, render_opts, cache, tcx)
825                     }),
826                     config::OutputFormat::Json => sess.time("render_json", || {
827                         run_renderer::<json::JsonRenderer<'_>>(krate, render_opts, cache, tcx)
828                     }),
829                 }
830             })
831         })
832     })
833 }