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