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