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