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 #![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_pretty;
35 extern crate rustc_attr;
36 extern crate rustc_data_structures;
37 extern crate rustc_driver;
38 extern crate rustc_errors;
39 extern crate rustc_expand;
40 extern crate rustc_feature;
41 extern crate rustc_hir;
42 extern crate rustc_hir_pretty;
43 extern crate rustc_index;
44 extern crate rustc_infer;
45 extern crate rustc_interface;
46 extern crate rustc_lexer;
47 extern crate rustc_lint;
48 extern crate rustc_lint_defs;
49 extern crate rustc_metadata;
50 extern crate rustc_middle;
51 extern crate rustc_mir;
52 extern crate rustc_parse;
53 extern crate rustc_passes;
54 extern crate rustc_resolve;
55 extern crate rustc_session;
56 extern crate rustc_span as rustc_span;
57 extern crate rustc_target;
58 extern crate rustc_trait_selection;
59 extern crate rustc_typeck;
60 extern crate test as testing;
62 use std::default::Default;
66 use rustc_driver::abort_on_err;
67 use rustc_errors::ErrorReported;
68 use rustc_interface::interface;
69 use rustc_middle::ty::TyCtxt;
70 use rustc_session::config::{make_crate_type_option, ErrorOutputType, RustcOptGroup};
71 use rustc_session::getopts;
72 use rustc_session::{early_error, early_warn};
87 // used by the error-index generator, so it needs to be public
98 rustc_driver::set_sigpipe_handler();
99 rustc_driver::install_ice_hook();
101 // When using CI artifacts (with `download_stage1 = true`), tracing is unconditionally built
102 // with `--features=static_max_level_info`, which disables almost all rustdoc logging. To avoid
103 // this, compile our own version of `tracing` that logs all levels.
104 // NOTE: this compiles both versions of tracing unconditionally, because
105 // - The compile time hit is not that bad, especially compared to rustdoc's incremental times, and
106 // - Otherwise, there's no warning that logging is being ignored when `download_stage1 = true`.
107 // NOTE: The reason this doesn't show double logging when `download_stage1 = false` and
108 // `debug_logging = true` is because all rustc logging goes to its version of tracing (the one
109 // in the sysroot), and all of rustdoc's logging goes to its version (the one in Cargo.toml).
111 rustc_driver::init_env_logger("RUSTDOC_LOG");
113 let exit_code = rustc_driver::catch_with_exit_code(|| match get_args() {
114 Some(args) => main_args(&args),
115 _ => Err(ErrorReported),
117 process::exit(exit_code);
123 // FIXME remove these and use winapi 0.3 instead
124 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs, rustc_driver/lib.rs
126 fn stdout_isatty() -> bool {
128 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
132 fn stdout_isatty() -> bool {
134 use winapi::um::consoleapi::GetConsoleMode;
135 use winapi::um::processenv::GetStdHandle;
136 use winapi::um::winbase::STD_OUTPUT_HANDLE;
139 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
141 GetConsoleMode(handle, &mut out) != 0
145 let color_logs = match std::env::var("RUSTDOC_LOG_COLOR") {
146 Ok(value) => match value.as_ref() {
149 "auto" => stdout_isatty(),
151 ErrorOutputType::default(),
153 "invalid log color value '{}': expected one of always, never, or auto",
158 Err(std::env::VarError::NotPresent) => stdout_isatty(),
159 Err(std::env::VarError::NotUnicode(_value)) => early_error(
160 ErrorOutputType::default(),
161 "non-Unicode log color value: expected one of always, never, or auto",
164 let filter = tracing_subscriber::EnvFilter::from_env("RUSTDOC_LOG");
165 let layer = tracing_tree::HierarchicalLayer::default()
166 .with_writer(io::stderr)
167 .with_indent_lines(true)
168 .with_ansi(color_logs)
171 .with_verbose_exit(true)
172 .with_verbose_entry(true)
173 .with_indent_amount(2);
174 #[cfg(parallel_compiler)]
175 let layer = layer.with_thread_ids(true).with_thread_names(true);
177 use tracing_subscriber::layer::SubscriberExt;
178 let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
179 tracing::subscriber::set_global_default(subscriber).unwrap();
182 fn get_args() -> Option<Vec<String>> {
189 ErrorOutputType::default(),
190 &format!("Argument {} is not valid Unicode: {:?}", i, arg),
198 fn opts() -> Vec<RustcOptGroup> {
199 let stable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::stable;
200 let unstable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::unstable;
202 stable("h", |o| o.optflag("h", "help", "show this help message")),
203 stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
204 stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
206 o.optopt("r", "input-format", "the input type of the specified file", "[rust]")
208 stable("w", |o| o.optopt("w", "output-format", "the output type to write", "[html]")),
209 stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
210 stable("crate-name", |o| {
211 o.optopt("", "crate-name", "specify the name of this crate", "NAME")
213 make_crate_type_option(),
215 o.optmulti("L", "library-path", "directory to add to crate search path", "DIR")
217 stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
218 stable("extern", |o| o.optmulti("", "extern", "pass an --extern to rustc", "NAME[=PATH]")),
219 unstable("extern-html-root-url", |o| {
220 o.optmulti("", "extern-html-root-url", "base URL to use for dependencies", "NAME=URL")
222 stable("plugin-path", |o| o.optmulti("", "plugin-path", "removed", "DIR")),
224 o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
226 stable("passes", |o| {
230 "list of passes to also run, you might want to pass it multiple times; a value of \
231 `list` will print available passes",
235 stable("plugins", |o| o.optmulti("", "plugins", "removed", "PLUGINS")),
236 stable("no-default", |o| o.optflag("", "no-defaults", "don't run the default passes")),
237 stable("document-private-items", |o| {
238 o.optflag("", "document-private-items", "document private items")
240 unstable("document-hidden-items", |o| {
241 o.optflag("", "document-hidden-items", "document items that have doc(hidden)")
243 stable("test", |o| o.optflag("", "test", "run code examples as tests")),
244 stable("test-args", |o| {
245 o.optmulti("", "test-args", "arguments to pass to the test runner", "ARGS")
247 unstable("test-run-directory", |o| {
250 "test-run-directory",
251 "The working directory in which to run tests",
255 stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
256 stable("markdown-css", |o| {
260 "CSS files to include via <link> in a rendered Markdown file",
264 stable("html-in-header", |o| {
268 "files to include inline in the <head> section of a rendered Markdown file \
269 or generated documentation",
273 stable("html-before-content", |o| {
276 "html-before-content",
277 "files to include inline between <body> and the content of a rendered \
278 Markdown file or generated documentation",
282 stable("html-after-content", |o| {
285 "html-after-content",
286 "files to include inline between the content and </body> of a rendered \
287 Markdown file or generated documentation",
291 unstable("markdown-before-content", |o| {
294 "markdown-before-content",
295 "files to include inline between <body> and the content of a rendered \
296 Markdown file or generated documentation",
300 unstable("markdown-after-content", |o| {
303 "markdown-after-content",
304 "files to include inline between the content and </body> of a rendered \
305 Markdown file or generated documentation",
309 stable("markdown-playground-url", |o| {
310 o.optopt("", "markdown-playground-url", "URL to send code snippets to", "URL")
312 stable("markdown-no-toc", |o| {
313 o.optflag("", "markdown-no-toc", "don't include table of contents")
319 "To add some CSS rules with a given file to generate doc with your \
320 own theme. However, your theme might break if the rustdoc's generated HTML \
321 changes, so be careful!",
326 o.optmulti("Z", "", "internal and debugging options (only on nightly build)", "FLAG")
328 stable("sysroot", |o| o.optopt("", "sysroot", "Override the system root", "PATH")),
329 unstable("playground-url", |o| {
333 "URL to send code snippets to, may be reset by --markdown-playground-url \
334 or `#![doc(html_playground_url=...)]`",
338 unstable("display-warnings", |o| {
339 o.optflag("", "display-warnings", "to print code warnings when testing doc")
341 stable("crate-version", |o| {
342 o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
344 unstable("sort-modules-by-appearance", |o| {
347 "sort-modules-by-appearance",
348 "sort modules by where they appear in the program, rather than alphabetically",
351 stable("default-theme", |o| {
355 "Set the default theme. THEME should be the theme name, generally lowercase. \
356 If an unknown default theme is specified, the builtin default is used. \
357 The set of themes, and the rustdoc built-in default, are not stable.",
361 unstable("default-setting", |o| {
365 "Default value for a rustdoc setting (used when \"rustdoc-SETTING\" is absent \
366 from web browser Local Storage). If VALUE is not supplied, \"true\" is used. \
367 Supported SETTINGs and VALUEs are not documented and not stable.",
371 stable("theme", |o| {
375 "additional themes which will be added to the generated docs",
379 stable("check-theme", |o| {
380 o.optmulti("", "check-theme", "check if given theme is valid", "FILES")
382 unstable("resource-suffix", |o| {
386 "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
387 \"light-suffix.css\"",
391 stable("edition", |o| {
395 "edition to use when compiling rust code (default: 2015)",
399 stable("color", |o| {
403 "Configure coloring of output:
404 auto = colorize, if output goes to a tty (default);
405 always = always colorize output;
406 never = never colorize output",
410 stable("error-format", |o| {
414 "How errors and other messages are produced",
419 o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
421 unstable("disable-minification", |o| {
422 o.optflag("", "disable-minification", "Disable minification applied on JS files")
424 stable("warn", |o| o.optmulti("W", "warn", "Set lint warnings", "OPT")),
425 stable("allow", |o| o.optmulti("A", "allow", "Set lint allowed", "OPT")),
426 stable("deny", |o| o.optmulti("D", "deny", "Set lint denied", "OPT")),
427 stable("forbid", |o| o.optmulti("F", "forbid", "Set lint forbidden", "OPT")),
428 stable("cap-lints", |o| {
432 "Set the most restrictive lint level. \
433 More restrictive lints are capped at this \
434 level. By default, it is at `forbid` level.",
438 unstable("index-page", |o| {
439 o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
441 unstable("enable-index-page", |o| {
442 o.optflag("", "enable-index-page", "To enable generation of the index page")
444 unstable("static-root-path", |o| {
448 "Path string to force loading static files from in output pages. \
449 If not set, uses combinations of '../' to reach the documentation root.",
453 unstable("disable-per-crate-search", |o| {
456 "disable-per-crate-search",
457 "disables generating the crate selector on the search box",
460 unstable("persist-doctests", |o| {
464 "Directory to persist doctest executables into",
468 unstable("show-coverage", |o| {
472 "calculate percentage of public items with documentation",
475 unstable("enable-per-target-ignores", |o| {
478 "enable-per-target-ignores",
479 "parse ignore-foo for ignoring doctests on a per-target basis",
482 unstable("runtool", |o| {
487 "The tool to run tests with when building for a different target than host",
490 unstable("runtool-arg", |o| {
495 "One (of possibly many) arguments to pass to the runtool",
498 unstable("test-builder", |o| {
499 o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH")
501 unstable("check", |o| o.optflag("", "check", "Run rustdoc checks")),
502 unstable("generate-redirect-map", |o| {
505 "generate-redirect-map",
506 "Generate JSON file at the top level instead of generating HTML redirection files",
512 fn usage(argv0: &str) {
513 let mut options = getopts::Options::new();
514 for option in opts() {
515 (option.apply)(&mut options);
517 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
518 println!(" @path Read newline separated options from `path`\n");
519 println!("More information available at https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html")
522 /// A result type used by several functions under `main()`.
523 type MainResult = Result<(), ErrorReported>;
525 fn main_args(at_args: &[String]) -> MainResult {
526 let args = rustc_driver::args::arg_expand_all(at_args);
528 let mut options = getopts::Options::new();
529 for option in opts() {
530 (option.apply)(&mut options);
532 let matches = match options.parse(&args[1..]) {
535 early_error(ErrorOutputType::default(), &err.to_string());
539 // Note that we discard any distinction between different non-zero exit
540 // codes from `from_matches` here.
541 let options = match config::Options::from_matches(&matches) {
543 Err(code) => return if code == 0 { Ok(()) } else { Err(ErrorReported) },
545 rustc_interface::util::setup_callbacks_and_run_in_thread_pool_with_globals(
547 1, // this runs single-threaded, even in a parallel compiler
549 move || main_options(options),
553 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
557 diag.struct_err(&err).emit();
563 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
565 renderopts: config::RenderOptions,
566 cache: formats::cache::Cache,
567 diag: &rustc_errors::Handler,
568 edition: rustc_span::edition::Edition,
571 match formats::run_format::<T>(krate, renderopts, cache, &diag, edition, tcx) {
574 let mut msg = diag.struct_err(&format!("couldn't generate documentation: {}", e.error));
575 let file = e.file.display().to_string();
579 msg.note(&format!("failed to create or modify \"{}\"", file)).emit()
586 fn main_options(options: config::Options) -> MainResult {
587 let diag = core::new_handler(options.error_format, None, &options.debugging_opts);
589 match (options.should_test, options.markdown_input()) {
590 (true, true) => return wrap_return(&diag, markdown::test(options)),
591 (true, false) => return doctest::run(options),
595 markdown::render(&options.input, options.render_options, options.edition),
601 // need to move these items separately because we lose them by the time the closure is called,
602 // but we can't create the Handler ahead of time because it's not Send
603 let diag_opts = (options.error_format, options.edition, options.debugging_opts.clone());
604 let show_coverage = options.show_coverage;
605 let run_check = options.run_check;
607 // First, parse the crate and extract all relevant information.
608 info!("starting to run rustc");
610 // Interpret the input file as a rust source file, passing it through the
611 // compiler all the way through the analysis passes. The rustdoc output is
612 // then generated from the cleaned AST of the crate. This runs all the
613 // plug/cleaning passes.
614 let crate_version = options.crate_version.clone();
616 let default_passes = options.default_passes;
617 let output_format = options.output_format;
618 // FIXME: fix this clone (especially render_options)
619 let externs = options.externs.clone();
620 let manual_passes = options.manual_passes.clone();
621 let render_options = options.render_options.clone();
622 let config = core::create_config(options);
624 interface::create_compiler_and_run(config, |compiler| {
625 compiler.enter(|queries| {
626 let sess = compiler.session();
628 // We need to hold on to the complete resolver, so we cause everything to be
629 // cloned for the analysis passes to use. Suboptimal, but necessary in the
630 // current architecture.
631 let resolver = core::create_resolver(externs, queries, &sess);
633 if sess.has_errors() {
634 sess.fatal("Compilation failed, aborting rustdoc");
637 let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).peek_mut();
639 global_ctxt.enter(|tcx| {
640 let (krate, render_opts, mut cache) = sess.time("run_global_ctxt", || {
641 core::run_global_ctxt(
650 info!("finished with rustc");
652 cache.crate_version = crate_version;
655 // if we ran coverage, bail early, we don't need to also generate docs at this point
656 // (also we didn't load in any of the useful passes)
658 } else if run_check {
659 // Since we're in "check" mode, no need to generate anything beyond this point.
663 info!("going to format");
664 let (error_format, edition, debugging_options) = diag_opts;
665 let diag = core::new_handler(error_format, None, &debugging_options);
666 match output_format {
667 config::OutputFormat::Html => sess.time("render_html", || {
668 run_renderer::<html::render::Context<'_>>(
677 config::OutputFormat::Json => sess.time("render_json", || {
678 run_renderer::<json::JsonRenderer<'_>>(