]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Rollup merge of #81542 - RReverser:wasi-symlink, r=alexcrichton
[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(peekable_next_if)]
13 #![feature(test)]
14 #![feature(crate_visibility_modifier)]
15 #![feature(never_type)]
16 #![feature(once_cell)]
17 #![feature(type_ascription)]
18 #![feature(str_split_once)]
19 #![feature(iter_intersperse)]
20 #![recursion_limit = "256"]
21 #![deny(rustc::internal)]
22
23 #[macro_use]
24 extern crate lazy_static;
25 #[macro_use]
26 extern crate tracing;
27
28 // N.B. these need `extern crate` even in 2018 edition
29 // because they're loaded implicitly from the sysroot.
30 // The reason they're loaded from the sysroot is because
31 // the rustdoc artifacts aren't stored in rustc's cargo target directory.
32 // So if `rustc` was specified in Cargo.toml, this would spuriously rebuild crates.
33 //
34 // Dependencies listed in Cargo.toml do not need `extern crate`.
35 extern crate rustc_ast;
36 extern crate rustc_ast_pretty;
37 extern crate rustc_attr;
38 extern crate rustc_data_structures;
39 extern crate rustc_driver;
40 extern crate rustc_errors;
41 extern crate rustc_expand;
42 extern crate rustc_feature;
43 extern crate rustc_hir;
44 extern crate rustc_hir_pretty;
45 extern crate rustc_index;
46 extern crate rustc_infer;
47 extern crate rustc_interface;
48 extern crate rustc_lexer;
49 extern crate rustc_lint;
50 extern crate rustc_metadata;
51 extern crate rustc_middle;
52 extern crate rustc_mir;
53 extern crate rustc_parse;
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 mod markdown;
91 mod passes;
92 mod theme;
93 mod visit_ast;
94 mod visit_lib;
95
96 pub fn main() {
97     rustc_driver::set_sigpipe_handler();
98     rustc_driver::install_ice_hook();
99     rustc_driver::init_env_logger("RUSTDOC_LOG");
100     let exit_code = rustc_driver::catch_with_exit_code(|| match get_args() {
101         Some(args) => main_args(&args),
102         _ => Err(ErrorReported),
103     });
104     process::exit(exit_code);
105 }
106
107 fn get_args() -> Option<Vec<String>> {
108     env::args_os()
109         .enumerate()
110         .map(|(i, arg)| {
111             arg.into_string()
112                 .map_err(|arg| {
113                     early_warn(
114                         ErrorOutputType::default(),
115                         &format!("Argument {} is not valid Unicode: {:?}", i, arg),
116                     );
117                 })
118                 .ok()
119         })
120         .collect()
121 }
122
123 fn opts() -> Vec<RustcOptGroup> {
124     let stable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::stable;
125     let unstable: fn(_, fn(&mut getopts::Options) -> &mut _) -> _ = RustcOptGroup::unstable;
126     vec![
127         stable("h", |o| o.optflag("h", "help", "show this help message")),
128         stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
129         stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
130         stable("r", |o| {
131             o.optopt("r", "input-format", "the input type of the specified file", "[rust]")
132         }),
133         stable("w", |o| o.optopt("w", "output-format", "the output type to write", "[html]")),
134         stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
135         stable("crate-name", |o| {
136             o.optopt("", "crate-name", "specify the name of this crate", "NAME")
137         }),
138         make_crate_type_option(),
139         stable("L", |o| {
140             o.optmulti("L", "library-path", "directory to add to crate search path", "DIR")
141         }),
142         stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
143         stable("extern", |o| o.optmulti("", "extern", "pass an --extern to rustc", "NAME[=PATH]")),
144         unstable("extern-html-root-url", |o| {
145             o.optmulti("", "extern-html-root-url", "base URL to use for dependencies", "NAME=URL")
146         }),
147         stable("plugin-path", |o| o.optmulti("", "plugin-path", "removed", "DIR")),
148         stable("C", |o| {
149             o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
150         }),
151         stable("passes", |o| {
152             o.optmulti(
153                 "",
154                 "passes",
155                 "list of passes to also run, you might want to pass it multiple times; a value of \
156                  `list` will print available passes",
157                 "PASSES",
158             )
159         }),
160         stable("plugins", |o| o.optmulti("", "plugins", "removed", "PLUGINS")),
161         stable("no-default", |o| o.optflag("", "no-defaults", "don't run the default passes")),
162         stable("document-private-items", |o| {
163             o.optflag("", "document-private-items", "document private items")
164         }),
165         unstable("document-hidden-items", |o| {
166             o.optflag("", "document-hidden-items", "document items that have doc(hidden)")
167         }),
168         stable("test", |o| o.optflag("", "test", "run code examples as tests")),
169         stable("test-args", |o| {
170             o.optmulti("", "test-args", "arguments to pass to the test runner", "ARGS")
171         }),
172         unstable("test-run-directory", |o| {
173             o.optopt(
174                 "",
175                 "test-run-directory",
176                 "The working directory in which to run tests",
177                 "PATH",
178             )
179         }),
180         stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
181         stable("markdown-css", |o| {
182             o.optmulti(
183                 "",
184                 "markdown-css",
185                 "CSS files to include via <link> in a rendered Markdown file",
186                 "FILES",
187             )
188         }),
189         stable("html-in-header", |o| {
190             o.optmulti(
191                 "",
192                 "html-in-header",
193                 "files to include inline in the <head> section of a rendered Markdown file \
194                  or generated documentation",
195                 "FILES",
196             )
197         }),
198         stable("html-before-content", |o| {
199             o.optmulti(
200                 "",
201                 "html-before-content",
202                 "files to include inline between <body> and the content of a rendered \
203                  Markdown file or generated documentation",
204                 "FILES",
205             )
206         }),
207         stable("html-after-content", |o| {
208             o.optmulti(
209                 "",
210                 "html-after-content",
211                 "files to include inline between the content and </body> of a rendered \
212                  Markdown file or generated documentation",
213                 "FILES",
214             )
215         }),
216         unstable("markdown-before-content", |o| {
217             o.optmulti(
218                 "",
219                 "markdown-before-content",
220                 "files to include inline between <body> and the content of a rendered \
221                  Markdown file or generated documentation",
222                 "FILES",
223             )
224         }),
225         unstable("markdown-after-content", |o| {
226             o.optmulti(
227                 "",
228                 "markdown-after-content",
229                 "files to include inline between the content and </body> of a rendered \
230                  Markdown file or generated documentation",
231                 "FILES",
232             )
233         }),
234         stable("markdown-playground-url", |o| {
235             o.optopt("", "markdown-playground-url", "URL to send code snippets to", "URL")
236         }),
237         stable("markdown-no-toc", |o| {
238             o.optflag("", "markdown-no-toc", "don't include table of contents")
239         }),
240         stable("e", |o| {
241             o.optopt(
242                 "e",
243                 "extend-css",
244                 "To add some CSS rules with a given file to generate doc with your \
245                  own theme. However, your theme might break if the rustdoc's generated HTML \
246                  changes, so be careful!",
247                 "PATH",
248             )
249         }),
250         unstable("Z", |o| {
251             o.optmulti("Z", "", "internal and debugging options (only on nightly build)", "FLAG")
252         }),
253         stable("sysroot", |o| o.optopt("", "sysroot", "Override the system root", "PATH")),
254         unstable("playground-url", |o| {
255             o.optopt(
256                 "",
257                 "playground-url",
258                 "URL to send code snippets to, may be reset by --markdown-playground-url \
259                  or `#![doc(html_playground_url=...)]`",
260                 "URL",
261             )
262         }),
263         unstable("display-warnings", |o| {
264             o.optflag("", "display-warnings", "to print code warnings when testing doc")
265         }),
266         stable("crate-version", |o| {
267             o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
268         }),
269         unstable("sort-modules-by-appearance", |o| {
270             o.optflag(
271                 "",
272                 "sort-modules-by-appearance",
273                 "sort modules by where they appear in the program, rather than alphabetically",
274             )
275         }),
276         stable("default-theme", |o| {
277             o.optopt(
278                 "",
279                 "default-theme",
280                 "Set the default theme. THEME should be the theme name, generally lowercase. \
281                  If an unknown default theme is specified, the builtin default is used. \
282                  The set of themes, and the rustdoc built-in default, are not stable.",
283                 "THEME",
284             )
285         }),
286         unstable("default-setting", |o| {
287             o.optmulti(
288                 "",
289                 "default-setting",
290                 "Default value for a rustdoc setting (used when \"rustdoc-SETTING\" is absent \
291                  from web browser Local Storage). If VALUE is not supplied, \"true\" is used. \
292                  Supported SETTINGs and VALUEs are not documented and not stable.",
293                 "SETTING[=VALUE]",
294             )
295         }),
296         stable("theme", |o| {
297             o.optmulti(
298                 "",
299                 "theme",
300                 "additional themes which will be added to the generated docs",
301                 "FILES",
302             )
303         }),
304         stable("check-theme", |o| {
305             o.optmulti("", "check-theme", "check if given theme is valid", "FILES")
306         }),
307         unstable("resource-suffix", |o| {
308             o.optopt(
309                 "",
310                 "resource-suffix",
311                 "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
312                  \"light-suffix.css\"",
313                 "PATH",
314             )
315         }),
316         stable("edition", |o| {
317             o.optopt(
318                 "",
319                 "edition",
320                 "edition to use when compiling rust code (default: 2015)",
321                 "EDITION",
322             )
323         }),
324         stable("color", |o| {
325             o.optopt(
326                 "",
327                 "color",
328                 "Configure coloring of output:
329                                           auto   = colorize, if output goes to a tty (default);
330                                           always = always colorize output;
331                                           never  = never colorize output",
332                 "auto|always|never",
333             )
334         }),
335         stable("error-format", |o| {
336             o.optopt(
337                 "",
338                 "error-format",
339                 "How errors and other messages are produced",
340                 "human|json|short",
341             )
342         }),
343         stable("json", |o| {
344             o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
345         }),
346         unstable("disable-minification", |o| {
347             o.optflag("", "disable-minification", "Disable minification applied on JS files")
348         }),
349         stable("warn", |o| o.optmulti("W", "warn", "Set lint warnings", "OPT")),
350         stable("allow", |o| o.optmulti("A", "allow", "Set lint allowed", "OPT")),
351         stable("deny", |o| o.optmulti("D", "deny", "Set lint denied", "OPT")),
352         stable("forbid", |o| o.optmulti("F", "forbid", "Set lint forbidden", "OPT")),
353         stable("cap-lints", |o| {
354             o.optmulti(
355                 "",
356                 "cap-lints",
357                 "Set the most restrictive lint level. \
358                  More restrictive lints are capped at this \
359                  level. By default, it is at `forbid` level.",
360                 "LEVEL",
361             )
362         }),
363         unstable("index-page", |o| {
364             o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
365         }),
366         unstable("enable-index-page", |o| {
367             o.optflag("", "enable-index-page", "To enable generation of the index page")
368         }),
369         unstable("static-root-path", |o| {
370             o.optopt(
371                 "",
372                 "static-root-path",
373                 "Path string to force loading static files from in output pages. \
374                  If not set, uses combinations of '../' to reach the documentation root.",
375                 "PATH",
376             )
377         }),
378         unstable("disable-per-crate-search", |o| {
379             o.optflag(
380                 "",
381                 "disable-per-crate-search",
382                 "disables generating the crate selector on the search box",
383             )
384         }),
385         unstable("persist-doctests", |o| {
386             o.optopt(
387                 "",
388                 "persist-doctests",
389                 "Directory to persist doctest executables into",
390                 "PATH",
391             )
392         }),
393         unstable("show-coverage", |o| {
394             o.optflag(
395                 "",
396                 "show-coverage",
397                 "calculate percentage of public items with documentation",
398             )
399         }),
400         unstable("enable-per-target-ignores", |o| {
401             o.optflag(
402                 "",
403                 "enable-per-target-ignores",
404                 "parse ignore-foo for ignoring doctests on a per-target basis",
405             )
406         }),
407         unstable("runtool", |o| {
408             o.optopt(
409                 "",
410                 "runtool",
411                 "",
412                 "The tool to run tests with when building for a different target than host",
413             )
414         }),
415         unstable("runtool-arg", |o| {
416             o.optmulti(
417                 "",
418                 "runtool-arg",
419                 "",
420                 "One (of possibly many) arguments to pass to the runtool",
421             )
422         }),
423         unstable("test-builder", |o| {
424             o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH")
425         }),
426         unstable("check", |o| o.optflag("", "check", "Run rustdoc checks")),
427     ]
428 }
429
430 fn usage(argv0: &str) {
431     let mut options = getopts::Options::new();
432     for option in opts() {
433         (option.apply)(&mut options);
434     }
435     println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
436     println!("More information available at https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html")
437 }
438
439 /// A result type used by several functions under `main()`.
440 type MainResult = Result<(), ErrorReported>;
441
442 fn main_args(args: &[String]) -> MainResult {
443     let mut options = getopts::Options::new();
444     for option in opts() {
445         (option.apply)(&mut options);
446     }
447     let matches = match options.parse(&args[1..]) {
448         Ok(m) => m,
449         Err(err) => {
450             early_error(ErrorOutputType::default(), &err.to_string());
451         }
452     };
453
454     // Note that we discard any distinction between different non-zero exit
455     // codes from `from_matches` here.
456     let options = match config::Options::from_matches(&matches) {
457         Ok(opts) => opts,
458         Err(code) => return if code == 0 { Ok(()) } else { Err(ErrorReported) },
459     };
460     rustc_interface::util::setup_callbacks_and_run_in_thread_pool_with_globals(
461         options.edition,
462         1, // this runs single-threaded, even in a parallel compiler
463         &None,
464         move || main_options(options),
465     )
466 }
467
468 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
469     match res {
470         Ok(()) => Ok(()),
471         Err(err) => {
472             diag.struct_err(&err).emit();
473             Err(ErrorReported)
474         }
475     }
476 }
477
478 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
479     krate: clean::Crate,
480     renderopts: config::RenderOptions,
481     render_info: config::RenderInfo,
482     diag: &rustc_errors::Handler,
483     edition: rustc_span::edition::Edition,
484     tcx: TyCtxt<'tcx>,
485 ) -> MainResult {
486     match formats::run_format::<T>(krate, renderopts, render_info, &diag, edition, tcx) {
487         Ok(_) => Ok(()),
488         Err(e) => {
489             let mut msg = diag.struct_err(&format!("couldn't generate documentation: {}", e.error));
490             let file = e.file.display().to_string();
491             if file.is_empty() {
492                 msg.emit()
493             } else {
494                 msg.note(&format!("failed to create or modify \"{}\"", file)).emit()
495             }
496             Err(ErrorReported)
497         }
498     }
499 }
500
501 fn main_options(options: config::Options) -> MainResult {
502     let diag = core::new_handler(options.error_format, None, &options.debugging_opts);
503
504     match (options.should_test, options.markdown_input()) {
505         (true, true) => return wrap_return(&diag, markdown::test(options)),
506         (true, false) => return doctest::run(options),
507         (false, true) => {
508             return wrap_return(
509                 &diag,
510                 markdown::render(&options.input, options.render_options, options.edition),
511             );
512         }
513         (false, false) => {}
514     }
515
516     // need to move these items separately because we lose them by the time the closure is called,
517     // but we can't create the Handler ahead of time because it's not Send
518     let diag_opts = (options.error_format, options.edition, options.debugging_opts.clone());
519     let show_coverage = options.show_coverage;
520     let run_check = options.run_check;
521
522     // First, parse the crate and extract all relevant information.
523     info!("starting to run rustc");
524
525     // Interpret the input file as a rust source file, passing it through the
526     // compiler all the way through the analysis passes. The rustdoc output is
527     // then generated from the cleaned AST of the crate. This runs all the
528     // plug/cleaning passes.
529     let crate_version = options.crate_version.clone();
530
531     let default_passes = options.default_passes;
532     let output_format = options.output_format;
533     // FIXME: fix this clone (especially render_options)
534     let externs = options.externs.clone();
535     let manual_passes = options.manual_passes.clone();
536     let render_options = options.render_options.clone();
537     let config = core::create_config(options);
538
539     interface::create_compiler_and_run(config, |compiler| {
540         compiler.enter(|queries| {
541             let sess = compiler.session();
542
543             // We need to hold on to the complete resolver, so we cause everything to be
544             // cloned for the analysis passes to use. Suboptimal, but necessary in the
545             // current architecture.
546             let resolver = core::create_resolver(externs, queries, &sess);
547
548             if sess.has_errors() {
549                 sess.fatal("Compilation failed, aborting rustdoc");
550             }
551
552             let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).peek_mut();
553
554             global_ctxt.enter(|tcx| {
555                 let (mut krate, render_info, render_opts) = sess.time("run_global_ctxt", || {
556                     core::run_global_ctxt(
557                         tcx,
558                         resolver,
559                         default_passes,
560                         manual_passes,
561                         render_options,
562                         output_format,
563                     )
564                 });
565                 info!("finished with rustc");
566
567                 krate.version = crate_version;
568
569                 if show_coverage {
570                     // if we ran coverage, bail early, we don't need to also generate docs at this point
571                     // (also we didn't load in any of the useful passes)
572                     return Ok(());
573                 } else if run_check {
574                     // Since we're in "check" mode, no need to generate anything beyond this point.
575                     return Ok(());
576                 }
577
578                 info!("going to format");
579                 let (error_format, edition, debugging_options) = diag_opts;
580                 let diag = core::new_handler(error_format, None, &debugging_options);
581                 match output_format {
582                     config::OutputFormat::Html => sess.time("render_html", || {
583                         run_renderer::<html::render::Context<'_>>(
584                             krate,
585                             render_opts,
586                             render_info,
587                             &diag,
588                             edition,
589                             tcx,
590                         )
591                     }),
592                     config::OutputFormat::Json => sess.time("render_json", || {
593                         run_renderer::<json::JsonRenderer<'_>>(
594                             krate,
595                             render_opts,
596                             render_info,
597                             &diag,
598                             edition,
599                             tcx,
600                         )
601                     }),
602                 }
603             })
604         })
605     })
606 }