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