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(impl_trait_in_assoc_type)]
10 #![feature(iter_intersperse)]
11 #![feature(lazy_cell)]
12 #![feature(let_chains)]
13 #![feature(never_type)]
14 #![feature(round_char_boundary)]
15 #![feature(test)]
16 #![feature(type_alias_impl_trait)]
17 #![feature(type_ascription)]
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 extern crate thin_vec;
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 pulldown_cmark;
36 extern crate rustc_abi;
37 extern crate rustc_ast;
38 extern crate rustc_ast_pretty;
39 extern crate rustc_attr;
40 extern crate rustc_const_eval;
41 extern crate rustc_data_structures;
42 extern crate rustc_driver;
43 extern crate rustc_errors;
44 extern crate rustc_expand;
45 extern crate rustc_feature;
46 extern crate rustc_hir;
47 extern crate rustc_hir_analysis;
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 test;
67
68 // See docs in https://github.com/rust-lang/rust/blob/master/compiler/rustc/src/main.rs
69 // about jemalloc.
70 #[cfg(feature = "jemalloc")]
71 extern crate jemalloc_sys;
72
73 use std::env::{self, VarError};
74 use std::io::{self, IsTerminal};
75 use std::process;
76
77 use rustc_driver::abort_on_err;
78 use rustc_errors::ErrorGuaranteed;
79 use rustc_interface::interface;
80 use rustc_middle::ty::TyCtxt;
81 use rustc_session::config::{make_crate_type_option, ErrorOutputType, RustcOptGroup};
82 use rustc_session::{getopts, EarlyErrorHandler};
83
84 use crate::clean::utils::DOC_RUST_LANG_ORG_CHANNEL;
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
main()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 let mut handler = EarlyErrorHandler::new(ErrorOutputType::default());
158
159 rustc_driver::install_ice_hook(
160 "https://github.com/rust-lang/rust/issues/new\
161 ?labels=C-bug%2C+I-ICE%2C+T-rustdoc&template=ice.md",
162 |_| (),
163 );
164
165 // When using CI artifacts with `download-rustc`, tracing is unconditionally built
166 // with `--features=static_max_level_info`, which disables almost all rustdoc logging. To avoid
167 // this, compile our own version of `tracing` that logs all levels.
168 // NOTE: this compiles both versions of tracing unconditionally, because
169 // - The compile time hit is not that bad, especially compared to rustdoc's incremental times, and
170 // - Otherwise, there's no warning that logging is being ignored when `download-rustc` is enabled
171 // NOTE: The reason this doesn't show double logging when `download-rustc = false` and
172 // `debug_logging = true` is because all rustc logging goes to its version of tracing (the one
173 // in the sysroot), and all of rustdoc's logging goes to its version (the one in Cargo.toml).
174
175 init_logging(&handler);
176 rustc_driver::init_env_logger(&handler, "RUSTDOC_LOG");
177
178 let exit_code = rustc_driver::catch_with_exit_code(|| match get_args(&handler) {
179 Some(args) => main_args(&mut handler, &args),
180 _ =>
181 {
182 #[allow(deprecated)]
183 Err(ErrorGuaranteed::unchecked_claim_error_was_emitted())
184 }
185 });
186 process::exit(exit_code);
187 }
188
init_logging(handler: &EarlyErrorHandler)189 fn init_logging(handler: &EarlyErrorHandler) {
190 let color_logs = match std::env::var("RUSTDOC_LOG_COLOR").as_deref() {
191 Ok("always") => true,
192 Ok("never") => false,
193 Ok("auto") | Err(VarError::NotPresent) => io::stdout().is_terminal(),
194 Ok(value) => handler.early_error(format!(
195 "invalid log color value '{}': expected one of always, never, or auto",
196 value
197 )),
198 Err(VarError::NotUnicode(value)) => handler.early_error(format!(
199 "invalid log color value '{}': expected one of always, never, or auto",
200 value.to_string_lossy()
201 )),
202 };
203 let filter = tracing_subscriber::EnvFilter::from_env("RUSTDOC_LOG");
204 let layer = tracing_tree::HierarchicalLayer::default()
205 .with_writer(io::stderr)
206 .with_indent_lines(true)
207 .with_ansi(color_logs)
208 .with_targets(true)
209 .with_wraparound(10)
210 .with_verbose_exit(true)
211 .with_verbose_entry(true)
212 .with_indent_amount(2);
213 #[cfg(all(parallel_compiler, debug_assertions))]
214 let layer = layer.with_thread_ids(true).with_thread_names(true);
215
216 use tracing_subscriber::layer::SubscriberExt;
217 let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
218 tracing::subscriber::set_global_default(subscriber).unwrap();
219 }
220
get_args(handler: &EarlyErrorHandler) -> Option<Vec<String>>221 fn get_args(handler: &EarlyErrorHandler) -> Option<Vec<String>> {
222 env::args_os()
223 .enumerate()
224 .map(|(i, arg)| {
225 arg.into_string()
226 .map_err(|arg| {
227 handler.early_warn(format!("Argument {} is not valid Unicode: {:?}", i, arg));
228 })
229 .ok()
230 })
231 .collect()
232 }
233
opts() -> Vec<RustcOptGroup>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 stable("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", "", "unstable / perma-unstable 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("diagnostic-width", |o| {
467 o.optopt(
468 "",
469 "diagnostic-width",
470 "Provide width of the output for truncated error messages",
471 "WIDTH",
472 )
473 }),
474 stable("json", |o| {
475 o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
476 }),
477 stable("allow", |o| o.optmulti("A", "allow", "Set lint allowed", "LINT")),
478 stable("warn", |o| o.optmulti("W", "warn", "Set lint warnings", "LINT")),
479 stable("force-warn", |o| o.optmulti("", "force-warn", "Set lint force-warn", "LINT")),
480 stable("deny", |o| o.optmulti("D", "deny", "Set lint denied", "LINT")),
481 stable("forbid", |o| o.optmulti("F", "forbid", "Set lint forbidden", "LINT")),
482 stable("cap-lints", |o| {
483 o.optmulti(
484 "",
485 "cap-lints",
486 "Set the most restrictive lint level. \
487 More restrictive lints are capped at this \
488 level. By default, it is at `forbid` level.",
489 "LEVEL",
490 )
491 }),
492 unstable("index-page", |o| {
493 o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
494 }),
495 unstable("enable-index-page", |o| {
496 o.optflagmulti("", "enable-index-page", "To enable generation of the index page")
497 }),
498 unstable("static-root-path", |o| {
499 o.optopt(
500 "",
501 "static-root-path",
502 "Path string to force loading static files from in output pages. \
503 If not set, uses combinations of '../' to reach the documentation root.",
504 "PATH",
505 )
506 }),
507 unstable("disable-per-crate-search", |o| {
508 o.optflagmulti(
509 "",
510 "disable-per-crate-search",
511 "disables generating the crate selector on the search box",
512 )
513 }),
514 unstable("persist-doctests", |o| {
515 o.optopt(
516 "",
517 "persist-doctests",
518 "Directory to persist doctest executables into",
519 "PATH",
520 )
521 }),
522 unstable("show-coverage", |o| {
523 o.optflagmulti(
524 "",
525 "show-coverage",
526 "calculate percentage of public items with documentation",
527 )
528 }),
529 unstable("enable-per-target-ignores", |o| {
530 o.optflagmulti(
531 "",
532 "enable-per-target-ignores",
533 "parse ignore-foo for ignoring doctests on a per-target basis",
534 )
535 }),
536 unstable("runtool", |o| {
537 o.optopt(
538 "",
539 "runtool",
540 "",
541 "The tool to run tests with when building for a different target than host",
542 )
543 }),
544 unstable("runtool-arg", |o| {
545 o.optmulti(
546 "",
547 "runtool-arg",
548 "",
549 "One (of possibly many) arguments to pass to the runtool",
550 )
551 }),
552 unstable("test-builder", |o| {
553 o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH")
554 }),
555 unstable("check", |o| o.optflagmulti("", "check", "Run rustdoc checks")),
556 unstable("generate-redirect-map", |o| {
557 o.optflagmulti(
558 "",
559 "generate-redirect-map",
560 "Generate JSON file at the top level instead of generating HTML redirection files",
561 )
562 }),
563 unstable("emit", |o| {
564 o.optmulti(
565 "",
566 "emit",
567 "Comma separated list of types of output for rustdoc to emit",
568 "[unversioned-shared-resources,toolchain-shared-resources,invocation-specific]",
569 )
570 }),
571 unstable("no-run", |o| {
572 o.optflagmulti("", "no-run", "Compile doctests without running them")
573 }),
574 unstable("show-type-layout", |o| {
575 o.optflagmulti("", "show-type-layout", "Include the memory layout of types in the docs")
576 }),
577 unstable("nocapture", |o| {
578 o.optflag("", "nocapture", "Don't capture stdout and stderr of tests")
579 }),
580 unstable("generate-link-to-definition", |o| {
581 o.optflag(
582 "",
583 "generate-link-to-definition",
584 "Make the identifiers in the HTML source code pages navigable",
585 )
586 }),
587 unstable("scrape-examples-output-path", |o| {
588 o.optopt(
589 "",
590 "scrape-examples-output-path",
591 "",
592 "collect function call information and output at the given path",
593 )
594 }),
595 unstable("scrape-examples-target-crate", |o| {
596 o.optmulti(
597 "",
598 "scrape-examples-target-crate",
599 "",
600 "collect function call information for functions from the target crate",
601 )
602 }),
603 unstable("scrape-tests", |o| {
604 o.optflag("", "scrape-tests", "Include test code when scraping examples")
605 }),
606 unstable("with-examples", |o| {
607 o.optmulti(
608 "",
609 "with-examples",
610 "",
611 "path to function call information (for displaying examples in the documentation)",
612 )
613 }),
614 // deprecated / removed options
615 unstable("disable-minification", |o| o.optflagmulti("", "disable-minification", "removed")),
616 stable("plugin-path", |o| {
617 o.optmulti(
618 "",
619 "plugin-path",
620 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
621 for more information",
622 "DIR",
623 )
624 }),
625 stable("passes", |o| {
626 o.optmulti(
627 "",
628 "passes",
629 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
630 for more information",
631 "PASSES",
632 )
633 }),
634 stable("plugins", |o| {
635 o.optmulti(
636 "",
637 "plugins",
638 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
639 for more information",
640 "PLUGINS",
641 )
642 }),
643 stable("no-default", |o| {
644 o.optflagmulti(
645 "",
646 "no-defaults",
647 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
648 for more information",
649 )
650 }),
651 stable("r", |o| {
652 o.optopt(
653 "r",
654 "input-format",
655 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
656 for more information",
657 "[rust]",
658 )
659 }),
660 ]
661 }
662
usage(argv0: &str)663 fn usage(argv0: &str) {
664 let mut options = getopts::Options::new();
665 for option in opts() {
666 (option.apply)(&mut options);
667 }
668 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
669 println!(" @path Read newline separated options from `path`\n");
670 println!(
671 "More information available at {}/rustdoc/what-is-rustdoc.html",
672 DOC_RUST_LANG_ORG_CHANNEL
673 );
674 }
675
676 /// A result type used by several functions under `main()`.
677 type MainResult = Result<(), ErrorGuaranteed>;
678
wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult679 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
680 match res {
681 Ok(()) => diag.has_errors().map_or(Ok(()), Err),
682 Err(err) => {
683 let reported = diag.struct_err(err).emit();
684 Err(reported)
685 }
686 }
687 }
688
run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>( krate: clean::Crate, renderopts: config::RenderOptions, cache: formats::cache::Cache, tcx: TyCtxt<'tcx>, ) -> MainResult689 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
690 krate: clean::Crate,
691 renderopts: config::RenderOptions,
692 cache: formats::cache::Cache,
693 tcx: TyCtxt<'tcx>,
694 ) -> MainResult {
695 match formats::run_format::<T>(krate, renderopts, cache, tcx) {
696 Ok(_) => tcx.sess.has_errors().map_or(Ok(()), Err),
697 Err(e) => {
698 let mut msg =
699 tcx.sess.struct_err(format!("couldn't generate documentation: {}", e.error));
700 let file = e.file.display().to_string();
701 if !file.is_empty() {
702 msg.note(format!("failed to create or modify \"{}\"", file));
703 }
704 Err(msg.emit())
705 }
706 }
707 }
708
main_args(handler: &mut EarlyErrorHandler, at_args: &[String]) -> MainResult709 fn main_args(handler: &mut EarlyErrorHandler, at_args: &[String]) -> MainResult {
710 // Throw away the first argument, the name of the binary.
711 // In case of at_args being empty, as might be the case by
712 // passing empty argument array to execve under some platforms,
713 // just use an empty slice.
714 //
715 // This situation was possible before due to arg_expand_all being
716 // called before removing the argument, enabling a crash by calling
717 // the compiler with @empty_file as argv[0] and no more arguments.
718 let at_args = at_args.get(1..).unwrap_or_default();
719
720 let args = rustc_driver::args::arg_expand_all(handler, at_args);
721
722 let mut options = getopts::Options::new();
723 for option in opts() {
724 (option.apply)(&mut options);
725 }
726 let matches = match options.parse(&args) {
727 Ok(m) => m,
728 Err(err) => {
729 handler.early_error(err.to_string());
730 }
731 };
732
733 // Note that we discard any distinction between different non-zero exit
734 // codes from `from_matches` here.
735 let (options, render_options) = match config::Options::from_matches(handler, &matches, args) {
736 Ok(opts) => opts,
737 Err(code) => {
738 return if code == 0 {
739 Ok(())
740 } else {
741 #[allow(deprecated)]
742 Err(ErrorGuaranteed::unchecked_claim_error_was_emitted())
743 };
744 }
745 };
746
747 // Set parallel mode before error handler creation, which will create `Lock`s.
748 interface::set_thread_safe_mode(&options.unstable_opts);
749
750 let diag = core::new_handler(
751 options.error_format,
752 None,
753 options.diagnostic_width,
754 &options.unstable_opts,
755 );
756
757 match (options.should_test, options.markdown_input()) {
758 (true, true) => return wrap_return(&diag, markdown::test(options)),
759 (true, false) => return doctest::run(options),
760 (false, true) => {
761 let input = options.input.clone();
762 let edition = options.edition;
763 let config = core::create_config(handler, options, &render_options);
764
765 // `markdown::render` can invoke `doctest::make_test`, which
766 // requires session globals and a thread pool, so we use
767 // `run_compiler`.
768 return wrap_return(
769 &diag,
770 interface::run_compiler(config, |_compiler| {
771 markdown::render(&input, render_options, edition)
772 }),
773 );
774 }
775 (false, false) => {}
776 }
777
778 // need to move these items separately because we lose them by the time the closure is called,
779 // but we can't create the Handler ahead of time because it's not Send
780 let show_coverage = options.show_coverage;
781 let run_check = options.run_check;
782
783 // First, parse the crate and extract all relevant information.
784 info!("starting to run rustc");
785
786 // Interpret the input file as a rust source file, passing it through the
787 // compiler all the way through the analysis passes. The rustdoc output is
788 // then generated from the cleaned AST of the crate. This runs all the
789 // plug/cleaning passes.
790 let crate_version = options.crate_version.clone();
791
792 let output_format = options.output_format;
793 let scrape_examples_options = options.scrape_examples_options.clone();
794 let bin_crate = options.bin_crate;
795
796 let config = core::create_config(handler, options, &render_options);
797
798 interface::run_compiler(config, |compiler| {
799 let sess = compiler.session();
800
801 if sess.opts.describe_lints {
802 let mut lint_store = rustc_lint::new_lint_store(sess.enable_internal_lints());
803 let registered_lints = if let Some(register_lints) = compiler.register_lints() {
804 register_lints(sess, &mut lint_store);
805 true
806 } else {
807 false
808 };
809 rustc_driver::describe_lints(sess, &lint_store, registered_lints);
810 return Ok(());
811 }
812
813 compiler.enter(|queries| {
814 let mut gcx = abort_on_err(queries.global_ctxt(), sess);
815 if sess.diagnostic().has_errors_or_lint_errors().is_some() {
816 sess.fatal("Compilation failed, aborting rustdoc");
817 }
818
819 gcx.enter(|tcx| {
820 let (krate, render_opts, mut cache) = sess.time("run_global_ctxt", || {
821 core::run_global_ctxt(tcx, show_coverage, render_options, output_format)
822 });
823 info!("finished with rustc");
824
825 if let Some(options) = scrape_examples_options {
826 return scrape_examples::run(
827 krate,
828 render_opts,
829 cache,
830 tcx,
831 options,
832 bin_crate,
833 );
834 }
835
836 cache.crate_version = crate_version;
837
838 if show_coverage {
839 // if we ran coverage, bail early, we don't need to also generate docs at this point
840 // (also we didn't load in any of the useful passes)
841 return Ok(());
842 } else if run_check {
843 // Since we're in "check" mode, no need to generate anything beyond this point.
844 return Ok(());
845 }
846
847 info!("going to format");
848 match output_format {
849 config::OutputFormat::Html => sess.time("render_html", || {
850 run_renderer::<html::render::Context<'_>>(krate, render_opts, cache, tcx)
851 }),
852 config::OutputFormat::Json => sess.time("render_json", || {
853 run_renderer::<json::JsonRenderer<'_>>(krate, render_opts, cache, tcx)
854 }),
855 }
856 })
857 })
858 })
859 }
860