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