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