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