]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Rollup merge of #61310 - RalfJung:mem, r=Centril
[rust.git] / src / librustdoc / lib.rs
1 #![deny(rust_2018_idioms)]
2 #![deny(internal)]
3
4 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
5        html_playground_url = "https://play.rust-lang.org/")]
6
7 #![feature(bind_by_move_pattern_guards)]
8 #![feature(rustc_private)]
9 #![feature(arbitrary_self_types)]
10 #![feature(box_patterns)]
11 #![feature(box_syntax)]
12 #![feature(in_band_lifetimes)]
13 #![feature(nll)]
14 #![feature(set_stdio)]
15 #![feature(test)]
16 #![feature(vec_remove_item)]
17 #![feature(ptr_offset_from)]
18 #![feature(crate_visibility_modifier)]
19 #![feature(const_fn)]
20 #![feature(drain_filter)]
21 #![feature(inner_deref)]
22 #![feature(never_type)]
23
24 #![recursion_limit="256"]
25
26 extern crate getopts;
27 extern crate env_logger;
28 extern crate rustc;
29 extern crate rustc_data_structures;
30 extern crate rustc_driver;
31 extern crate rustc_resolve;
32 extern crate rustc_lint;
33 extern crate rustc_interface;
34 extern crate rustc_metadata;
35 extern crate rustc_target;
36 extern crate rustc_typeck;
37 extern crate serialize;
38 extern crate syntax;
39 extern crate syntax_pos;
40 extern crate test as testing;
41 #[macro_use] extern crate log;
42 extern crate rustc_errors as errors;
43
44 extern crate serialize as rustc_serialize; // used by deriving
45
46 use std::default::Default;
47 use std::env;
48 use std::panic;
49 use std::process;
50 use std::sync::mpsc::channel;
51
52 use rustc::session::{early_warn, early_error};
53 use rustc::session::config::{ErrorOutputType, RustcOptGroup};
54
55 #[macro_use]
56 mod externalfiles;
57
58 mod clean;
59 mod config;
60 mod core;
61 mod doctree;
62 mod fold;
63 pub mod html {
64     crate mod highlight;
65     crate mod escape;
66     crate mod item_type;
67     crate mod format;
68     crate mod layout;
69     pub mod markdown;
70     crate mod render;
71     crate mod static_files;
72     crate mod toc;
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     passes: Vec<String>,
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();
96     let res = std::thread::Builder::new().stack_size(thread_stack_size).spawn(move || {
97         get_args().map(|args| main_args(&args)).unwrap_or(1)
98     }).unwrap().join().unwrap_or(rustc_driver::EXIT_FAILURE);
99     process::exit(res);
100 }
101
102 fn get_args() -> Option<Vec<String>> {
103     env::args_os().enumerate()
104         .map(|(i, arg)| arg.into_string().map_err(|arg| {
105              early_warn(ErrorOutputType::default(),
106                         &format!("Argument {} is not valid Unicode: {:?}", i, arg));
107         }).ok())
108         .collect()
109 }
110
111 fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
112     where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
113 {
114     RustcOptGroup::stable(name, f)
115 }
116
117 fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
118     where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
119 {
120     RustcOptGroup::unstable(name, f)
121 }
122
123 fn opts() -> Vec<RustcOptGroup> {
124     vec![
125         stable("h", |o| o.optflag("h", "help", "show this help message")),
126         stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
127         stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
128         stable("r", |o| {
129             o.optopt("r", "input-format", "the input type of the specified file",
130                      "[rust]")
131         }),
132         stable("w", |o| {
133             o.optopt("w", "output-format", "the output type to write", "[html]")
134         }),
135         stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
136         stable("crate-name", |o| {
137             o.optopt("", "crate-name", "specify the name of this crate", "NAME")
138         }),
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("linker", |o| {
248             o.optopt("", "linker", "linker used for building executable test code", "PATH")
249         }),
250         unstable("sort-modules-by-appearance", |o| {
251             o.optflag("", "sort-modules-by-appearance", "sort modules by where they appear in the \
252                                                          program, rather than alphabetically")
253         }),
254         unstable("themes", |o| {
255             o.optmulti("", "themes",
256                        "additional themes which will be added to the generated docs",
257                        "FILES")
258         }),
259         unstable("theme-checker", |o| {
260             o.optmulti("", "theme-checker",
261                        "check if given theme is valid",
262                        "FILES")
263         }),
264         unstable("resource-suffix", |o| {
265             o.optopt("",
266                      "resource-suffix",
267                      "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
268                       \"light-suffix.css\"",
269                      "PATH")
270         }),
271         stable("edition", |o| {
272             o.optopt("", "edition",
273                      "edition to use when compiling rust code (default: 2015)",
274                      "EDITION")
275         }),
276         stable("color", |o| {
277             o.optopt("",
278                      "color",
279                      "Configure coloring of output:
280                                           auto   = colorize, if output goes to a tty (default);
281                                           always = always colorize output;
282                                           never  = never colorize output",
283                      "auto|always|never")
284         }),
285         stable("error-format", |o| {
286             o.optopt("",
287                      "error-format",
288                      "How errors and other messages are produced",
289                      "human|json|short")
290         }),
291         unstable("disable-minification", |o| {
292              o.optflag("",
293                        "disable-minification",
294                        "Disable minification applied on JS files")
295         }),
296         stable("warn", |o| {
297             o.optmulti("W", "warn", "Set lint warnings", "OPT")
298         }),
299         stable("allow", |o| {
300             o.optmulti("A", "allow", "Set lint allowed", "OPT")
301         }),
302         stable("deny", |o| {
303             o.optmulti("D", "deny", "Set lint denied", "OPT")
304         }),
305         stable("forbid", |o| {
306             o.optmulti("F", "forbid", "Set lint forbidden", "OPT")
307         }),
308         stable("cap-lints", |o| {
309             o.optmulti(
310                 "",
311                 "cap-lints",
312                 "Set the most restrictive lint level. \
313                  More restrictive lints are capped at this \
314                  level. By default, it is at `forbid` level.",
315                 "LEVEL",
316             )
317         }),
318         unstable("index-page", |o| {
319              o.optopt("",
320                       "index-page",
321                       "Markdown file to be used as index page",
322                       "PATH")
323         }),
324         unstable("enable-index-page", |o| {
325              o.optflag("",
326                        "enable-index-page",
327                        "To enable generation of the index page")
328         }),
329         unstable("static-root-path", |o| {
330             o.optopt("",
331                      "static-root-path",
332                      "Path string to force loading static files from in output pages. \
333                       If not set, uses combinations of '../' to reach the documentation root.",
334                      "PATH")
335         }),
336         unstable("disable-per-crate-search", |o| {
337             o.optflag("",
338                       "disable-per-crate-search",
339                       "disables generating the crate selector on the search box")
340         }),
341         unstable("persist-doctests", |o| {
342              o.optopt("",
343                        "persist-doctests",
344                        "Directory to persist doctest executables into",
345                        "PATH")
346         }),
347         unstable("generate-redirect-pages", |o| {
348             o.optflag("",
349                       "generate-redirect-pages",
350                       "Generate extra pages to support legacy URLs and tool links")
351         }),
352         unstable("show-coverage", |o| {
353             o.optflag("",
354                       "show-coverage",
355                       "calculate percentage of public items with documentation")
356         }),
357     ]
358 }
359
360 fn usage(argv0: &str) {
361     let mut options = getopts::Options::new();
362     for option in opts() {
363         (option.apply)(&mut options);
364     }
365     println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
366 }
367
368 fn main_args(args: &[String]) -> i32 {
369     let mut options = getopts::Options::new();
370     for option in opts() {
371         (option.apply)(&mut options);
372     }
373     let matches = match options.parse(&args[1..]) {
374         Ok(m) => m,
375         Err(err) => {
376             early_error(ErrorOutputType::default(), &err.to_string());
377         }
378     };
379     let options = match config::Options::from_matches(&matches) {
380         Ok(opts) => opts,
381         Err(code) => return code,
382     };
383     rustc_interface::interface::default_thread_pool(options.edition, move || {
384         main_options(options)
385     })
386 }
387
388 fn main_options(options: config::Options) -> i32 {
389     let diag = core::new_handler(options.error_format,
390                                  None,
391                                  options.debugging_options.treat_err_as_bug,
392                                  options.debugging_options.ui_testing);
393
394     match (options.should_test, options.markdown_input()) {
395         (true, true) => return markdown::test(options, &diag),
396         (true, false) => return test::run(options),
397         (false, true) => return markdown::render(options.input,
398                                                  options.render_options,
399                                                  &diag,
400                                                  options.edition),
401         (false, false) => {}
402     }
403
404     // need to move these items separately because we lose them by the time the closure is called,
405     // but we can't crates the Handler ahead of time because it's not Send
406     let diag_opts = (options.error_format,
407                      options.debugging_options.treat_err_as_bug,
408                      options.debugging_options.ui_testing,
409                      options.edition);
410     let show_coverage = options.show_coverage;
411     rust_input(options, move |out| {
412         if show_coverage {
413             // if we ran coverage, bail early, we don't need to also generate docs at this point
414             // (also we didn't load in any of the useful passes)
415             return rustc_driver::EXIT_SUCCESS;
416         }
417
418         let Output { krate, passes, renderinfo, renderopts } = out;
419         info!("going to format");
420         let (error_format, treat_err_as_bug, ui_testing, edition) = diag_opts;
421         let diag = core::new_handler(error_format, None, treat_err_as_bug, ui_testing);
422         match html::render::run(
423             krate,
424             renderopts,
425             passes.into_iter().collect(),
426             renderinfo,
427             &diag,
428             edition,
429         ) {
430             Ok(_) => rustc_driver::EXIT_SUCCESS,
431             Err(e) => {
432                 diag.struct_err(&format!("couldn't generate documentation: {}", e.error))
433                     .note(&format!("failed to create or modify \"{}\"", e.file.display()))
434                     .emit();
435                 rustc_driver::EXIT_FAILURE
436             }
437         }
438     })
439 }
440
441 /// Interprets the input file as a rust source file, passing it through the
442 /// compiler all the way through the analysis passes. The rustdoc output is then
443 /// generated from the cleaned AST of the crate.
444 ///
445 /// This form of input will run all of the plug/cleaning passes
446 fn rust_input<R, F>(options: config::Options, f: F) -> R
447 where R: 'static + Send,
448       F: 'static + Send + FnOnce(Output) -> R
449 {
450     // First, parse the crate and extract all relevant information.
451     info!("starting to run rustc");
452
453     let (tx, rx) = channel();
454
455     let result = rustc_driver::report_ices_to_stderr_if_any(move || {
456         let crate_name = options.crate_name.clone();
457         let crate_version = options.crate_version.clone();
458         let (mut krate, renderinfo, renderopts, passes) = core::run_core(options);
459
460         info!("finished with rustc");
461
462         if let Some(name) = crate_name {
463             krate.name = name
464         }
465
466         krate.version = crate_version;
467
468         tx.send(f(Output {
469             krate: krate,
470             renderinfo: renderinfo,
471             renderopts,
472             passes: passes
473         })).unwrap();
474     });
475
476     match result {
477         Ok(()) => rx.recv().unwrap(),
478         Err(_) => panic::resume_unwind(Box::new(errors::FatalErrorMarker)),
479     }
480 }