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