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