]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Rollup merge of #66834 - infinity0:master, r=Mark-Simulacrum
[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 #![cfg_attr(bootstrap, 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 serialize;
39 extern crate syntax;
40 extern crate syntax_expand;
41 extern crate syntax_pos;
42 extern crate test as testing;
43 #[macro_use] extern crate log;
44 extern crate rustc_errors as errors;
45
46 use std::default::Default;
47 use std::env;
48 use std::panic;
49 use std::process;
50
51 use rustc::session::{early_warn, early_error};
52 use rustc::session::config::{ErrorOutputType, RustcOptGroup, make_crate_type_option};
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 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     crate mod sources;
74 }
75 mod markdown;
76 mod passes;
77 mod visit_ast;
78 mod visit_lib;
79 mod test;
80 mod theme;
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().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         make_crate_type_option(),
140         stable("L", |o| {
141             o.optmulti("L", "library-path", "directory to add to crate search path",
142                        "DIR")
143         }),
144         stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
145         stable("extern", |o| {
146             o.optmulti("", "extern", "pass an --extern to rustc", "NAME[=PATH]")
147         }),
148         unstable("extern-private", |o| {
149             o.optmulti("", "extern-private",
150                        "pass an --extern to rustc (compatibility only)", "NAME=PATH")
151         }),
152         unstable("extern-html-root-url", |o| {
153             o.optmulti("", "extern-html-root-url",
154                        "base URL to use for dependencies", "NAME=URL")
155         }),
156         stable("plugin-path", |o| {
157             o.optmulti("", "plugin-path", "removed", "DIR")
158         }),
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("", "passes",
164                        "list of passes to also run, you might want \
165                         to pass it multiple times; a value of `list` \
166                         will print available passes",
167                        "PASSES")
168         }),
169         stable("plugins", |o| {
170             o.optmulti("", "plugins", "removed",
171                        "PLUGINS")
172         }),
173         stable("no-default", |o| {
174             o.optflag("", "no-defaults", "don't run the default passes")
175         }),
176         stable("document-private-items", |o| {
177             o.optflag("", "document-private-items", "document private items")
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",
182                        "ARGS")
183         }),
184         stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
185         stable("markdown-css", |o| {
186             o.optmulti("", "markdown-css",
187                        "CSS files to include via <link> in a rendered Markdown file",
188                        "FILES")
189         }),
190         stable("html-in-header", |o|  {
191             o.optmulti("", "html-in-header",
192                        "files to include inline in the <head> section of a rendered Markdown file \
193                         or generated documentation",
194                        "FILES")
195         }),
196         stable("html-before-content", |o| {
197             o.optmulti("", "html-before-content",
198                        "files to include inline between <body> and the content of a rendered \
199                         Markdown file or generated documentation",
200                        "FILES")
201         }),
202         stable("html-after-content", |o| {
203             o.optmulti("", "html-after-content",
204                        "files to include inline between the content and </body> of a rendered \
205                         Markdown file or generated documentation",
206                        "FILES")
207         }),
208         unstable("markdown-before-content", |o| {
209             o.optmulti("", "markdown-before-content",
210                        "files to include inline between <body> and the content of a rendered \
211                         Markdown file or generated documentation",
212                        "FILES")
213         }),
214         unstable("markdown-after-content", |o| {
215             o.optmulti("", "markdown-after-content",
216                        "files to include inline between the content and </body> of a rendered \
217                         Markdown file or generated documentation",
218                        "FILES")
219         }),
220         stable("markdown-playground-url", |o| {
221             o.optopt("", "markdown-playground-url",
222                      "URL to send code snippets to", "URL")
223         }),
224         stable("markdown-no-toc", |o| {
225             o.optflag("", "markdown-no-toc", "don't include table of contents")
226         }),
227         stable("e", |o| {
228             o.optopt("e", "extend-css",
229                      "To add some CSS rules with a given file to generate doc with your \
230                       own theme. However, your theme might break if the rustdoc's generated HTML \
231                       changes, so be careful!", "PATH")
232         }),
233         unstable("Z", |o| {
234             o.optmulti("Z", "",
235                        "internal and debugging options (only on nightly build)", "FLAG")
236         }),
237         stable("sysroot", |o| {
238             o.optopt("", "sysroot", "Override the system root", "PATH")
239         }),
240         unstable("playground-url", |o| {
241             o.optopt("", "playground-url",
242                      "URL to send code snippets to, may be reset by --markdown-playground-url \
243                       or `#![doc(html_playground_url=...)]`",
244                      "URL")
245         }),
246         unstable("display-warnings", |o| {
247             o.optflag("", "display-warnings", "to print code warnings when testing doc")
248         }),
249         unstable("crate-version", |o| {
250             o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
251         }),
252         unstable("sort-modules-by-appearance", |o| {
253             o.optflag("", "sort-modules-by-appearance", "sort modules by where they appear in the \
254                                                          program, rather than alphabetically")
255         }),
256         stable("theme", |o| {
257             o.optmulti("", "theme",
258                        "additional themes which will be added to the generated docs",
259                        "FILES")
260         }),
261         stable("check-theme", |o| {
262             o.optmulti("", "check-theme",
263                        "check if given theme is valid",
264                        "FILES")
265         }),
266         unstable("resource-suffix", |o| {
267             o.optopt("",
268                      "resource-suffix",
269                      "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
270                       \"light-suffix.css\"",
271                      "PATH")
272         }),
273         stable("edition", |o| {
274             o.optopt("", "edition",
275                      "edition to use when compiling rust code (default: 2015)",
276                      "EDITION")
277         }),
278         stable("color", |o| {
279             o.optopt("",
280                      "color",
281                      "Configure coloring of output:
282                                           auto   = colorize, if output goes to a tty (default);
283                                           always = always colorize output;
284                                           never  = never colorize output",
285                      "auto|always|never")
286         }),
287         stable("error-format", |o| {
288             o.optopt("",
289                      "error-format",
290                      "How errors and other messages are produced",
291                      "human|json|short")
292         }),
293         stable("json", |o| {
294             o.optopt("",
295                      "json",
296                      "Configure the structure of JSON diagnostics",
297                      "CONFIG")
298         }),
299         unstable("disable-minification", |o| {
300              o.optflag("",
301                        "disable-minification",
302                        "Disable minification applied on JS files")
303         }),
304         stable("warn", |o| {
305             o.optmulti("W", "warn", "Set lint warnings", "OPT")
306         }),
307         stable("allow", |o| {
308             o.optmulti("A", "allow", "Set lint allowed", "OPT")
309         }),
310         stable("deny", |o| {
311             o.optmulti("D", "deny", "Set lint denied", "OPT")
312         }),
313         stable("forbid", |o| {
314             o.optmulti("F", "forbid", "Set lint forbidden", "OPT")
315         }),
316         stable("cap-lints", |o| {
317             o.optmulti(
318                 "",
319                 "cap-lints",
320                 "Set the most restrictive lint level. \
321                  More restrictive lints are capped at this \
322                  level. By default, it is at `forbid` level.",
323                 "LEVEL",
324             )
325         }),
326         unstable("index-page", |o| {
327              o.optopt("",
328                       "index-page",
329                       "Markdown file to be used as index page",
330                       "PATH")
331         }),
332         unstable("enable-index-page", |o| {
333              o.optflag("",
334                        "enable-index-page",
335                        "To enable generation of the index page")
336         }),
337         unstable("static-root-path", |o| {
338             o.optopt("",
339                      "static-root-path",
340                      "Path string to force loading static files from in output pages. \
341                       If not set, uses combinations of '../' to reach the documentation root.",
342                      "PATH")
343         }),
344         unstable("disable-per-crate-search", |o| {
345             o.optflag("",
346                       "disable-per-crate-search",
347                       "disables generating the crate selector on the search box")
348         }),
349         unstable("persist-doctests", |o| {
350              o.optopt("",
351                        "persist-doctests",
352                        "Directory to persist doctest executables into",
353                        "PATH")
354         }),
355         unstable("generate-redirect-pages", |o| {
356             o.optflag("",
357                       "generate-redirect-pages",
358                       "Generate extra pages to support legacy URLs and tool links")
359         }),
360         unstable("show-coverage", |o| {
361             o.optflag("",
362                       "show-coverage",
363                       "calculate percentage of public items with documentation")
364         }),
365         unstable("enable-per-target-ignores", |o| {
366             o.optflag("",
367                       "enable-per-target-ignores",
368                       "parse ignore-foo for ignoring doctests on a per-target basis")
369         }),
370         unstable("runtool", |o| {
371             o.optopt("",
372                      "runtool",
373                      "",
374                      "The tool to run tests with when building for a different target than host")
375         }),
376         unstable("runtool-arg", |o| {
377             o.optmulti("",
378                        "runtool-arg",
379                        "",
380                        "One (of possibly many) arguments to pass to the runtool")
381         }),
382         unstable("test-builder", |o| {
383             o.optflag("",
384                       "test-builder",
385                       "specified the rustc-like binary to use as the test builder")
386         }),
387     ]
388 }
389
390 fn usage(argv0: &str) {
391     let mut options = getopts::Options::new();
392     for option in opts() {
393         (option.apply)(&mut options);
394     }
395     println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
396 }
397
398 fn main_args(args: &[String]) -> i32 {
399     let mut options = getopts::Options::new();
400     for option in opts() {
401         (option.apply)(&mut options);
402     }
403     let matches = match options.parse(&args[1..]) {
404         Ok(m) => m,
405         Err(err) => {
406             early_error(ErrorOutputType::default(), &err.to_string());
407         }
408     };
409     let options = match config::Options::from_matches(&matches) {
410         Ok(opts) => opts,
411         Err(code) => return code,
412     };
413     rustc_interface::interface::default_thread_pool(options.edition, move || {
414         main_options(options)
415     })
416 }
417
418 fn main_options(options: config::Options) -> i32 {
419     let diag = core::new_handler(options.error_format,
420                                  None,
421                                  options.debugging_options.treat_err_as_bug,
422                                  options.debugging_options.ui_testing);
423
424     match (options.should_test, options.markdown_input()) {
425         (true, true) => return markdown::test(options, &diag),
426         (true, false) => return test::run(options),
427         (false, true) => return markdown::render(options.input,
428                                                  options.render_options,
429                                                  &diag,
430                                                  options.edition),
431         (false, false) => {}
432     }
433
434     // need to move these items separately because we lose them by the time the closure is called,
435     // but we can't crates the Handler ahead of time because it's not Send
436     let diag_opts = (options.error_format,
437                      options.debugging_options.treat_err_as_bug,
438                      options.debugging_options.ui_testing,
439                      options.edition);
440     let show_coverage = options.show_coverage;
441     rust_input(options, move |out| {
442         if show_coverage {
443             // if we ran coverage, bail early, we don't need to also generate docs at this point
444             // (also we didn't load in any of the useful passes)
445             return rustc_driver::EXIT_SUCCESS;
446         }
447
448         let Output { krate, renderinfo, renderopts } = out;
449         info!("going to format");
450         let (error_format, treat_err_as_bug, ui_testing, edition) = diag_opts;
451         let diag = core::new_handler(error_format, None, treat_err_as_bug, ui_testing);
452         match html::render::run(
453             krate,
454             renderopts,
455             renderinfo,
456             &diag,
457             edition,
458         ) {
459             Ok(_) => rustc_driver::EXIT_SUCCESS,
460             Err(e) => {
461                 diag.struct_err(&format!("couldn't generate documentation: {}", e.error))
462                     .note(&format!("failed to create or modify \"{}\"", e.file.display()))
463                     .emit();
464                 rustc_driver::EXIT_FAILURE
465             }
466         }
467     })
468 }
469
470 /// Interprets the input file as a rust source file, passing it through the
471 /// compiler all the way through the analysis passes. The rustdoc output is then
472 /// generated from the cleaned AST of the crate.
473 ///
474 /// This form of input will run all of the plug/cleaning passes
475 fn rust_input<R, F>(options: config::Options, f: F) -> R
476 where R: 'static + Send,
477       F: 'static + Send + FnOnce(Output) -> R
478 {
479     // First, parse the crate and extract all relevant information.
480     info!("starting to run rustc");
481
482     let result = rustc_driver::catch_fatal_errors(move || {
483         let crate_name = options.crate_name.clone();
484         let crate_version = options.crate_version.clone();
485         let (mut krate, renderinfo, renderopts) = core::run_core(options);
486
487         info!("finished with rustc");
488
489         if let Some(name) = crate_name {
490             krate.name = name
491         }
492
493         krate.version = crate_version;
494
495         f(Output {
496             krate,
497             renderinfo,
498             renderopts,
499         })
500     });
501
502     match result {
503         Ok(output) => output,
504         Err(_) => panic::resume_unwind(Box::new(errors::FatalErrorMarker)),
505     }
506 }