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