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