]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Rollup merge of #92117 - solid-rs:fix-kmc-solid-read-buf, r=yaahc
[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(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
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
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
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
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("w", |o| o.optopt("w", "output-format", "the output type to write", "[html]")),
278         stable("output", |o| {
279             o.optopt(
280                 "",
281                 "output",
282                 "Which directory to place the output. \
283                  This option is deprecated, use --out-dir instead.",
284                 "PATH",
285             )
286         }),
287         stable("o", |o| o.optopt("o", "out-dir", "which directory to place the output", "PATH")),
288         stable("crate-name", |o| {
289             o.optopt("", "crate-name", "specify the name of this crate", "NAME")
290         }),
291         make_crate_type_option(),
292         stable("L", |o| {
293             o.optmulti("L", "library-path", "directory to add to crate search path", "DIR")
294         }),
295         stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
296         stable("extern", |o| o.optmulti("", "extern", "pass an --extern to rustc", "NAME[=PATH]")),
297         unstable("extern-html-root-url", |o| {
298             o.optmulti(
299                 "",
300                 "extern-html-root-url",
301                 "base URL to use for dependencies; for example, \
302                  \"std=/doc\" links std::vec::Vec to /doc/std/vec/struct.Vec.html",
303                 "NAME=URL",
304             )
305         }),
306         unstable("extern-html-root-takes-precedence", |o| {
307             o.optflagmulti(
308                 "",
309                 "extern-html-root-takes-precedence",
310                 "give precedence to `--extern-html-root-url`, not `html_root_url`",
311             )
312         }),
313         stable("C", |o| {
314             o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
315         }),
316         stable("document-private-items", |o| {
317             o.optflagmulti("", "document-private-items", "document private items")
318         }),
319         unstable("document-hidden-items", |o| {
320             o.optflagmulti("", "document-hidden-items", "document items that have doc(hidden)")
321         }),
322         stable("test", |o| o.optflagmulti("", "test", "run code examples as tests")),
323         stable("test-args", |o| {
324             o.optmulti("", "test-args", "arguments to pass to the test runner", "ARGS")
325         }),
326         unstable("test-run-directory", |o| {
327             o.optopt(
328                 "",
329                 "test-run-directory",
330                 "The working directory in which to run tests",
331                 "PATH",
332             )
333         }),
334         stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
335         stable("markdown-css", |o| {
336             o.optmulti(
337                 "",
338                 "markdown-css",
339                 "CSS files to include via <link> in a rendered Markdown file",
340                 "FILES",
341             )
342         }),
343         stable("html-in-header", |o| {
344             o.optmulti(
345                 "",
346                 "html-in-header",
347                 "files to include inline in the <head> section of a rendered Markdown file \
348                  or generated documentation",
349                 "FILES",
350             )
351         }),
352         stable("html-before-content", |o| {
353             o.optmulti(
354                 "",
355                 "html-before-content",
356                 "files to include inline between <body> and the content of a rendered \
357                  Markdown file or generated documentation",
358                 "FILES",
359             )
360         }),
361         stable("html-after-content", |o| {
362             o.optmulti(
363                 "",
364                 "html-after-content",
365                 "files to include inline between the content and </body> of a rendered \
366                  Markdown file or generated documentation",
367                 "FILES",
368             )
369         }),
370         unstable("markdown-before-content", |o| {
371             o.optmulti(
372                 "",
373                 "markdown-before-content",
374                 "files to include inline between <body> and the content of a rendered \
375                  Markdown file or generated documentation",
376                 "FILES",
377             )
378         }),
379         unstable("markdown-after-content", |o| {
380             o.optmulti(
381                 "",
382                 "markdown-after-content",
383                 "files to include inline between the content and </body> of a rendered \
384                  Markdown file or generated documentation",
385                 "FILES",
386             )
387         }),
388         stable("markdown-playground-url", |o| {
389             o.optopt("", "markdown-playground-url", "URL to send code snippets to", "URL")
390         }),
391         stable("markdown-no-toc", |o| {
392             o.optflagmulti("", "markdown-no-toc", "don't include table of contents")
393         }),
394         stable("e", |o| {
395             o.optopt(
396                 "e",
397                 "extend-css",
398                 "To add some CSS rules with a given file to generate doc with your \
399                  own theme. However, your theme might break if the rustdoc's generated HTML \
400                  changes, so be careful!",
401                 "PATH",
402             )
403         }),
404         unstable("Z", |o| {
405             o.optmulti("Z", "", "internal and debugging options (only on nightly build)", "FLAG")
406         }),
407         stable("sysroot", |o| o.optopt("", "sysroot", "Override the system root", "PATH")),
408         unstable("playground-url", |o| {
409             o.optopt(
410                 "",
411                 "playground-url",
412                 "URL to send code snippets to, may be reset by --markdown-playground-url \
413                  or `#![doc(html_playground_url=...)]`",
414                 "URL",
415             )
416         }),
417         unstable("display-doctest-warnings", |o| {
418             o.optflagmulti(
419                 "",
420                 "display-doctest-warnings",
421                 "show warnings that originate in doctests",
422             )
423         }),
424         stable("crate-version", |o| {
425             o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
426         }),
427         unstable("sort-modules-by-appearance", |o| {
428             o.optflagmulti(
429                 "",
430                 "sort-modules-by-appearance",
431                 "sort modules by where they appear in the program, rather than alphabetically",
432             )
433         }),
434         stable("default-theme", |o| {
435             o.optopt(
436                 "",
437                 "default-theme",
438                 "Set the default theme. THEME should be the theme name, generally lowercase. \
439                  If an unknown default theme is specified, the builtin default is used. \
440                  The set of themes, and the rustdoc built-in default, are not stable.",
441                 "THEME",
442             )
443         }),
444         unstable("default-setting", |o| {
445             o.optmulti(
446                 "",
447                 "default-setting",
448                 "Default value for a rustdoc setting (used when \"rustdoc-SETTING\" is absent \
449                  from web browser Local Storage). If VALUE is not supplied, \"true\" is used. \
450                  Supported SETTINGs and VALUEs are not documented and not stable.",
451                 "SETTING[=VALUE]",
452             )
453         }),
454         stable("theme", |o| {
455             o.optmulti(
456                 "",
457                 "theme",
458                 "additional themes which will be added to the generated docs",
459                 "FILES",
460             )
461         }),
462         stable("check-theme", |o| {
463             o.optmulti("", "check-theme", "check if given theme is valid", "FILES")
464         }),
465         unstable("resource-suffix", |o| {
466             o.optopt(
467                 "",
468                 "resource-suffix",
469                 "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
470                  \"light-suffix.css\"",
471                 "PATH",
472             )
473         }),
474         stable("edition", |o| {
475             o.optopt(
476                 "",
477                 "edition",
478                 "edition to use when compiling rust code (default: 2015)",
479                 "EDITION",
480             )
481         }),
482         stable("color", |o| {
483             o.optopt(
484                 "",
485                 "color",
486                 "Configure coloring of output:
487                                           auto   = colorize, if output goes to a tty (default);
488                                           always = always colorize output;
489                                           never  = never colorize output",
490                 "auto|always|never",
491             )
492         }),
493         stable("error-format", |o| {
494             o.optopt(
495                 "",
496                 "error-format",
497                 "How errors and other messages are produced",
498                 "human|json|short",
499             )
500         }),
501         stable("json", |o| {
502             o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
503         }),
504         unstable("disable-minification", |o| {
505             o.optflagmulti("", "disable-minification", "Disable minification applied on JS files")
506         }),
507         stable("allow", |o| o.optmulti("A", "allow", "Set lint allowed", "LINT")),
508         stable("warn", |o| o.optmulti("W", "warn", "Set lint warnings", "LINT")),
509         stable("force-warn", |o| o.optmulti("", "force-warn", "Set lint force-warn", "LINT")),
510         stable("deny", |o| o.optmulti("D", "deny", "Set lint denied", "LINT")),
511         stable("forbid", |o| o.optmulti("F", "forbid", "Set lint forbidden", "LINT")),
512         stable("cap-lints", |o| {
513             o.optmulti(
514                 "",
515                 "cap-lints",
516                 "Set the most restrictive lint level. \
517                  More restrictive lints are capped at this \
518                  level. By default, it is at `forbid` level.",
519                 "LEVEL",
520             )
521         }),
522         unstable("index-page", |o| {
523             o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
524         }),
525         unstable("enable-index-page", |o| {
526             o.optflagmulti("", "enable-index-page", "To enable generation of the index page")
527         }),
528         unstable("static-root-path", |o| {
529             o.optopt(
530                 "",
531                 "static-root-path",
532                 "Path string to force loading static files from in output pages. \
533                  If not set, uses combinations of '../' to reach the documentation root.",
534                 "PATH",
535             )
536         }),
537         unstable("disable-per-crate-search", |o| {
538             o.optflagmulti(
539                 "",
540                 "disable-per-crate-search",
541                 "disables generating the crate selector on the search box",
542             )
543         }),
544         unstable("persist-doctests", |o| {
545             o.optopt(
546                 "",
547                 "persist-doctests",
548                 "Directory to persist doctest executables into",
549                 "PATH",
550             )
551         }),
552         unstable("show-coverage", |o| {
553             o.optflagmulti(
554                 "",
555                 "show-coverage",
556                 "calculate percentage of public items with documentation",
557             )
558         }),
559         unstable("enable-per-target-ignores", |o| {
560             o.optflagmulti(
561                 "",
562                 "enable-per-target-ignores",
563                 "parse ignore-foo for ignoring doctests on a per-target basis",
564             )
565         }),
566         unstable("runtool", |o| {
567             o.optopt(
568                 "",
569                 "runtool",
570                 "",
571                 "The tool to run tests with when building for a different target than host",
572             )
573         }),
574         unstable("runtool-arg", |o| {
575             o.optmulti(
576                 "",
577                 "runtool-arg",
578                 "",
579                 "One (of possibly many) arguments to pass to the runtool",
580             )
581         }),
582         unstable("test-builder", |o| {
583             o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH")
584         }),
585         unstable("check", |o| o.optflagmulti("", "check", "Run rustdoc checks")),
586         unstable("generate-redirect-map", |o| {
587             o.optflagmulti(
588                 "",
589                 "generate-redirect-map",
590                 "Generate JSON file at the top level instead of generating HTML redirection files",
591             )
592         }),
593         unstable("emit", |o| {
594             o.optmulti(
595                 "",
596                 "emit",
597                 "Comma separated list of types of output for rustdoc to emit",
598                 "[unversioned-shared-resources,toolchain-shared-resources,invocation-specific]",
599             )
600         }),
601         unstable("no-run", |o| {
602             o.optflagmulti("", "no-run", "Compile doctests without running them")
603         }),
604         unstable("show-type-layout", |o| {
605             o.optflagmulti("", "show-type-layout", "Include the memory layout of types in the docs")
606         }),
607         unstable("nocapture", |o| {
608             o.optflag("", "nocapture", "Don't capture stdout and stderr of tests")
609         }),
610         unstable("generate-link-to-definition", |o| {
611             o.optflag(
612                 "",
613                 "generate-link-to-definition",
614                 "Make the identifiers in the HTML source code pages navigable",
615             )
616         }),
617         unstable("scrape-examples-output-path", |o| {
618             o.optopt(
619                 "",
620                 "scrape-examples-output-path",
621                 "",
622                 "collect function call information and output at the given path",
623             )
624         }),
625         unstable("scrape-examples-target-crate", |o| {
626             o.optmulti(
627                 "",
628                 "scrape-examples-target-crate",
629                 "",
630                 "collect function call information for functions from the target crate",
631             )
632         }),
633         unstable("with-examples", |o| {
634             o.optmulti(
635                 "",
636                 "with-examples",
637                 "",
638                 "path to function call information (for displaying examples in the documentation)",
639             )
640         }),
641         // deprecated / removed options
642         stable("plugin-path", |o| {
643             o.optmulti(
644                 "",
645                 "plugin-path",
646                 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
647                 for more information",
648                 "DIR",
649             )
650         }),
651         stable("passes", |o| {
652             o.optmulti(
653                 "",
654                 "passes",
655                 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
656                 for more information",
657                 "PASSES",
658             )
659         }),
660         stable("plugins", |o| {
661             o.optmulti(
662                 "",
663                 "plugins",
664                 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
665                 for more information",
666                 "PLUGINS",
667             )
668         }),
669         stable("no-default", |o| {
670             o.optflagmulti(
671                 "",
672                 "no-defaults",
673                 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
674                 for more information",
675             )
676         }),
677         stable("r", |o| {
678             o.optopt(
679                 "r",
680                 "input-format",
681                 "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
682                 for more information",
683                 "[rust]",
684             )
685         }),
686     ]
687 }
688
689 fn usage(argv0: &str) {
690     let mut options = getopts::Options::new();
691     for option in opts() {
692         (option.apply)(&mut options);
693     }
694     println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
695     println!("    @path               Read newline separated options from `path`\n");
696     println!(
697         "More information available at {}/rustdoc/what-is-rustdoc.html",
698         DOC_RUST_LANG_ORG_CHANNEL
699     );
700 }
701
702 /// A result type used by several functions under `main()`.
703 type MainResult = Result<(), ErrorReported>;
704
705 fn main_args(at_args: &[String]) -> MainResult {
706     let args = rustc_driver::args::arg_expand_all(at_args);
707
708     let mut options = getopts::Options::new();
709     for option in opts() {
710         (option.apply)(&mut options);
711     }
712     let matches = match options.parse(&args[1..]) {
713         Ok(m) => m,
714         Err(err) => {
715             early_error(ErrorOutputType::default(), &err.to_string());
716         }
717     };
718
719     // Note that we discard any distinction between different non-zero exit
720     // codes from `from_matches` here.
721     let options = match config::Options::from_matches(&matches) {
722         Ok(opts) => opts,
723         Err(code) => return if code == 0 { Ok(()) } else { Err(ErrorReported) },
724     };
725     rustc_interface::util::setup_callbacks_and_run_in_thread_pool_with_globals(
726         options.edition,
727         1, // this runs single-threaded, even in a parallel compiler
728         &None,
729         move || main_options(options),
730     )
731 }
732
733 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
734     match res {
735         Ok(()) => Ok(()),
736         Err(err) => {
737             diag.struct_err(&err).emit();
738             Err(ErrorReported)
739         }
740     }
741 }
742
743 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
744     krate: clean::Crate,
745     renderopts: config::RenderOptions,
746     cache: formats::cache::Cache,
747     tcx: TyCtxt<'tcx>,
748 ) -> MainResult {
749     match formats::run_format::<T>(krate, renderopts, cache, tcx) {
750         Ok(_) => Ok(()),
751         Err(e) => {
752             let mut msg =
753                 tcx.sess.struct_err(&format!("couldn't generate documentation: {}", e.error));
754             let file = e.file.display().to_string();
755             if file.is_empty() {
756                 msg.emit()
757             } else {
758                 msg.note(&format!("failed to create or modify \"{}\"", file)).emit()
759             }
760             Err(ErrorReported)
761         }
762     }
763 }
764
765 fn main_options(options: config::Options) -> MainResult {
766     let diag = core::new_handler(options.error_format, None, &options.debugging_opts);
767
768     match (options.should_test, options.markdown_input()) {
769         (true, true) => return wrap_return(&diag, markdown::test(options)),
770         (true, false) => return doctest::run(options),
771         (false, true) => {
772             return wrap_return(
773                 &diag,
774                 markdown::render(&options.input, options.render_options, options.edition),
775             );
776         }
777         (false, false) => {}
778     }
779
780     // need to move these items separately because we lose them by the time the closure is called,
781     // but we can't create the Handler ahead of time because it's not Send
782     let show_coverage = options.show_coverage;
783     let run_check = options.run_check;
784
785     // First, parse the crate and extract all relevant information.
786     info!("starting to run rustc");
787
788     // Interpret the input file as a rust source file, passing it through the
789     // compiler all the way through the analysis passes. The rustdoc output is
790     // then generated from the cleaned AST of the crate. This runs all the
791     // plug/cleaning passes.
792     let crate_version = options.crate_version.clone();
793
794     let output_format = options.output_format;
795     // FIXME: fix this clone (especially render_options)
796     let externs = options.externs.clone();
797     let render_options = options.render_options.clone();
798     let scrape_examples_options = options.scrape_examples_options.clone();
799     let config = core::create_config(options);
800
801     interface::create_compiler_and_run(config, |compiler| {
802         compiler.enter(|queries| {
803             let sess = compiler.session();
804
805             if sess.opts.describe_lints {
806                 let (_, lint_store) = &*queries.register_plugins()?.peek();
807                 describe_lints(sess, lint_store, true);
808                 return Ok(());
809             }
810
811             // We need to hold on to the complete resolver, so we cause everything to be
812             // cloned for the analysis passes to use. Suboptimal, but necessary in the
813             // current architecture.
814             let resolver = core::create_resolver(externs, queries, sess);
815
816             if sess.diagnostic().has_errors_or_lint_errors() {
817                 sess.fatal("Compilation failed, aborting rustdoc");
818             }
819
820             let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).peek_mut();
821
822             global_ctxt.enter(|tcx| {
823                 let (krate, render_opts, mut cache) = sess.time("run_global_ctxt", || {
824                     core::run_global_ctxt(
825                         tcx,
826                         resolver,
827                         show_coverage,
828                         render_options,
829                         output_format,
830                     )
831                 });
832                 info!("finished with rustc");
833
834                 if let Some(options) = scrape_examples_options {
835                     return scrape_examples::run(krate, render_opts, cache, tcx, options);
836                 }
837
838                 cache.crate_version = crate_version;
839
840                 if show_coverage {
841                     // if we ran coverage, bail early, we don't need to also generate docs at this point
842                     // (also we didn't load in any of the useful passes)
843                     return Ok(());
844                 } else if run_check {
845                     // Since we're in "check" mode, no need to generate anything beyond this point.
846                     return Ok(());
847                 }
848
849                 info!("going to format");
850                 match output_format {
851                     config::OutputFormat::Html => sess.time("render_html", || {
852                         run_renderer::<html::render::Context<'_>>(krate, render_opts, cache, tcx)
853                     }),
854                     config::OutputFormat::Json => sess.time("render_json", || {
855                         run_renderer::<json::JsonRenderer<'_>>(krate, render_opts, cache, tcx)
856                     }),
857                 }
858             })
859         })
860     })
861 }