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