]> git.proxmox.com Git - rustc.git/blob - src/librustdoc/lib.rs
New upstream version 1.52.0~beta.3+dfsg1
[rustc.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(box_patterns)]
8 #![feature(box_syntax)]
9 #![feature(in_band_lifetimes)]
10 #![feature(nll)]
11 #![feature(or_patterns)]
12 #![feature(test)]
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)]
20
21 #[macro_use]
22 extern crate lazy_static;
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 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;
61
62 use std::default::Default;
63 use std::env;
64 use std::process;
65
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};
73
74 /// A macro to create a FxHashMap.
75 ///
76 /// Example:
77 ///
78 /// ```
79 /// let letters = map!{"a" => "b", "c" => "d"};
80 /// ```
81 ///
82 /// Trailing commas are allowed.
83 /// Commas between elements are required (even if the expression is a block).
84 macro_rules! map {
85 ($( $key: expr => $val: expr ),* $(,)*) => {{
86 let mut map = ::rustc_data_structures::fx::FxHashMap::default();
87 $( map.insert($key, $val); )*
88 map
89 }}
90 }
91
92 #[macro_use]
93 mod externalfiles;
94
95 mod clean;
96 mod config;
97 mod core;
98 mod docfs;
99 mod doctree;
100 #[macro_use]
101 mod error;
102 mod doctest;
103 mod fold;
104 mod formats;
105 // used by the error-index generator, so it needs to be public
106 pub mod html;
107 mod json;
108 crate mod lint;
109 mod markdown;
110 mod passes;
111 mod theme;
112 mod visit_ast;
113 mod visit_lib;
114
115 pub fn main() {
116 rustc_driver::set_sigpipe_handler();
117 rustc_driver::install_ice_hook();
118
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).
128 init_logging();
129 rustc_driver::init_env_logger("RUSTDOC_LOG");
130
131 let exit_code = rustc_driver::catch_with_exit_code(|| match get_args() {
132 Some(args) => main_args(&args),
133 _ => Err(ErrorReported),
134 });
135 process::exit(exit_code);
136 }
137
138 fn init_logging() {
139 use std::io;
140
141 // FIXME remove these and use winapi 0.3 instead
142 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs, rustc_driver/lib.rs
143 #[cfg(unix)]
144 fn stdout_isatty() -> bool {
145 extern crate libc;
146 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
147 }
148
149 #[cfg(windows)]
150 fn stdout_isatty() -> bool {
151 extern crate winapi;
152 use winapi::um::consoleapi::GetConsoleMode;
153 use winapi::um::processenv::GetStdHandle;
154 use winapi::um::winbase::STD_OUTPUT_HANDLE;
155
156 unsafe {
157 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
158 let mut out = 0;
159 GetConsoleMode(handle, &mut out) != 0
160 }
161 }
162
163 let color_logs = match std::env::var("RUSTDOC_LOG_COLOR") {
164 Ok(value) => match value.as_ref() {
165 "always" => true,
166 "never" => false,
167 "auto" => stdout_isatty(),
168 _ => early_error(
169 ErrorOutputType::default(),
170 &format!(
171 "invalid log color value '{}': expected one of always, never, or auto",
172 value
173 ),
174 ),
175 },
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",
180 ),
181 };
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)
187 .with_targets(true)
188 .with_wraparound(10)
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);
194
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();
198 }
199
200 fn get_args() -> Option<Vec<String>> {
201 env::args_os()
202 .enumerate()
203 .map(|(i, arg)| {
204 arg.into_string()
205 .map_err(|arg| {
206 early_warn(
207 ErrorOutputType::default(),
208 &format!("Argument {} is not valid Unicode: {:?}", i, arg),
209 );
210 })
211 .ok()
212 })
213 .collect()
214 }
215
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;
219 vec![
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")),
223 stable("r", |o| {
224 o.optopt("r", "input-format", "the input type of the specified file", "[rust]")
225 }),
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")
230 }),
231 make_crate_type_option(),
232 stable("L", |o| {
233 o.optmulti("L", "library-path", "directory to add to crate search path", "DIR")
234 }),
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")
239 }),
240 stable("plugin-path", |o| o.optmulti("", "plugin-path", "removed", "DIR")),
241 stable("C", |o| {
242 o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
243 }),
244 stable("passes", |o| {
245 o.optmulti(
246 "",
247 "passes",
248 "list of passes to also run, you might want to pass it multiple times; a value of \
249 `list` will print available passes",
250 "PASSES",
251 )
252 }),
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")
257 }),
258 unstable("document-hidden-items", |o| {
259 o.optflag("", "document-hidden-items", "document items that have doc(hidden)")
260 }),
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")
264 }),
265 unstable("test-run-directory", |o| {
266 o.optopt(
267 "",
268 "test-run-directory",
269 "The working directory in which to run tests",
270 "PATH",
271 )
272 }),
273 stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
274 stable("markdown-css", |o| {
275 o.optmulti(
276 "",
277 "markdown-css",
278 "CSS files to include via <link> in a rendered Markdown file",
279 "FILES",
280 )
281 }),
282 stable("html-in-header", |o| {
283 o.optmulti(
284 "",
285 "html-in-header",
286 "files to include inline in the <head> section of a rendered Markdown file \
287 or generated documentation",
288 "FILES",
289 )
290 }),
291 stable("html-before-content", |o| {
292 o.optmulti(
293 "",
294 "html-before-content",
295 "files to include inline between <body> and the content of a rendered \
296 Markdown file or generated documentation",
297 "FILES",
298 )
299 }),
300 stable("html-after-content", |o| {
301 o.optmulti(
302 "",
303 "html-after-content",
304 "files to include inline between the content and </body> of a rendered \
305 Markdown file or generated documentation",
306 "FILES",
307 )
308 }),
309 unstable("markdown-before-content", |o| {
310 o.optmulti(
311 "",
312 "markdown-before-content",
313 "files to include inline between <body> and the content of a rendered \
314 Markdown file or generated documentation",
315 "FILES",
316 )
317 }),
318 unstable("markdown-after-content", |o| {
319 o.optmulti(
320 "",
321 "markdown-after-content",
322 "files to include inline between the content and </body> of a rendered \
323 Markdown file or generated documentation",
324 "FILES",
325 )
326 }),
327 stable("markdown-playground-url", |o| {
328 o.optopt("", "markdown-playground-url", "URL to send code snippets to", "URL")
329 }),
330 stable("markdown-no-toc", |o| {
331 o.optflag("", "markdown-no-toc", "don't include table of contents")
332 }),
333 stable("e", |o| {
334 o.optopt(
335 "e",
336 "extend-css",
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!",
340 "PATH",
341 )
342 }),
343 unstable("Z", |o| {
344 o.optmulti("Z", "", "internal and debugging options (only on nightly build)", "FLAG")
345 }),
346 stable("sysroot", |o| o.optopt("", "sysroot", "Override the system root", "PATH")),
347 unstable("playground-url", |o| {
348 o.optopt(
349 "",
350 "playground-url",
351 "URL to send code snippets to, may be reset by --markdown-playground-url \
352 or `#![doc(html_playground_url=...)]`",
353 "URL",
354 )
355 }),
356 unstable("display-warnings", |o| {
357 o.optflag("", "display-warnings", "to print code warnings when testing doc")
358 }),
359 stable("crate-version", |o| {
360 o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
361 }),
362 unstable("sort-modules-by-appearance", |o| {
363 o.optflag(
364 "",
365 "sort-modules-by-appearance",
366 "sort modules by where they appear in the program, rather than alphabetically",
367 )
368 }),
369 stable("default-theme", |o| {
370 o.optopt(
371 "",
372 "default-theme",
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.",
376 "THEME",
377 )
378 }),
379 unstable("default-setting", |o| {
380 o.optmulti(
381 "",
382 "default-setting",
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.",
386 "SETTING[=VALUE]",
387 )
388 }),
389 stable("theme", |o| {
390 o.optmulti(
391 "",
392 "theme",
393 "additional themes which will be added to the generated docs",
394 "FILES",
395 )
396 }),
397 stable("check-theme", |o| {
398 o.optmulti("", "check-theme", "check if given theme is valid", "FILES")
399 }),
400 unstable("resource-suffix", |o| {
401 o.optopt(
402 "",
403 "resource-suffix",
404 "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
405 \"light-suffix.css\"",
406 "PATH",
407 )
408 }),
409 stable("edition", |o| {
410 o.optopt(
411 "",
412 "edition",
413 "edition to use when compiling rust code (default: 2015)",
414 "EDITION",
415 )
416 }),
417 stable("color", |o| {
418 o.optopt(
419 "",
420 "color",
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",
425 "auto|always|never",
426 )
427 }),
428 stable("error-format", |o| {
429 o.optopt(
430 "",
431 "error-format",
432 "How errors and other messages are produced",
433 "human|json|short",
434 )
435 }),
436 stable("json", |o| {
437 o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
438 }),
439 unstable("disable-minification", |o| {
440 o.optflag("", "disable-minification", "Disable minification applied on JS files")
441 }),
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| {
447 o.optmulti(
448 "",
449 "cap-lints",
450 "Set the most restrictive lint level. \
451 More restrictive lints are capped at this \
452 level. By default, it is at `forbid` level.",
453 "LEVEL",
454 )
455 }),
456 unstable("index-page", |o| {
457 o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
458 }),
459 unstable("enable-index-page", |o| {
460 o.optflag("", "enable-index-page", "To enable generation of the index page")
461 }),
462 unstable("static-root-path", |o| {
463 o.optopt(
464 "",
465 "static-root-path",
466 "Path string to force loading static files from in output pages. \
467 If not set, uses combinations of '../' to reach the documentation root.",
468 "PATH",
469 )
470 }),
471 unstable("disable-per-crate-search", |o| {
472 o.optflag(
473 "",
474 "disable-per-crate-search",
475 "disables generating the crate selector on the search box",
476 )
477 }),
478 unstable("persist-doctests", |o| {
479 o.optopt(
480 "",
481 "persist-doctests",
482 "Directory to persist doctest executables into",
483 "PATH",
484 )
485 }),
486 unstable("show-coverage", |o| {
487 o.optflag(
488 "",
489 "show-coverage",
490 "calculate percentage of public items with documentation",
491 )
492 }),
493 unstable("enable-per-target-ignores", |o| {
494 o.optflag(
495 "",
496 "enable-per-target-ignores",
497 "parse ignore-foo for ignoring doctests on a per-target basis",
498 )
499 }),
500 unstable("runtool", |o| {
501 o.optopt(
502 "",
503 "runtool",
504 "",
505 "The tool to run tests with when building for a different target than host",
506 )
507 }),
508 unstable("runtool-arg", |o| {
509 o.optmulti(
510 "",
511 "runtool-arg",
512 "",
513 "One (of possibly many) arguments to pass to the runtool",
514 )
515 }),
516 unstable("test-builder", |o| {
517 o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH")
518 }),
519 unstable("check", |o| o.optflag("", "check", "Run rustdoc checks")),
520 unstable("generate-redirect-map", |o| {
521 o.optflag(
522 "",
523 "generate-redirect-map",
524 "Generate JSON file at the top level instead of generating HTML redirection files",
525 )
526 }),
527 unstable("print", |o| {
528 o.optmulti("", "print", "Rustdoc information to print on stdout", "[unversioned-files]")
529 }),
530 ]
531 }
532
533 fn usage(argv0: &str) {
534 let mut options = getopts::Options::new();
535 for option in opts() {
536 (option.apply)(&mut options);
537 }
538 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
539 println!(" @path Read newline separated options from `path`\n");
540 println!("More information available at https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html")
541 }
542
543 /// A result type used by several functions under `main()`.
544 type MainResult = Result<(), ErrorReported>;
545
546 fn main_args(at_args: &[String]) -> MainResult {
547 let args = rustc_driver::args::arg_expand_all(at_args);
548
549 let mut options = getopts::Options::new();
550 for option in opts() {
551 (option.apply)(&mut options);
552 }
553 let matches = match options.parse(&args[1..]) {
554 Ok(m) => m,
555 Err(err) => {
556 early_error(ErrorOutputType::default(), &err.to_string());
557 }
558 };
559
560 // Note that we discard any distinction between different non-zero exit
561 // codes from `from_matches` here.
562 let options = match config::Options::from_matches(&matches) {
563 Ok(opts) => opts,
564 Err(code) => return if code == 0 { Ok(()) } else { Err(ErrorReported) },
565 };
566 rustc_interface::util::setup_callbacks_and_run_in_thread_pool_with_globals(
567 options.edition,
568 1, // this runs single-threaded, even in a parallel compiler
569 &None,
570 move || main_options(options),
571 )
572 }
573
574 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
575 match res {
576 Ok(()) => Ok(()),
577 Err(err) => {
578 diag.struct_err(&err).emit();
579 Err(ErrorReported)
580 }
581 }
582 }
583
584 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
585 krate: clean::Crate,
586 renderopts: config::RenderOptions,
587 cache: formats::cache::Cache,
588 diag: &rustc_errors::Handler,
589 edition: rustc_span::edition::Edition,
590 tcx: TyCtxt<'tcx>,
591 ) -> MainResult {
592 match formats::run_format::<T>(krate, renderopts, cache, &diag, edition, tcx) {
593 Ok(_) => Ok(()),
594 Err(e) => {
595 let mut msg = diag.struct_err(&format!("couldn't generate documentation: {}", e.error));
596 let file = e.file.display().to_string();
597 if file.is_empty() {
598 msg.emit()
599 } else {
600 msg.note(&format!("failed to create or modify \"{}\"", file)).emit()
601 }
602 Err(ErrorReported)
603 }
604 }
605 }
606
607 fn main_options(options: config::Options) -> MainResult {
608 let diag = core::new_handler(options.error_format, None, &options.debugging_opts);
609
610 match (options.should_test, options.markdown_input()) {
611 (true, true) => return wrap_return(&diag, markdown::test(options)),
612 (true, false) => return doctest::run(options),
613 (false, true) => {
614 return wrap_return(
615 &diag,
616 markdown::render(&options.input, options.render_options, options.edition),
617 );
618 }
619 (false, false) => {}
620 }
621
622 // need to move these items separately because we lose them by the time the closure is called,
623 // but we can't create the Handler ahead of time because it's not Send
624 let diag_opts = (options.error_format, options.edition, options.debugging_opts.clone());
625 let show_coverage = options.show_coverage;
626 let run_check = options.run_check;
627
628 // First, parse the crate and extract all relevant information.
629 info!("starting to run rustc");
630
631 // Interpret the input file as a rust source file, passing it through the
632 // compiler all the way through the analysis passes. The rustdoc output is
633 // then generated from the cleaned AST of the crate. This runs all the
634 // plug/cleaning passes.
635 let crate_version = options.crate_version.clone();
636
637 let default_passes = options.default_passes;
638 let output_format = options.output_format;
639 // FIXME: fix this clone (especially render_options)
640 let externs = options.externs.clone();
641 let manual_passes = options.manual_passes.clone();
642 let render_options = options.render_options.clone();
643 let config = core::create_config(options);
644
645 interface::create_compiler_and_run(config, |compiler| {
646 compiler.enter(|queries| {
647 let sess = compiler.session();
648
649 // We need to hold on to the complete resolver, so we cause everything to be
650 // cloned for the analysis passes to use. Suboptimal, but necessary in the
651 // current architecture.
652 let resolver = core::create_resolver(externs, queries, &sess);
653
654 if sess.has_errors() {
655 sess.fatal("Compilation failed, aborting rustdoc");
656 }
657
658 let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).peek_mut();
659
660 global_ctxt.enter(|tcx| {
661 let (krate, render_opts, mut cache) = sess.time("run_global_ctxt", || {
662 core::run_global_ctxt(
663 tcx,
664 resolver,
665 default_passes,
666 manual_passes,
667 render_options,
668 output_format,
669 )
670 });
671 info!("finished with rustc");
672
673 cache.crate_version = crate_version;
674
675 if show_coverage {
676 // if we ran coverage, bail early, we don't need to also generate docs at this point
677 // (also we didn't load in any of the useful passes)
678 return Ok(());
679 } else if run_check {
680 // Since we're in "check" mode, no need to generate anything beyond this point.
681 return Ok(());
682 }
683
684 info!("going to format");
685 let (error_format, edition, debugging_options) = diag_opts;
686 let diag = core::new_handler(error_format, None, &debugging_options);
687 match output_format {
688 config::OutputFormat::Html => sess.time("render_html", || {
689 run_renderer::<html::render::Context<'_>>(
690 krate,
691 render_opts,
692 cache,
693 &diag,
694 edition,
695 tcx,
696 )
697 }),
698 config::OutputFormat::Json => sess.time("render_json", || {
699 run_renderer::<json::JsonRenderer<'_>>(
700 krate,
701 render_opts,
702 cache,
703 &diag,
704 edition,
705 tcx,
706 )
707 }),
708 }
709 })
710 })
711 })
712 }