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