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