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