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