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