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