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