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