2 html_root_url = "https://doc.rust-lang.org/nightly/",
3 html_playground_url = "https://play.rust-lang.org/"
5 #![feature(rustc_private)]
6 #![feature(array_methods)]
7 #![feature(box_patterns)]
8 #![feature(box_syntax)]
9 #![feature(in_band_lifetimes)]
11 #![cfg_attr(bootstrap, feature(or_patterns))]
13 #![feature(crate_visibility_modifier)]
14 #![feature(never_type)]
15 #![feature(once_cell)]
16 #![feature(type_ascription)]
17 #![feature(iter_intersperse)]
18 #![recursion_limit = "256"]
19 #![deny(rustc::internal)]
22 extern crate lazy_static;
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.
32 // Dependencies listed in Cargo.toml do not need `extern crate`.
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_data_structures;
38 extern crate rustc_driver;
39 extern crate rustc_errors;
40 extern crate rustc_expand;
41 extern crate rustc_feature;
42 extern crate rustc_hir;
43 extern crate rustc_hir_pretty;
44 extern crate rustc_index;
45 extern crate rustc_infer;
46 extern crate rustc_interface;
47 extern crate rustc_lexer;
48 extern crate rustc_lint;
49 extern crate rustc_lint_defs;
50 extern crate rustc_metadata;
51 extern crate rustc_middle;
52 extern crate rustc_mir;
53 extern crate rustc_parse;
54 extern crate rustc_passes;
55 extern crate rustc_resolve;
56 extern crate rustc_session;
57 extern crate rustc_span as rustc_span;
58 extern crate rustc_target;
59 extern crate rustc_trait_selection;
60 extern crate rustc_typeck;
61 extern crate test as testing;
63 use std::default::Default;
67 use rustc_driver::abort_on_err;
68 use rustc_errors::ErrorReported;
69 use rustc_interface::interface;
70 use rustc_middle::ty::TyCtxt;
71 use rustc_session::config::{make_crate_type_option, ErrorOutputType, RustcOptGroup};
72 use rustc_session::getopts;
73 use rustc_session::{early_error, early_warn};
75 /// A macro to create a FxHashMap.
80 /// let letters = map!{"a" => "b", "c" => "d"};
83 /// Trailing commas are allowed.
84 /// Commas between elements are required (even if the expression is a block).
86 ($( $key: expr => $val: expr ),* $(,)*) => {{
87 let mut map = ::rustc_data_structures::fx::FxHashMap::default();
88 $( map.insert($key, $val); )*
106 // used by the error-index generator, so it needs to be public
117 rustc_driver::set_sigpipe_handler();
118 rustc_driver::install_ice_hook();
120 // When using CI artifacts (with `download_stage1 = true`), tracing is unconditionally built
121 // with `--features=static_max_level_info`, which disables almost all rustdoc logging. To avoid
122 // this, compile our own version of `tracing` that logs all levels.
123 // NOTE: this compiles both versions of tracing unconditionally, because
124 // - The compile time hit is not that bad, especially compared to rustdoc's incremental times, and
125 // - Otherwise, there's no warning that logging is being ignored when `download_stage1 = true`.
126 // NOTE: The reason this doesn't show double logging when `download_stage1 = false` and
127 // `debug_logging = true` is because all rustc logging goes to its version of tracing (the one
128 // in the sysroot), and all of rustdoc's logging goes to its version (the one in Cargo.toml).
130 rustc_driver::init_env_logger("RUSTDOC_LOG");
132 let exit_code = rustc_driver::catch_with_exit_code(|| match get_args() {
133 Some(args) => main_args(&args),
134 _ => Err(ErrorReported),
136 process::exit(exit_code);
142 // FIXME remove these and use winapi 0.3 instead
143 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs, rustc_driver/lib.rs
145 fn stdout_isatty() -> bool {
147 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
151 fn stdout_isatty() -> bool {
153 use winapi::um::consoleapi::GetConsoleMode;
154 use winapi::um::processenv::GetStdHandle;
155 use winapi::um::winbase::STD_OUTPUT_HANDLE;
158 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
160 GetConsoleMode(handle, &mut out) != 0
164 let color_logs = match std::env::var("RUSTDOC_LOG_COLOR") {
165 Ok(value) => match value.as_ref() {
168 "auto" => stdout_isatty(),
170 ErrorOutputType::default(),
172 "invalid log color value '{}': expected one of always, never, or auto",
177 Err(std::env::VarError::NotPresent) => stdout_isatty(),
178 Err(std::env::VarError::NotUnicode(_value)) => early_error(
179 ErrorOutputType::default(),
180 "non-Unicode log color value: expected one of always, never, or auto",
183 let filter = tracing_subscriber::EnvFilter::from_env("RUSTDOC_LOG");
184 let layer = tracing_tree::HierarchicalLayer::default()
185 .with_writer(io::stderr)
186 .with_indent_lines(true)
187 .with_ansi(color_logs)
190 .with_verbose_exit(true)
191 .with_verbose_entry(true)
192 .with_indent_amount(2);
193 #[cfg(parallel_compiler)]
194 let layer = layer.with_thread_ids(true).with_thread_names(true);
196 use tracing_subscriber::layer::SubscriberExt;
197 let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
198 tracing::subscriber::set_global_default(subscriber).unwrap();
201 fn get_args() -> Option<Vec<String>> {
208 ErrorOutputType::default(),
209 &format!("Argument {} is not valid Unicode: {:?}", i, arg),
217 fn opts() -> Vec<RustcOptGroup> {
218 let stable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::stable;
219 let unstable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::unstable;
221 stable("h", |o| o.optflag("h", "help", "show this help message")),
222 stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
223 stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
225 o.optopt("r", "input-format", "the input type of the specified file", "[rust]")
227 stable("w", |o| o.optopt("w", "output-format", "the output type to write", "[html]")),
228 stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
229 stable("crate-name", |o| {
230 o.optopt("", "crate-name", "specify the name of this crate", "NAME")
232 make_crate_type_option(),
234 o.optmulti("L", "library-path", "directory to add to crate search path", "DIR")
236 stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
237 stable("extern", |o| o.optmulti("", "extern", "pass an --extern to rustc", "NAME[=PATH]")),
238 unstable("extern-html-root-url", |o| {
239 o.optmulti("", "extern-html-root-url", "base URL to use for dependencies", "NAME=URL")
241 stable("plugin-path", |o| o.optmulti("", "plugin-path", "removed", "DIR")),
243 o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
245 stable("passes", |o| {
249 "list of passes to also run, you might want to pass it multiple times; a value of \
250 `list` will print available passes",
254 stable("plugins", |o| o.optmulti("", "plugins", "removed", "PLUGINS")),
255 stable("no-default", |o| o.optflag("", "no-defaults", "don't run the default passes")),
256 stable("document-private-items", |o| {
257 o.optflag("", "document-private-items", "document private items")
259 unstable("document-hidden-items", |o| {
260 o.optflag("", "document-hidden-items", "document items that have doc(hidden)")
262 stable("test", |o| o.optflag("", "test", "run code examples as tests")),
263 stable("test-args", |o| {
264 o.optmulti("", "test-args", "arguments to pass to the test runner", "ARGS")
266 unstable("test-run-directory", |o| {
269 "test-run-directory",
270 "The working directory in which to run tests",
274 stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
275 stable("markdown-css", |o| {
279 "CSS files to include via <link> in a rendered Markdown file",
283 stable("html-in-header", |o| {
287 "files to include inline in the <head> section of a rendered Markdown file \
288 or generated documentation",
292 stable("html-before-content", |o| {
295 "html-before-content",
296 "files to include inline between <body> and the content of a rendered \
297 Markdown file or generated documentation",
301 stable("html-after-content", |o| {
304 "html-after-content",
305 "files to include inline between the content and </body> of a rendered \
306 Markdown file or generated documentation",
310 unstable("markdown-before-content", |o| {
313 "markdown-before-content",
314 "files to include inline between <body> and the content of a rendered \
315 Markdown file or generated documentation",
319 unstable("markdown-after-content", |o| {
322 "markdown-after-content",
323 "files to include inline between the content and </body> of a rendered \
324 Markdown file or generated documentation",
328 stable("markdown-playground-url", |o| {
329 o.optopt("", "markdown-playground-url", "URL to send code snippets to", "URL")
331 stable("markdown-no-toc", |o| {
332 o.optflag("", "markdown-no-toc", "don't include table of contents")
338 "To add some CSS rules with a given file to generate doc with your \
339 own theme. However, your theme might break if the rustdoc's generated HTML \
340 changes, so be careful!",
345 o.optmulti("Z", "", "internal and debugging options (only on nightly build)", "FLAG")
347 stable("sysroot", |o| o.optopt("", "sysroot", "Override the system root", "PATH")),
348 unstable("playground-url", |o| {
352 "URL to send code snippets to, may be reset by --markdown-playground-url \
353 or `#![doc(html_playground_url=...)]`",
357 unstable("display-warnings", |o| {
358 o.optflag("", "display-warnings", "to print code warnings when testing doc")
360 stable("crate-version", |o| {
361 o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
363 unstable("sort-modules-by-appearance", |o| {
366 "sort-modules-by-appearance",
367 "sort modules by where they appear in the program, rather than alphabetically",
370 stable("default-theme", |o| {
374 "Set the default theme. THEME should be the theme name, generally lowercase. \
375 If an unknown default theme is specified, the builtin default is used. \
376 The set of themes, and the rustdoc built-in default, are not stable.",
380 unstable("default-setting", |o| {
384 "Default value for a rustdoc setting (used when \"rustdoc-SETTING\" is absent \
385 from web browser Local Storage). If VALUE is not supplied, \"true\" is used. \
386 Supported SETTINGs and VALUEs are not documented and not stable.",
390 stable("theme", |o| {
394 "additional themes which will be added to the generated docs",
398 stable("check-theme", |o| {
399 o.optmulti("", "check-theme", "check if given theme is valid", "FILES")
401 unstable("resource-suffix", |o| {
405 "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
406 \"light-suffix.css\"",
410 stable("edition", |o| {
414 "edition to use when compiling rust code (default: 2015)",
418 stable("color", |o| {
422 "Configure coloring of output:
423 auto = colorize, if output goes to a tty (default);
424 always = always colorize output;
425 never = never colorize output",
429 stable("error-format", |o| {
433 "How errors and other messages are produced",
438 o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
440 unstable("disable-minification", |o| {
441 o.optflag("", "disable-minification", "Disable minification applied on JS files")
443 stable("warn", |o| o.optmulti("W", "warn", "Set lint warnings", "OPT")),
444 stable("allow", |o| o.optmulti("A", "allow", "Set lint allowed", "OPT")),
445 stable("deny", |o| o.optmulti("D", "deny", "Set lint denied", "OPT")),
446 stable("forbid", |o| o.optmulti("F", "forbid", "Set lint forbidden", "OPT")),
447 stable("cap-lints", |o| {
451 "Set the most restrictive lint level. \
452 More restrictive lints are capped at this \
453 level. By default, it is at `forbid` level.",
457 unstable("index-page", |o| {
458 o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
460 unstable("enable-index-page", |o| {
461 o.optflag("", "enable-index-page", "To enable generation of the index page")
463 unstable("static-root-path", |o| {
467 "Path string to force loading static files from in output pages. \
468 If not set, uses combinations of '../' to reach the documentation root.",
472 unstable("disable-per-crate-search", |o| {
475 "disable-per-crate-search",
476 "disables generating the crate selector on the search box",
479 unstable("persist-doctests", |o| {
483 "Directory to persist doctest executables into",
487 unstable("show-coverage", |o| {
491 "calculate percentage of public items with documentation",
494 unstable("enable-per-target-ignores", |o| {
497 "enable-per-target-ignores",
498 "parse ignore-foo for ignoring doctests on a per-target basis",
501 unstable("runtool", |o| {
506 "The tool to run tests with when building for a different target than host",
509 unstable("runtool-arg", |o| {
514 "One (of possibly many) arguments to pass to the runtool",
517 unstable("test-builder", |o| {
518 o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH")
520 unstable("check", |o| o.optflag("", "check", "Run rustdoc checks")),
521 unstable("generate-redirect-map", |o| {
524 "generate-redirect-map",
525 "Generate JSON file at the top level instead of generating HTML redirection files",
528 unstable("print", |o| {
529 o.optmulti("", "print", "Rustdoc information to print on stdout", "[unversioned-files]")
531 unstable("emit", |o| {
535 "Comma separated list of types of output for rustdoc to emit",
536 "[unversioned-shared-resources,toolchain-shared-resources,invocation-specific]",
542 fn usage(argv0: &str) {
543 let mut options = getopts::Options::new();
544 for option in opts() {
545 (option.apply)(&mut options);
547 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
548 println!(" @path Read newline separated options from `path`\n");
549 println!("More information available at https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html")
552 /// A result type used by several functions under `main()`.
553 type MainResult = Result<(), ErrorReported>;
555 fn main_args(at_args: &[String]) -> MainResult {
556 let args = rustc_driver::args::arg_expand_all(at_args);
558 let mut options = getopts::Options::new();
559 for option in opts() {
560 (option.apply)(&mut options);
562 let matches = match options.parse(&args[1..]) {
565 early_error(ErrorOutputType::default(), &err.to_string());
569 // Note that we discard any distinction between different non-zero exit
570 // codes from `from_matches` here.
571 let options = match config::Options::from_matches(&matches) {
573 Err(code) => return if code == 0 { Ok(()) } else { Err(ErrorReported) },
575 rustc_interface::util::setup_callbacks_and_run_in_thread_pool_with_globals(
577 1, // this runs single-threaded, even in a parallel compiler
579 move || main_options(options),
583 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
587 diag.struct_err(&err).emit();
593 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
595 renderopts: config::RenderOptions,
596 cache: formats::cache::Cache,
597 diag: &rustc_errors::Handler,
598 edition: rustc_span::edition::Edition,
601 match formats::run_format::<T>(krate, renderopts, cache, &diag, edition, tcx) {
604 let mut msg = diag.struct_err(&format!("couldn't generate documentation: {}", e.error));
605 let file = e.file.display().to_string();
609 msg.note(&format!("failed to create or modify \"{}\"", file)).emit()
616 fn main_options(options: config::Options) -> MainResult {
617 let diag = core::new_handler(options.error_format, None, &options.debugging_opts);
619 match (options.should_test, options.markdown_input()) {
620 (true, true) => return wrap_return(&diag, markdown::test(options)),
621 (true, false) => return doctest::run(options),
625 markdown::render(&options.input, options.render_options, options.edition),
631 // need to move these items separately because we lose them by the time the closure is called,
632 // but we can't create the Handler ahead of time because it's not Send
633 let diag_opts = (options.error_format, options.edition, options.debugging_opts.clone());
634 let show_coverage = options.show_coverage;
635 let run_check = options.run_check;
637 // First, parse the crate and extract all relevant information.
638 info!("starting to run rustc");
640 // Interpret the input file as a rust source file, passing it through the
641 // compiler all the way through the analysis passes. The rustdoc output is
642 // then generated from the cleaned AST of the crate. This runs all the
643 // plug/cleaning passes.
644 let crate_version = options.crate_version.clone();
646 let default_passes = options.default_passes;
647 let output_format = options.output_format;
648 // FIXME: fix this clone (especially render_options)
649 let manual_passes = options.manual_passes.clone();
650 let render_options = options.render_options.clone();
651 let config = core::create_config(options);
653 interface::create_compiler_and_run(config, |compiler| {
654 compiler.enter(|queries| {
655 let sess = compiler.session();
657 // We need to hold on to the complete resolver, so we cause everything to be
658 // cloned for the analysis passes to use. Suboptimal, but necessary in the
659 // current architecture.
660 let resolver = core::create_resolver(queries, &sess);
662 if sess.has_errors() {
663 sess.fatal("Compilation failed, aborting rustdoc");
666 let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).peek_mut();
668 global_ctxt.enter(|tcx| {
669 let (krate, render_opts, mut cache) = sess.time("run_global_ctxt", || {
670 core::run_global_ctxt(
679 info!("finished with rustc");
681 cache.crate_version = crate_version;
684 // if we ran coverage, bail early, we don't need to also generate docs at this point
685 // (also we didn't load in any of the useful passes)
687 } else if run_check {
688 // Since we're in "check" mode, no need to generate anything beyond this point.
692 info!("going to format");
693 let (error_format, edition, debugging_options) = diag_opts;
694 let diag = core::new_handler(error_format, None, &debugging_options);
695 match output_format {
696 config::OutputFormat::Html => sess.time("render_html", || {
697 run_renderer::<html::render::Context<'_>>(
706 config::OutputFormat::Json => sess.time("render_json", || {
707 run_renderer::<json::JsonRenderer<'_>>(