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