]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Remove many RefCells from DocContext
[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(test)]
13 #![feature(crate_visibility_modifier)]
14 #![feature(never_type)]
15 #![feature(once_cell)]
16 #![feature(type_ascription)]
17 #![feature(str_split_once)]
18 #![feature(iter_intersperse)]
19 #![recursion_limit = "256"]
20 #![deny(rustc::internal)]
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::TyCtxt;
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 mod formats;
86 // used by the error-index generator, so it needs to be public
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!("    @path               Read newline separated options from `path`\n");
436     println!("More information available at https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html")
437 }
438
439 /// A result type used by several functions under `main()`.
440 type MainResult = Result<(), ErrorReported>;
441
442 fn main_args(at_args: &[String]) -> MainResult {
443     let args = rustc_driver::args::arg_expand_all(at_args);
444
445     let mut options = getopts::Options::new();
446     for option in opts() {
447         (option.apply)(&mut options);
448     }
449     let matches = match options.parse(&args[1..]) {
450         Ok(m) => m,
451         Err(err) => {
452             early_error(ErrorOutputType::default(), &err.to_string());
453         }
454     };
455
456     // Note that we discard any distinction between different non-zero exit
457     // codes from `from_matches` here.
458     let options = match config::Options::from_matches(&matches) {
459         Ok(opts) => opts,
460         Err(code) => return if code == 0 { Ok(()) } else { Err(ErrorReported) },
461     };
462     rustc_interface::util::setup_callbacks_and_run_in_thread_pool_with_globals(
463         options.edition,
464         1, // this runs single-threaded, even in a parallel compiler
465         &None,
466         move || main_options(options),
467     )
468 }
469
470 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> MainResult {
471     match res {
472         Ok(()) => Ok(()),
473         Err(err) => {
474             diag.struct_err(&err).emit();
475             Err(ErrorReported)
476         }
477     }
478 }
479
480 fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
481     krate: clean::Crate,
482     renderopts: config::RenderOptions,
483     render_info: config::RenderInfo,
484     diag: &rustc_errors::Handler,
485     edition: rustc_span::edition::Edition,
486     tcx: TyCtxt<'tcx>,
487 ) -> MainResult {
488     match formats::run_format::<T>(krate, renderopts, render_info, &diag, edition, tcx) {
489         Ok(_) => Ok(()),
490         Err(e) => {
491             let mut msg = diag.struct_err(&format!("couldn't generate documentation: {}", e.error));
492             let file = e.file.display().to_string();
493             if file.is_empty() {
494                 msg.emit()
495             } else {
496                 msg.note(&format!("failed to create or modify \"{}\"", file)).emit()
497             }
498             Err(ErrorReported)
499         }
500     }
501 }
502
503 fn main_options(options: config::Options) -> MainResult {
504     let diag = core::new_handler(options.error_format, None, &options.debugging_opts);
505
506     match (options.should_test, options.markdown_input()) {
507         (true, true) => return wrap_return(&diag, markdown::test(options)),
508         (true, false) => return doctest::run(options),
509         (false, true) => {
510             return wrap_return(
511                 &diag,
512                 markdown::render(&options.input, options.render_options, options.edition),
513             );
514         }
515         (false, false) => {}
516     }
517
518     // need to move these items separately because we lose them by the time the closure is called,
519     // but we can't create the Handler ahead of time because it's not Send
520     let diag_opts = (options.error_format, options.edition, options.debugging_opts.clone());
521     let show_coverage = options.show_coverage;
522     let run_check = options.run_check;
523
524     // First, parse the crate and extract all relevant information.
525     info!("starting to run rustc");
526
527     // Interpret the input file as a rust source file, passing it through the
528     // compiler all the way through the analysis passes. The rustdoc output is
529     // then generated from the cleaned AST of the crate. This runs all the
530     // plug/cleaning passes.
531     let crate_version = options.crate_version.clone();
532
533     let default_passes = options.default_passes;
534     let output_format = options.output_format;
535     // FIXME: fix this clone (especially render_options)
536     let externs = options.externs.clone();
537     let manual_passes = options.manual_passes.clone();
538     let render_options = options.render_options.clone();
539     let config = core::create_config(options);
540
541     interface::create_compiler_and_run(config, |compiler| {
542         compiler.enter(|queries| {
543             let sess = compiler.session();
544
545             // We need to hold on to the complete resolver, so we cause everything to be
546             // cloned for the analysis passes to use. Suboptimal, but necessary in the
547             // current architecture.
548             let resolver = core::create_resolver(externs, queries, &sess);
549
550             if sess.has_errors() {
551                 sess.fatal("Compilation failed, aborting rustdoc");
552             }
553
554             let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).peek_mut();
555
556             global_ctxt.enter(|tcx| {
557                 let (mut krate, render_info, render_opts) = sess.time("run_global_ctxt", || {
558                     core::run_global_ctxt(
559                         tcx,
560                         resolver,
561                         default_passes,
562                         manual_passes,
563                         render_options,
564                         output_format,
565                     )
566                 });
567                 info!("finished with rustc");
568
569                 krate.version = crate_version;
570
571                 if show_coverage {
572                     // if we ran coverage, bail early, we don't need to also generate docs at this point
573                     // (also we didn't load in any of the useful passes)
574                     return Ok(());
575                 } else if run_check {
576                     // Since we're in "check" mode, no need to generate anything beyond this point.
577                     return Ok(());
578                 }
579
580                 info!("going to format");
581                 let (error_format, edition, debugging_options) = diag_opts;
582                 let diag = core::new_handler(error_format, None, &debugging_options);
583                 match output_format {
584                     config::OutputFormat::Html => sess.time("render_html", || {
585                         run_renderer::<html::render::Context<'_>>(
586                             krate,
587                             render_opts,
588                             render_info,
589                             &diag,
590                             edition,
591                             tcx,
592                         )
593                     }),
594                     config::OutputFormat::Json => sess.time("render_json", || {
595                         run_renderer::<json::JsonRenderer<'_>>(
596                             krate,
597                             render_opts,
598                             render_info,
599                             &diag,
600                             edition,
601                             tcx,
602                         )
603                     }),
604                 }
605             })
606         })
607     })
608 }