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