]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Rollup merge of #83655 - sebpop:arm64-outline-atomics, r=workingjubilee
[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(in_band_lifetimes)]
12 #![feature(nll)]
13 #![feature(test)]
14 #![feature(crate_visibility_modifier)]
15 #![feature(never_type)]
16 #![feature(once_cell)]
17 #![feature(type_ascription)]
18 #![recursion_limit = "256"]
19 #![warn(rustc::internal)]
20
21 #[macro_use]
22 extern crate tracing;
23
24 // N.B. these need `extern crate` even in 2018 edition
25 // because they're loaded implicitly from the sysroot.
26 // The reason they're loaded from the sysroot is because
27 // the rustdoc artifacts aren't stored in rustc's cargo target directory.
28 // So if `rustc` was specified in Cargo.toml, this would spuriously rebuild crates.
29 //
30 // Dependencies listed in Cargo.toml do not need `extern crate`.
31
32 extern crate rustc_ast;
33 extern crate rustc_ast_lowering;
34 extern crate rustc_ast_pretty;
35 extern crate rustc_attr;
36 extern crate rustc_const_eval;
37 extern crate rustc_data_structures;
38 extern crate rustc_driver;
39 extern crate rustc_errors;
40 extern crate rustc_expand;
41 extern crate rustc_feature;
42 extern crate rustc_hir;
43 extern crate rustc_hir_pretty;
44 extern crate rustc_index;
45 extern crate rustc_infer;
46 extern crate rustc_interface;
47 extern crate rustc_lexer;
48 extern crate rustc_lint;
49 extern crate rustc_lint_defs;
50 extern crate rustc_metadata;
51 extern crate rustc_middle;
52 extern crate rustc_parse;
53 extern crate rustc_passes;
54 extern crate rustc_resolve;
55 extern crate rustc_session;
56 extern crate rustc_span;
57 extern crate rustc_target;
58 extern crate rustc_trait_selection;
59 extern crate rustc_typeck;
60 extern crate test;
61
62 #[cfg(feature = "jemalloc")]
63 extern crate tikv_jemalloc_sys;
64 #[cfg(feature = "jemalloc")]
65 use tikv_jemalloc_sys as jemalloc_sys;
66 #[cfg(feature = "jemalloc")]
67 extern crate tikv_jemallocator;
68 #[cfg(feature = "jemalloc")]
69 use tikv_jemallocator as jemallocator;
70
71 use std::default::Default;
72 use std::env;
73 use std::process;
74
75 use rustc_driver::{abort_on_err, describe_lints};
76 use rustc_errors::ErrorReported;
77 use rustc_interface::interface;
78 use rustc_middle::ty::TyCtxt;
79 use rustc_session::config::{make_crate_type_option, ErrorOutputType, RustcOptGroup};
80 use rustc_session::getopts;
81 use rustc_session::{early_error, early_warn};
82
83 use crate::clean::utils::DOC_RUST_LANG_ORG_CHANNEL;
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.optflagmulti("h", "help", "show this help message")),
273         stable("V", |o| o.optflagmulti("V", "version", "print rustdoc's version")),
274         stable("v", |o| o.optflagmulti("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(
291                 "",
292                 "extern-html-root-url",
293                 "base URL to use for dependencies; for example, \
294                  \"std=/doc\" links std::vec::Vec to /doc/std/vec/struct.Vec.html",
295                 "NAME=URL",
296             )
297         }),
298         unstable("extern-html-root-takes-precedence", |o| {
299             o.optflagmulti(
300                 "",
301                 "extern-html-root-takes-precedence",
302                 "give precedence to `--extern-html-root-url`, not `html_root_url`",
303             )
304         }),
305         stable("plugin-path", |o| o.optmulti("", "plugin-path", "removed", "DIR")),
306         stable("C", |o| {
307             o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
308         }),
309         stable("passes", |o| {
310             o.optmulti(
311                 "",
312                 "passes",
313                 "list of passes to also run, you might want to pass it multiple times; a value of \
314                  `list` will print available passes",
315                 "PASSES",
316             )
317         }),
318         stable("plugins", |o| o.optmulti("", "plugins", "removed", "PLUGINS")),
319         stable("no-default", |o| o.optflagmulti("", "no-defaults", "don't run the default passes")),
320         stable("document-private-items", |o| {
321             o.optflagmulti("", "document-private-items", "document private items")
322         }),
323         unstable("document-hidden-items", |o| {
324             o.optflagmulti("", "document-hidden-items", "document items that have doc(hidden)")
325         }),
326         stable("test", |o| o.optflagmulti("", "test", "run code examples as tests")),
327         stable("test-args", |o| {
328             o.optmulti("", "test-args", "arguments to pass to the test runner", "ARGS")
329         }),
330         unstable("test-run-directory", |o| {
331             o.optopt(
332                 "",
333                 "test-run-directory",
334                 "The working directory in which to run tests",
335                 "PATH",
336             )
337         }),
338         stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
339         stable("markdown-css", |o| {
340             o.optmulti(
341                 "",
342                 "markdown-css",
343                 "CSS files to include via <link> in a rendered Markdown file",
344                 "FILES",
345             )
346         }),
347         stable("html-in-header", |o| {
348             o.optmulti(
349                 "",
350                 "html-in-header",
351                 "files to include inline in the <head> section of a rendered Markdown file \
352                  or generated documentation",
353                 "FILES",
354             )
355         }),
356         stable("html-before-content", |o| {
357             o.optmulti(
358                 "",
359                 "html-before-content",
360                 "files to include inline between <body> and the content of a rendered \
361                  Markdown file or generated documentation",
362                 "FILES",
363             )
364         }),
365         stable("html-after-content", |o| {
366             o.optmulti(
367                 "",
368                 "html-after-content",
369                 "files to include inline between the content and </body> of a rendered \
370                  Markdown file or generated documentation",
371                 "FILES",
372             )
373         }),
374         unstable("markdown-before-content", |o| {
375             o.optmulti(
376                 "",
377                 "markdown-before-content",
378                 "files to include inline between <body> and the content of a rendered \
379                  Markdown file or generated documentation",
380                 "FILES",
381             )
382         }),
383         unstable("markdown-after-content", |o| {
384             o.optmulti(
385                 "",
386                 "markdown-after-content",
387                 "files to include inline between the content and </body> of a rendered \
388                  Markdown file or generated documentation",
389                 "FILES",
390             )
391         }),
392         stable("markdown-playground-url", |o| {
393             o.optopt("", "markdown-playground-url", "URL to send code snippets to", "URL")
394         }),
395         stable("markdown-no-toc", |o| {
396             o.optflagmulti("", "markdown-no-toc", "don't include table of contents")
397         }),
398         stable("e", |o| {
399             o.optopt(
400                 "e",
401                 "extend-css",
402                 "To add some CSS rules with a given file to generate doc with your \
403                  own theme. However, your theme might break if the rustdoc's generated HTML \
404                  changes, so be careful!",
405                 "PATH",
406             )
407         }),
408         unstable("Z", |o| {
409             o.optmulti("Z", "", "internal and debugging options (only on nightly build)", "FLAG")
410         }),
411         stable("sysroot", |o| o.optopt("", "sysroot", "Override the system root", "PATH")),
412         unstable("playground-url", |o| {
413             o.optopt(
414                 "",
415                 "playground-url",
416                 "URL to send code snippets to, may be reset by --markdown-playground-url \
417                  or `#![doc(html_playground_url=...)]`",
418                 "URL",
419             )
420         }),
421         unstable("display-doctest-warnings", |o| {
422             o.optflagmulti(
423                 "",
424                 "display-doctest-warnings",
425                 "show warnings that originate in doctests",
426             )
427         }),
428         stable("crate-version", |o| {
429             o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
430         }),
431         unstable("sort-modules-by-appearance", |o| {
432             o.optflagmulti(
433                 "",
434                 "sort-modules-by-appearance",
435                 "sort modules by where they appear in the program, rather than alphabetically",
436             )
437         }),
438         stable("default-theme", |o| {
439             o.optopt(
440                 "",
441                 "default-theme",
442                 "Set the default theme. THEME should be the theme name, generally lowercase. \
443                  If an unknown default theme is specified, the builtin default is used. \
444                  The set of themes, and the rustdoc built-in default, are not stable.",
445                 "THEME",
446             )
447         }),
448         unstable("default-setting", |o| {
449             o.optmulti(
450                 "",
451                 "default-setting",
452                 "Default value for a rustdoc setting (used when \"rustdoc-SETTING\" is absent \
453                  from web browser Local Storage). If VALUE is not supplied, \"true\" is used. \
454                  Supported SETTINGs and VALUEs are not documented and not stable.",
455                 "SETTING[=VALUE]",
456             )
457         }),
458         stable("theme", |o| {
459             o.optmulti(
460                 "",
461                 "theme",
462                 "additional themes which will be added to the generated docs",
463                 "FILES",
464             )
465         }),
466         stable("check-theme", |o| {
467             o.optmulti("", "check-theme", "check if given theme is valid", "FILES")
468         }),
469         unstable("resource-suffix", |o| {
470             o.optopt(
471                 "",
472                 "resource-suffix",
473                 "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
474                  \"light-suffix.css\"",
475                 "PATH",
476             )
477         }),
478         stable("edition", |o| {
479             o.optopt(
480                 "",
481                 "edition",
482                 "edition to use when compiling rust code (default: 2015)",
483                 "EDITION",
484             )
485         }),
486         stable("color", |o| {
487             o.optopt(
488                 "",
489                 "color",
490                 "Configure coloring of output:
491                                           auto   = colorize, if output goes to a tty (default);
492                                           always = always colorize output;
493                                           never  = never colorize output",
494                 "auto|always|never",
495             )
496         }),
497         stable("error-format", |o| {
498             o.optopt(
499                 "",
500                 "error-format",
501                 "How errors and other messages are produced",
502                 "human|json|short",
503             )
504         }),
505         stable("json", |o| {
506             o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
507         }),
508         unstable("disable-minification", |o| {
509             o.optflagmulti("", "disable-minification", "Disable minification applied on JS files")
510         }),
511         stable("allow", |o| o.optmulti("A", "allow", "Set lint allowed", "LINT")),
512         stable("warn", |o| o.optmulti("W", "warn", "Set lint warnings", "LINT")),
513         stable("force-warn", |o| o.optmulti("", "force-warn", "Set lint force-warn", "LINT")),
514         stable("deny", |o| o.optmulti("D", "deny", "Set lint denied", "LINT")),
515         stable("forbid", |o| o.optmulti("F", "forbid", "Set lint forbidden", "LINT")),
516         stable("cap-lints", |o| {
517             o.optmulti(
518                 "",
519                 "cap-lints",
520                 "Set the most restrictive lint level. \
521                  More restrictive lints are capped at this \
522                  level. By default, it is at `forbid` level.",
523                 "LEVEL",
524             )
525         }),
526         unstable("index-page", |o| {
527             o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
528         }),
529         unstable("enable-index-page", |o| {
530             o.optflagmulti("", "enable-index-page", "To enable generation of the index page")
531         }),
532         unstable("static-root-path", |o| {
533             o.optopt(
534                 "",
535                 "static-root-path",
536                 "Path string to force loading static files from in output pages. \
537                  If not set, uses combinations of '../' to reach the documentation root.",
538                 "PATH",
539             )
540         }),
541         unstable("disable-per-crate-search", |o| {
542             o.optflagmulti(
543                 "",
544                 "disable-per-crate-search",
545                 "disables generating the crate selector on the search box",
546             )
547         }),
548         unstable("persist-doctests", |o| {
549             o.optopt(
550                 "",
551                 "persist-doctests",
552                 "Directory to persist doctest executables into",
553                 "PATH",
554             )
555         }),
556         unstable("show-coverage", |o| {
557             o.optflagmulti(
558                 "",
559                 "show-coverage",
560                 "calculate percentage of public items with documentation",
561             )
562         }),
563         unstable("enable-per-target-ignores", |o| {
564             o.optflagmulti(
565                 "",
566                 "enable-per-target-ignores",
567                 "parse ignore-foo for ignoring doctests on a per-target basis",
568             )
569         }),
570         unstable("runtool", |o| {
571             o.optopt(
572                 "",
573                 "runtool",
574                 "",
575                 "The tool to run tests with when building for a different target than host",
576             )
577         }),
578         unstable("runtool-arg", |o| {
579             o.optmulti(
580                 "",
581                 "runtool-arg",
582                 "",
583                 "One (of possibly many) arguments to pass to the runtool",
584             )
585         }),
586         unstable("test-builder", |o| {
587             o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH")
588         }),
589         unstable("check", |o| o.optflagmulti("", "check", "Run rustdoc checks")),
590         unstable("generate-redirect-map", |o| {
591             o.optflagmulti(
592                 "",
593                 "generate-redirect-map",
594                 "Generate JSON file at the top level instead of generating HTML redirection files",
595             )
596         }),
597         unstable("emit", |o| {
598             o.optmulti(
599                 "",
600                 "emit",
601                 "Comma separated list of types of output for rustdoc to emit",
602                 "[unversioned-shared-resources,toolchain-shared-resources,invocation-specific]",
603             )
604         }),
605         unstable("no-run", |o| {
606             o.optflagmulti("", "no-run", "Compile doctests without running them")
607         }),
608         unstable("show-type-layout", |o| {
609             o.optflagmulti("", "show-type-layout", "Include the memory layout of types in the docs")
610         }),
611         unstable("nocapture", |o| {
612             o.optflag("", "nocapture", "Don't capture stdout and stderr of tests")
613         }),
614         unstable("generate-link-to-definition", |o| {
615             o.optflag(
616                 "",
617                 "generate-link-to-definition",
618                 "Make the identifiers in the HTML source code pages navigable",
619             )
620         }),
621     ]
622 }
623
624 fn usage(argv0: &str) {
625     let mut options = getopts::Options::new();
626     for option in opts() {
627         (option.apply)(&mut options);
628     }
629     println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
630     println!("    @path               Read newline separated options from `path`\n");
631     println!(
632         "More information available at {}/rustdoc/what-is-rustdoc.html",
633         DOC_RUST_LANG_ORG_CHANNEL
634     );
635 }
636
637 /// A result type used by several functions under `main()`.
638 type MainResult = Result<(), ErrorReported>;
639
640 fn main_args(at_args: &[String]) -> MainResult {
641     let args = rustc_driver::args::arg_expand_all(at_args);
642
643     let mut options = getopts::Options::new();
644     for option in opts() {
645         (option.apply)(&mut options);
646     }
647     let matches = match options.parse(&args[1..]) {
648         Ok(m) => m,
649         Err(err) => {
650             early_error(ErrorOutputType::default(), &err.to_string());
651         }
652     };
653
654     // Note that we discard any distinction between different non-zero exit
655     // codes from `from_matches` here.
656     let options = match config::Options::from_matches(&matches) {
657         Ok(opts) => opts,
658         Err(code) => return if code == 0 { Ok(()) } else { Err(ErrorReported) },
659     };
660     rustc_interface::util::setup_callbacks_and_run_in_thread_pool_with_globals(
661         options.edition,
662         1, // this runs single-threaded, even in a parallel compiler
663         &None,
664         move || main_options(options),
665     )
666 }
667
668 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
669     match res {
670         Ok(()) => Ok(()),
671         Err(err) => {
672             diag.struct_err(&err).emit();
673             Err(ErrorReported)
674         }
675     }
676 }
677
678 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
679     krate: clean::Crate,
680     renderopts: config::RenderOptions,
681     cache: formats::cache::Cache,
682     tcx: TyCtxt<'tcx>,
683 ) -> MainResult {
684     match formats::run_format::<T>(krate, renderopts, cache, tcx) {
685         Ok(_) => Ok(()),
686         Err(e) => {
687             let mut msg =
688                 tcx.sess.struct_err(&format!("couldn't generate documentation: {}", e.error));
689             let file = e.file.display().to_string();
690             if file.is_empty() {
691                 msg.emit()
692             } else {
693                 msg.note(&format!("failed to create or modify \"{}\"", file)).emit()
694             }
695             Err(ErrorReported)
696         }
697     }
698 }
699
700 fn main_options(options: config::Options) -> MainResult {
701     let diag = core::new_handler(options.error_format, None, &options.debugging_opts);
702
703     match (options.should_test, options.markdown_input()) {
704         (true, true) => return wrap_return(&diag, markdown::test(options)),
705         (true, false) => return doctest::run(options),
706         (false, true) => {
707             return wrap_return(
708                 &diag,
709                 markdown::render(&options.input, options.render_options, options.edition),
710             );
711         }
712         (false, false) => {}
713     }
714
715     // need to move these items separately because we lose them by the time the closure is called,
716     // but we can't create the Handler ahead of time because it's not Send
717     let show_coverage = options.show_coverage;
718     let run_check = options.run_check;
719
720     // First, parse the crate and extract all relevant information.
721     info!("starting to run rustc");
722
723     // Interpret the input file as a rust source file, passing it through the
724     // compiler all the way through the analysis passes. The rustdoc output is
725     // then generated from the cleaned AST of the crate. This runs all the
726     // plug/cleaning passes.
727     let crate_version = options.crate_version.clone();
728
729     let default_passes = options.default_passes;
730     let output_format = options.output_format;
731     // FIXME: fix this clone (especially render_options)
732     let manual_passes = options.manual_passes.clone();
733     let render_options = options.render_options.clone();
734     let config = core::create_config(options);
735
736     interface::create_compiler_and_run(config, |compiler| {
737         compiler.enter(|queries| {
738             let sess = compiler.session();
739
740             if sess.opts.describe_lints {
741                 let (_, lint_store) = &*queries.register_plugins()?.peek();
742                 describe_lints(sess, lint_store, true);
743                 return Ok(());
744             }
745
746             // We need to hold on to the complete resolver, so we cause everything to be
747             // cloned for the analysis passes to use. Suboptimal, but necessary in the
748             // current architecture.
749             let resolver = core::create_resolver(queries, &sess);
750
751             if sess.has_errors() {
752                 sess.fatal("Compilation failed, aborting rustdoc");
753             }
754
755             let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).peek_mut();
756
757             global_ctxt.enter(|tcx| {
758                 let (krate, render_opts, mut cache) = sess.time("run_global_ctxt", || {
759                     core::run_global_ctxt(
760                         tcx,
761                         resolver,
762                         default_passes,
763                         manual_passes,
764                         render_options,
765                         output_format,
766                     )
767                 });
768                 info!("finished with rustc");
769
770                 cache.crate_version = crate_version;
771
772                 if show_coverage {
773                     // if we ran coverage, bail early, we don't need to also generate docs at this point
774                     // (also we didn't load in any of the useful passes)
775                     return Ok(());
776                 } else if run_check {
777                     // Since we're in "check" mode, no need to generate anything beyond this point.
778                     return Ok(());
779                 }
780
781                 info!("going to format");
782                 match output_format {
783                     config::OutputFormat::Html => sess.time("render_html", || {
784                         run_renderer::<html::render::Context<'_>>(krate, render_opts, cache, tcx)
785                     }),
786                     config::OutputFormat::Json => sess.time("render_json", || {
787                         run_renderer::<json::JsonRenderer<'_>>(krate, render_opts, cache, tcx)
788                     }),
789                 }
790             })
791         })
792     })
793 }