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_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};
74 /// A macro to create a FxHashMap.
79 /// let letters = map!{"a" => "b", "c" => "d"};
82 /// Trailing commas are allowed.
83 /// Commas between elements are required (even if the expression is a block).
85 ($( $key: expr => $val: expr ),* $(,)*) => {{
86 let mut map = ::rustc_data_structures::fx::FxHashMap::default();
87 $( map.insert($key, $val); )*
105 // used by the error-index generator, so it needs to be public
116 rustc_driver::set_sigpipe_handler();
117 rustc_driver::install_ice_hook();
119 // When using CI artifacts (with `download_stage1 = true`), tracing is unconditionally built
120 // with `--features=static_max_level_info`, which disables almost all rustdoc logging. To avoid
121 // this, compile our own version of `tracing` that logs all levels.
122 // NOTE: this compiles both versions of tracing unconditionally, because
123 // - The compile time hit is not that bad, especially compared to rustdoc's incremental times, and
124 // - Otherwise, there's no warning that logging is being ignored when `download_stage1 = true`.
125 // NOTE: The reason this doesn't show double logging when `download_stage1 = false` and
126 // `debug_logging = true` is because all rustc logging goes to its version of tracing (the one
127 // in the sysroot), and all of rustdoc's logging goes to its version (the one in Cargo.toml).
129 rustc_driver::init_env_logger("RUSTDOC_LOG");
131 let exit_code = rustc_driver::catch_with_exit_code(|| match get_args() {
132 Some(args) => main_args(&args),
133 _ => Err(ErrorReported),
135 process::exit(exit_code);
141 // FIXME remove these and use winapi 0.3 instead
142 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs, rustc_driver/lib.rs
144 fn stdout_isatty() -> bool {
146 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
150 fn stdout_isatty() -> bool {
152 use winapi::um::consoleapi::GetConsoleMode;
153 use winapi::um::processenv::GetStdHandle;
154 use winapi::um::winbase::STD_OUTPUT_HANDLE;
157 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
159 GetConsoleMode(handle, &mut out) != 0
163 let color_logs = match std::env::var("RUSTDOC_LOG_COLOR") {
164 Ok(value) => match value.as_ref() {
167 "auto" => stdout_isatty(),
169 ErrorOutputType::default(),
171 "invalid log color value '{}': expected one of always, never, or auto",
176 Err(std::env::VarError::NotPresent) => stdout_isatty(),
177 Err(std::env::VarError::NotUnicode(_value)) => early_error(
178 ErrorOutputType::default(),
179 "non-Unicode log color value: expected one of always, never, or auto",
182 let filter = tracing_subscriber::EnvFilter::from_env("RUSTDOC_LOG");
183 let layer = tracing_tree::HierarchicalLayer::default()
184 .with_writer(io::stderr)
185 .with_indent_lines(true)
186 .with_ansi(color_logs)
189 .with_verbose_exit(true)
190 .with_verbose_entry(true)
191 .with_indent_amount(2);
192 #[cfg(parallel_compiler)]
193 let layer = layer.with_thread_ids(true).with_thread_names(true);
195 use tracing_subscriber::layer::SubscriberExt;
196 let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
197 tracing::subscriber::set_global_default(subscriber).unwrap();
200 fn get_args() -> Option<Vec<String>> {
207 ErrorOutputType::default(),
208 &format!("Argument {} is not valid Unicode: {:?}", i, arg),
216 fn opts() -> Vec<RustcOptGroup> {
217 let stable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::stable;
218 let unstable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::unstable;
220 stable("h", |o| o.optflag("h", "help", "show this help message")),
221 stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
222 stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
224 o.optopt("r", "input-format", "the input type of the specified file", "[rust]")
226 stable("w", |o| o.optopt("w", "output-format", "the output type to write", "[html]")),
227 stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
228 stable("crate-name", |o| {
229 o.optopt("", "crate-name", "specify the name of this crate", "NAME")
231 make_crate_type_option(),
233 o.optmulti("L", "library-path", "directory to add to crate search path", "DIR")
235 stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
236 stable("extern", |o| o.optmulti("", "extern", "pass an --extern to rustc", "NAME[=PATH]")),
237 unstable("extern-html-root-url", |o| {
238 o.optmulti("", "extern-html-root-url", "base URL to use for dependencies", "NAME=URL")
240 stable("plugin-path", |o| o.optmulti("", "plugin-path", "removed", "DIR")),
242 o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
244 stable("passes", |o| {
248 "list of passes to also run, you might want to pass it multiple times; a value of \
249 `list` will print available passes",
253 stable("plugins", |o| o.optmulti("", "plugins", "removed", "PLUGINS")),
254 stable("no-default", |o| o.optflag("", "no-defaults", "don't run the default passes")),
255 stable("document-private-items", |o| {
256 o.optflag("", "document-private-items", "document private items")
258 unstable("document-hidden-items", |o| {
259 o.optflag("", "document-hidden-items", "document items that have doc(hidden)")
261 stable("test", |o| o.optflag("", "test", "run code examples as tests")),
262 stable("test-args", |o| {
263 o.optmulti("", "test-args", "arguments to pass to the test runner", "ARGS")
265 unstable("test-run-directory", |o| {
268 "test-run-directory",
269 "The working directory in which to run tests",
273 stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
274 stable("markdown-css", |o| {
278 "CSS files to include via <link> in a rendered Markdown file",
282 stable("html-in-header", |o| {
286 "files to include inline in the <head> section of a rendered Markdown file \
287 or generated documentation",
291 stable("html-before-content", |o| {
294 "html-before-content",
295 "files to include inline between <body> and the content of a rendered \
296 Markdown file or generated documentation",
300 stable("html-after-content", |o| {
303 "html-after-content",
304 "files to include inline between the content and </body> of a rendered \
305 Markdown file or generated documentation",
309 unstable("markdown-before-content", |o| {
312 "markdown-before-content",
313 "files to include inline between <body> and the content of a rendered \
314 Markdown file or generated documentation",
318 unstable("markdown-after-content", |o| {
321 "markdown-after-content",
322 "files to include inline between the content and </body> of a rendered \
323 Markdown file or generated documentation",
327 stable("markdown-playground-url", |o| {
328 o.optopt("", "markdown-playground-url", "URL to send code snippets to", "URL")
330 stable("markdown-no-toc", |o| {
331 o.optflag("", "markdown-no-toc", "don't include table of contents")
337 "To add some CSS rules with a given file to generate doc with your \
338 own theme. However, your theme might break if the rustdoc's generated HTML \
339 changes, so be careful!",
344 o.optmulti("Z", "", "internal and debugging options (only on nightly build)", "FLAG")
346 stable("sysroot", |o| o.optopt("", "sysroot", "Override the system root", "PATH")),
347 unstable("playground-url", |o| {
351 "URL to send code snippets to, may be reset by --markdown-playground-url \
352 or `#![doc(html_playground_url=...)]`",
356 unstable("display-warnings", |o| {
357 o.optflag("", "display-warnings", "to print code warnings when testing doc")
359 stable("crate-version", |o| {
360 o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
362 unstable("sort-modules-by-appearance", |o| {
365 "sort-modules-by-appearance",
366 "sort modules by where they appear in the program, rather than alphabetically",
369 stable("default-theme", |o| {
373 "Set the default theme. THEME should be the theme name, generally lowercase. \
374 If an unknown default theme is specified, the builtin default is used. \
375 The set of themes, and the rustdoc built-in default, are not stable.",
379 unstable("default-setting", |o| {
383 "Default value for a rustdoc setting (used when \"rustdoc-SETTING\" is absent \
384 from web browser Local Storage). If VALUE is not supplied, \"true\" is used. \
385 Supported SETTINGs and VALUEs are not documented and not stable.",
389 stable("theme", |o| {
393 "additional themes which will be added to the generated docs",
397 stable("check-theme", |o| {
398 o.optmulti("", "check-theme", "check if given theme is valid", "FILES")
400 unstable("resource-suffix", |o| {
404 "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
405 \"light-suffix.css\"",
409 stable("edition", |o| {
413 "edition to use when compiling rust code (default: 2015)",
417 stable("color", |o| {
421 "Configure coloring of output:
422 auto = colorize, if output goes to a tty (default);
423 always = always colorize output;
424 never = never colorize output",
428 stable("error-format", |o| {
432 "How errors and other messages are produced",
437 o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
439 unstable("disable-minification", |o| {
440 o.optflag("", "disable-minification", "Disable minification applied on JS files")
442 stable("warn", |o| o.optmulti("W", "warn", "Set lint warnings", "OPT")),
443 stable("allow", |o| o.optmulti("A", "allow", "Set lint allowed", "OPT")),
444 stable("deny", |o| o.optmulti("D", "deny", "Set lint denied", "OPT")),
445 stable("forbid", |o| o.optmulti("F", "forbid", "Set lint forbidden", "OPT")),
446 stable("cap-lints", |o| {
450 "Set the most restrictive lint level. \
451 More restrictive lints are capped at this \
452 level. By default, it is at `forbid` level.",
456 unstable("index-page", |o| {
457 o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
459 unstable("enable-index-page", |o| {
460 o.optflag("", "enable-index-page", "To enable generation of the index page")
462 unstable("static-root-path", |o| {
466 "Path string to force loading static files from in output pages. \
467 If not set, uses combinations of '../' to reach the documentation root.",
471 unstable("disable-per-crate-search", |o| {
474 "disable-per-crate-search",
475 "disables generating the crate selector on the search box",
478 unstable("persist-doctests", |o| {
482 "Directory to persist doctest executables into",
486 unstable("show-coverage", |o| {
490 "calculate percentage of public items with documentation",
493 unstable("enable-per-target-ignores", |o| {
496 "enable-per-target-ignores",
497 "parse ignore-foo for ignoring doctests on a per-target basis",
500 unstable("runtool", |o| {
505 "The tool to run tests with when building for a different target than host",
508 unstable("runtool-arg", |o| {
513 "One (of possibly many) arguments to pass to the runtool",
516 unstable("test-builder", |o| {
517 o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH")
519 unstable("check", |o| o.optflag("", "check", "Run rustdoc checks")),
520 unstable("generate-redirect-map", |o| {
523 "generate-redirect-map",
524 "Generate JSON file at the top level instead of generating HTML redirection files",
527 unstable("print", |o| {
528 o.optmulti("", "print", "Rustdoc information to print on stdout", "[unversioned-files]")
530 unstable("emit", |o| {
534 "Comma separated list of types of output for rustdoc to emit",
535 "[unversioned-shared-resources,toolchain-shared-resources,invocation-specific]",
541 fn usage(argv0: &str) {
542 let mut options = getopts::Options::new();
543 for option in opts() {
544 (option.apply)(&mut options);
546 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
547 println!(" @path Read newline separated options from `path`\n");
548 println!("More information available at https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html")
551 /// A result type used by several functions under `main()`.
552 type MainResult = Result<(), ErrorReported>;
554 fn main_args(at_args: &[String]) -> MainResult {
555 let args = rustc_driver::args::arg_expand_all(at_args);
557 let mut options = getopts::Options::new();
558 for option in opts() {
559 (option.apply)(&mut options);
561 let matches = match options.parse(&args[1..]) {
564 early_error(ErrorOutputType::default(), &err.to_string());
568 // Note that we discard any distinction between different non-zero exit
569 // codes from `from_matches` here.
570 let options = match config::Options::from_matches(&matches) {
572 Err(code) => return if code == 0 { Ok(()) } else { Err(ErrorReported) },
574 rustc_interface::util::setup_callbacks_and_run_in_thread_pool_with_globals(
576 1, // this runs single-threaded, even in a parallel compiler
578 move || main_options(options),
582 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
586 diag.struct_err(&err).emit();
592 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
594 renderopts: config::RenderOptions,
595 cache: formats::cache::Cache,
596 diag: &rustc_errors::Handler,
597 edition: rustc_span::edition::Edition,
600 match formats::run_format::<T>(krate, renderopts, cache, &diag, edition, tcx) {
603 let mut msg = diag.struct_err(&format!("couldn't generate documentation: {}", e.error));
604 let file = e.file.display().to_string();
608 msg.note(&format!("failed to create or modify \"{}\"", file)).emit()
615 fn main_options(options: config::Options) -> MainResult {
616 let diag = core::new_handler(options.error_format, None, &options.debugging_opts);
618 match (options.should_test, options.markdown_input()) {
619 (true, true) => return wrap_return(&diag, markdown::test(options)),
620 (true, false) => return doctest::run(options),
624 markdown::render(&options.input, options.render_options, options.edition),
630 // need to move these items separately because we lose them by the time the closure is called,
631 // but we can't create the Handler ahead of time because it's not Send
632 let diag_opts = (options.error_format, options.edition, options.debugging_opts.clone());
633 let show_coverage = options.show_coverage;
634 let run_check = options.run_check;
636 // First, parse the crate and extract all relevant information.
637 info!("starting to run rustc");
639 // Interpret the input file as a rust source file, passing it through the
640 // compiler all the way through the analysis passes. The rustdoc output is
641 // then generated from the cleaned AST of the crate. This runs all the
642 // plug/cleaning passes.
643 let crate_version = options.crate_version.clone();
645 let default_passes = options.default_passes;
646 let output_format = options.output_format;
647 // FIXME: fix this clone (especially render_options)
648 let externs = options.externs.clone();
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(externs, 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<'_>>(