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