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