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