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