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