]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Rollup merge of #82714 - estebank:missing-braces, r=oli-obk
[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(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 #[macro_use]
75 mod externalfiles;
76
77 mod clean;
78 mod config;
79 mod core;
80 mod docfs;
81 mod doctree;
82 #[macro_use]
83 mod error;
84 mod doctest;
85 mod fold;
86 mod formats;
87 // used by the error-index generator, so it needs to be public
88 pub mod html;
89 mod json;
90 crate mod lint;
91 mod markdown;
92 mod passes;
93 mod theme;
94 mod visit_ast;
95 mod visit_lib;
96
97 pub fn main() {
98     rustc_driver::set_sigpipe_handler();
99     rustc_driver::install_ice_hook();
100
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).
110     init_logging();
111     rustc_driver::init_env_logger("RUSTDOC_LOG");
112
113     let exit_code = rustc_driver::catch_with_exit_code(|| match get_args() {
114         Some(args) => main_args(&args),
115         _ => Err(ErrorReported),
116     });
117     process::exit(exit_code);
118 }
119
120 fn init_logging() {
121     use std::io;
122
123     // FIXME remove these and use winapi 0.3 instead
124     // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs, rustc_driver/lib.rs
125     #[cfg(unix)]
126     fn stdout_isatty() -> bool {
127         extern crate libc;
128         unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
129     }
130
131     #[cfg(windows)]
132     fn stdout_isatty() -> bool {
133         extern crate winapi;
134         use winapi::um::consoleapi::GetConsoleMode;
135         use winapi::um::processenv::GetStdHandle;
136         use winapi::um::winbase::STD_OUTPUT_HANDLE;
137
138         unsafe {
139             let handle = GetStdHandle(STD_OUTPUT_HANDLE);
140             let mut out = 0;
141             GetConsoleMode(handle, &mut out) != 0
142         }
143     }
144
145     let color_logs = match std::env::var("RUSTDOC_LOG_COLOR") {
146         Ok(value) => match value.as_ref() {
147             "always" => true,
148             "never" => false,
149             "auto" => stdout_isatty(),
150             _ => early_error(
151                 ErrorOutputType::default(),
152                 &format!(
153                     "invalid log color value '{}': expected one of always, never, or auto",
154                     value
155                 ),
156             ),
157         },
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",
162         ),
163     };
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)
169         .with_targets(true)
170         .with_wraparound(10)
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);
176
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();
180 }
181
182 fn get_args() -> Option<Vec<String>> {
183     env::args_os()
184         .enumerate()
185         .map(|(i, arg)| {
186             arg.into_string()
187                 .map_err(|arg| {
188                     early_warn(
189                         ErrorOutputType::default(),
190                         &format!("Argument {} is not valid Unicode: {:?}", i, arg),
191                     );
192                 })
193                 .ok()
194         })
195         .collect()
196 }
197
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;
201     vec![
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")),
205         stable("r", |o| {
206             o.optopt("r", "input-format", "the input type of the specified file", "[rust]")
207         }),
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")
212         }),
213         make_crate_type_option(),
214         stable("L", |o| {
215             o.optmulti("L", "library-path", "directory to add to crate search path", "DIR")
216         }),
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")
221         }),
222         stable("plugin-path", |o| o.optmulti("", "plugin-path", "removed", "DIR")),
223         stable("C", |o| {
224             o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
225         }),
226         stable("passes", |o| {
227             o.optmulti(
228                 "",
229                 "passes",
230                 "list of passes to also run, you might want to pass it multiple times; a value of \
231                  `list` will print available passes",
232                 "PASSES",
233             )
234         }),
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")
239         }),
240         unstable("document-hidden-items", |o| {
241             o.optflag("", "document-hidden-items", "document items that have doc(hidden)")
242         }),
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")
246         }),
247         unstable("test-run-directory", |o| {
248             o.optopt(
249                 "",
250                 "test-run-directory",
251                 "The working directory in which to run tests",
252                 "PATH",
253             )
254         }),
255         stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
256         stable("markdown-css", |o| {
257             o.optmulti(
258                 "",
259                 "markdown-css",
260                 "CSS files to include via <link> in a rendered Markdown file",
261                 "FILES",
262             )
263         }),
264         stable("html-in-header", |o| {
265             o.optmulti(
266                 "",
267                 "html-in-header",
268                 "files to include inline in the <head> section of a rendered Markdown file \
269                  or generated documentation",
270                 "FILES",
271             )
272         }),
273         stable("html-before-content", |o| {
274             o.optmulti(
275                 "",
276                 "html-before-content",
277                 "files to include inline between <body> and the content of a rendered \
278                  Markdown file or generated documentation",
279                 "FILES",
280             )
281         }),
282         stable("html-after-content", |o| {
283             o.optmulti(
284                 "",
285                 "html-after-content",
286                 "files to include inline between the content and </body> of a rendered \
287                  Markdown file or generated documentation",
288                 "FILES",
289             )
290         }),
291         unstable("markdown-before-content", |o| {
292             o.optmulti(
293                 "",
294                 "markdown-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         unstable("markdown-after-content", |o| {
301             o.optmulti(
302                 "",
303                 "markdown-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         stable("markdown-playground-url", |o| {
310             o.optopt("", "markdown-playground-url", "URL to send code snippets to", "URL")
311         }),
312         stable("markdown-no-toc", |o| {
313             o.optflag("", "markdown-no-toc", "don't include table of contents")
314         }),
315         stable("e", |o| {
316             o.optopt(
317                 "e",
318                 "extend-css",
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!",
322                 "PATH",
323             )
324         }),
325         unstable("Z", |o| {
326             o.optmulti("Z", "", "internal and debugging options (only on nightly build)", "FLAG")
327         }),
328         stable("sysroot", |o| o.optopt("", "sysroot", "Override the system root", "PATH")),
329         unstable("playground-url", |o| {
330             o.optopt(
331                 "",
332                 "playground-url",
333                 "URL to send code snippets to, may be reset by --markdown-playground-url \
334                  or `#![doc(html_playground_url=...)]`",
335                 "URL",
336             )
337         }),
338         unstable("display-warnings", |o| {
339             o.optflag("", "display-warnings", "to print code warnings when testing doc")
340         }),
341         stable("crate-version", |o| {
342             o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
343         }),
344         unstable("sort-modules-by-appearance", |o| {
345             o.optflag(
346                 "",
347                 "sort-modules-by-appearance",
348                 "sort modules by where they appear in the program, rather than alphabetically",
349             )
350         }),
351         stable("default-theme", |o| {
352             o.optopt(
353                 "",
354                 "default-theme",
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.",
358                 "THEME",
359             )
360         }),
361         unstable("default-setting", |o| {
362             o.optmulti(
363                 "",
364                 "default-setting",
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.",
368                 "SETTING[=VALUE]",
369             )
370         }),
371         stable("theme", |o| {
372             o.optmulti(
373                 "",
374                 "theme",
375                 "additional themes which will be added to the generated docs",
376                 "FILES",
377             )
378         }),
379         stable("check-theme", |o| {
380             o.optmulti("", "check-theme", "check if given theme is valid", "FILES")
381         }),
382         unstable("resource-suffix", |o| {
383             o.optopt(
384                 "",
385                 "resource-suffix",
386                 "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
387                  \"light-suffix.css\"",
388                 "PATH",
389             )
390         }),
391         stable("edition", |o| {
392             o.optopt(
393                 "",
394                 "edition",
395                 "edition to use when compiling rust code (default: 2015)",
396                 "EDITION",
397             )
398         }),
399         stable("color", |o| {
400             o.optopt(
401                 "",
402                 "color",
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",
407                 "auto|always|never",
408             )
409         }),
410         stable("error-format", |o| {
411             o.optopt(
412                 "",
413                 "error-format",
414                 "How errors and other messages are produced",
415                 "human|json|short",
416             )
417         }),
418         stable("json", |o| {
419             o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
420         }),
421         unstable("disable-minification", |o| {
422             o.optflag("", "disable-minification", "Disable minification applied on JS files")
423         }),
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| {
429             o.optmulti(
430                 "",
431                 "cap-lints",
432                 "Set the most restrictive lint level. \
433                  More restrictive lints are capped at this \
434                  level. By default, it is at `forbid` level.",
435                 "LEVEL",
436             )
437         }),
438         unstable("index-page", |o| {
439             o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
440         }),
441         unstable("enable-index-page", |o| {
442             o.optflag("", "enable-index-page", "To enable generation of the index page")
443         }),
444         unstable("static-root-path", |o| {
445             o.optopt(
446                 "",
447                 "static-root-path",
448                 "Path string to force loading static files from in output pages. \
449                  If not set, uses combinations of '../' to reach the documentation root.",
450                 "PATH",
451             )
452         }),
453         unstable("disable-per-crate-search", |o| {
454             o.optflag(
455                 "",
456                 "disable-per-crate-search",
457                 "disables generating the crate selector on the search box",
458             )
459         }),
460         unstable("persist-doctests", |o| {
461             o.optopt(
462                 "",
463                 "persist-doctests",
464                 "Directory to persist doctest executables into",
465                 "PATH",
466             )
467         }),
468         unstable("show-coverage", |o| {
469             o.optflag(
470                 "",
471                 "show-coverage",
472                 "calculate percentage of public items with documentation",
473             )
474         }),
475         unstable("enable-per-target-ignores", |o| {
476             o.optflag(
477                 "",
478                 "enable-per-target-ignores",
479                 "parse ignore-foo for ignoring doctests on a per-target basis",
480             )
481         }),
482         unstable("runtool", |o| {
483             o.optopt(
484                 "",
485                 "runtool",
486                 "",
487                 "The tool to run tests with when building for a different target than host",
488             )
489         }),
490         unstable("runtool-arg", |o| {
491             o.optmulti(
492                 "",
493                 "runtool-arg",
494                 "",
495                 "One (of possibly many) arguments to pass to the runtool",
496             )
497         }),
498         unstable("test-builder", |o| {
499             o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH")
500         }),
501         unstable("check", |o| o.optflag("", "check", "Run rustdoc checks")),
502         unstable("generate-redirect-map", |o| {
503             o.optflag(
504                 "",
505                 "generate-redirect-map",
506                 "Generate JSON file at the top level instead of generating HTML redirection files",
507             )
508         }),
509     ]
510 }
511
512 fn usage(argv0: &str) {
513     let mut options = getopts::Options::new();
514     for option in opts() {
515         (option.apply)(&mut options);
516     }
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")
520 }
521
522 /// A result type used by several functions under `main()`.
523 type MainResult = Result<(), ErrorReported>;
524
525 fn main_args(at_args: &[String]) -> MainResult {
526     let args = rustc_driver::args::arg_expand_all(at_args);
527
528     let mut options = getopts::Options::new();
529     for option in opts() {
530         (option.apply)(&mut options);
531     }
532     let matches = match options.parse(&args[1..]) {
533         Ok(m) => m,
534         Err(err) => {
535             early_error(ErrorOutputType::default(), &err.to_string());
536         }
537     };
538
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) {
542         Ok(opts) => opts,
543         Err(code) => return if code == 0 { Ok(()) } else { Err(ErrorReported) },
544     };
545     rustc_interface::util::setup_callbacks_and_run_in_thread_pool_with_globals(
546         options.edition,
547         1, // this runs single-threaded, even in a parallel compiler
548         &None,
549         move || main_options(options),
550     )
551 }
552
553 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
554     match res {
555         Ok(()) => Ok(()),
556         Err(err) => {
557             diag.struct_err(&err).emit();
558             Err(ErrorReported)
559         }
560     }
561 }
562
563 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
564     krate: clean::Crate,
565     renderopts: config::RenderOptions,
566     cache: formats::cache::Cache,
567     diag: &rustc_errors::Handler,
568     edition: rustc_span::edition::Edition,
569     tcx: TyCtxt<'tcx>,
570 ) -> MainResult {
571     match formats::run_format::<T>(krate, renderopts, cache, &diag, edition, tcx) {
572         Ok(_) => Ok(()),
573         Err(e) => {
574             let mut msg = diag.struct_err(&format!("couldn't generate documentation: {}", e.error));
575             let file = e.file.display().to_string();
576             if file.is_empty() {
577                 msg.emit()
578             } else {
579                 msg.note(&format!("failed to create or modify \"{}\"", file)).emit()
580             }
581             Err(ErrorReported)
582         }
583     }
584 }
585
586 fn main_options(options: config::Options) -> MainResult {
587     let diag = core::new_handler(options.error_format, None, &options.debugging_opts);
588
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),
592         (false, true) => {
593             return wrap_return(
594                 &diag,
595                 markdown::render(&options.input, options.render_options, options.edition),
596             );
597         }
598         (false, false) => {}
599     }
600
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;
606
607     // First, parse the crate and extract all relevant information.
608     info!("starting to run rustc");
609
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();
615
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);
623
624     interface::create_compiler_and_run(config, |compiler| {
625         compiler.enter(|queries| {
626             let sess = compiler.session();
627
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);
632
633             if sess.has_errors() {
634                 sess.fatal("Compilation failed, aborting rustdoc");
635             }
636
637             let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).peek_mut();
638
639             global_ctxt.enter(|tcx| {
640                 let (krate, render_opts, mut cache) = sess.time("run_global_ctxt", || {
641                     core::run_global_ctxt(
642                         tcx,
643                         resolver,
644                         default_passes,
645                         manual_passes,
646                         render_options,
647                         output_format,
648                     )
649                 });
650                 info!("finished with rustc");
651
652                 cache.crate_version = crate_version;
653
654                 if show_coverage {
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)
657                     return Ok(());
658                 } else if run_check {
659                     // Since we're in "check" mode, no need to generate anything beyond this point.
660                     return Ok(());
661                 }
662
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<'_>>(
669                             krate,
670                             render_opts,
671                             cache,
672                             &diag,
673                             edition,
674                             tcx,
675                         )
676                     }),
677                     config::OutputFormat::Json => sess.time("render_json", || {
678                         run_renderer::<json::JsonRenderer<'_>>(
679                             krate,
680                             render_opts,
681                             cache,
682                             &diag,
683                             edition,
684                             tcx,
685                         )
686                     }),
687                 }
688             })
689         })
690     })
691 }