]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Rollup merge of #58448 - euclio:missing-summaries, r=QuietMisdreavus
[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(bind_by_move_pattern_guards)]
5 #![feature(rustc_private)]
6 #![feature(box_patterns)]
7 #![feature(box_syntax)]
8 #![feature(nll)]
9 #![feature(set_stdio)]
10 #![feature(test)]
11 #![feature(vec_remove_item)]
12 #![feature(ptr_offset_from)]
13 #![feature(crate_visibility_modifier)]
14 #![feature(const_fn)]
15 #![feature(drain_filter)]
16 #![feature(inner_deref)]
17
18 #![recursion_limit="256"]
19
20 extern crate arena;
21 extern crate getopts;
22 extern crate env_logger;
23 extern crate rustc;
24 extern crate rustc_data_structures;
25 extern crate rustc_codegen_utils;
26 extern crate rustc_driver;
27 extern crate rustc_resolve;
28 extern crate rustc_lint;
29 extern crate rustc_metadata;
30 extern crate rustc_target;
31 extern crate rustc_typeck;
32 extern crate serialize;
33 extern crate syntax;
34 extern crate syntax_pos;
35 extern crate test as testing;
36 #[macro_use] extern crate log;
37 extern crate rustc_errors as errors;
38 extern crate pulldown_cmark;
39 extern crate tempfile;
40 extern crate minifier;
41 extern crate parking_lot;
42
43 extern crate serialize as rustc_serialize; // used by deriving
44
45 use std::default::Default;
46 use std::env;
47 use std::panic;
48 use std::process;
49 use std::sync::mpsc::channel;
50
51 use rustc::session::{early_warn, early_error};
52 use rustc::session::config::{ErrorOutputType, RustcOptGroup};
53
54 #[macro_use]
55 mod externalfiles;
56
57 mod clean;
58 mod config;
59 mod core;
60 mod doctree;
61 mod fold;
62 pub mod html {
63     crate mod highlight;
64     crate mod escape;
65     crate mod item_type;
66     crate mod format;
67     crate mod layout;
68     pub mod markdown;
69     crate mod render;
70     crate mod static_files;
71     crate mod toc;
72 }
73 mod markdown;
74 mod passes;
75 mod visit_ast;
76 mod visit_lib;
77 mod test;
78 mod theme;
79
80 struct Output {
81     krate: clean::Crate,
82     renderinfo: html::render::RenderInfo,
83     renderopts: config::RenderOptions,
84     passes: Vec<String>,
85 }
86
87 pub fn main() {
88     let thread_stack_size: usize = if cfg!(target_os = "haiku") {
89         16_000_000 // 16MB on Haiku
90     } else {
91         32_000_000 // 32MB on other platforms
92     };
93     rustc_driver::set_sigpipe_handler();
94     env_logger::init();
95     let res = std::thread::Builder::new().stack_size(thread_stack_size).spawn(move || {
96         syntax::with_globals(move || {
97             get_args().map(|args| main_args(&args)).unwrap_or(1)
98         })
99     }).unwrap().join().unwrap_or(rustc_driver::EXIT_FAILURE);
100     process::exit(res as i32);
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     ]
349 }
350
351 fn usage(argv0: &str) {
352     let mut options = getopts::Options::new();
353     for option in opts() {
354         (option.apply)(&mut options);
355     }
356     println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
357 }
358
359 fn main_args(args: &[String]) -> isize {
360     let mut options = getopts::Options::new();
361     for option in opts() {
362         (option.apply)(&mut options);
363     }
364     let matches = match options.parse(&args[1..]) {
365         Ok(m) => m,
366         Err(err) => {
367             early_error(ErrorOutputType::default(), &err.to_string());
368         }
369     };
370     let options = match config::Options::from_matches(&matches) {
371         Ok(opts) => opts,
372         Err(code) => return code,
373     };
374
375     let diag = core::new_handler(options.error_format,
376                                  None,
377                                  options.debugging_options.treat_err_as_bug,
378                                  options.debugging_options.ui_testing);
379
380     match (options.should_test, options.markdown_input()) {
381         (true, true) => return markdown::test(options, &diag),
382         (true, false) => return test::run(options),
383         (false, true) => return markdown::render(options.input, options.render_options, &diag),
384         (false, false) => {}
385     }
386
387     // need to move these items separately because we lose them by the time the closure is called,
388     // but we can't crates the Handler ahead of time because it's not Send
389     let diag_opts = (options.error_format,
390                      options.debugging_options.treat_err_as_bug,
391                      options.debugging_options.ui_testing);
392     rust_input(options, move |out| {
393         let Output { krate, passes, renderinfo, renderopts } = out;
394         info!("going to format");
395         let (error_format, treat_err_as_bug, ui_testing) = diag_opts;
396         let diag = core::new_handler(error_format, None, treat_err_as_bug, ui_testing);
397         match html::render::run(
398             krate,
399             renderopts,
400             passes.into_iter().collect(),
401             renderinfo,
402             &diag,
403         ) {
404             Ok(_) => rustc_driver::EXIT_SUCCESS,
405             Err(e) => {
406                 diag.struct_err(&format!("couldn't generate documentation: {}", e.error))
407                     .note(&format!("failed to create or modify \"{}\"", e.file.display()))
408                     .emit();
409                 rustc_driver::EXIT_FAILURE
410             }
411         }
412     })
413 }
414
415 /// Interprets the input file as a rust source file, passing it through the
416 /// compiler all the way through the analysis passes. The rustdoc output is then
417 /// generated from the cleaned AST of the crate.
418 ///
419 /// This form of input will run all of the plug/cleaning passes
420 fn rust_input<R, F>(options: config::Options, f: F) -> R
421 where R: 'static + Send,
422       F: 'static + Send + FnOnce(Output) -> R
423 {
424     // First, parse the crate and extract all relevant information.
425     info!("starting to run rustc");
426
427     let (tx, rx) = channel();
428
429     let result = rustc_driver::monitor(move || syntax::with_globals(move || {
430         let crate_name = options.crate_name.clone();
431         let crate_version = options.crate_version.clone();
432         let (mut krate, renderinfo, renderopts, passes) = core::run_core(options);
433
434         info!("finished with rustc");
435
436         if let Some(name) = crate_name {
437             krate.name = name
438         }
439
440         krate.version = crate_version;
441
442         info!("Executing passes");
443
444         for pass in &passes {
445             // determine if we know about this pass
446             let pass = match passes::find_pass(pass) {
447                 Some(pass) => if let Some(pass) = pass.late_fn() {
448                     pass
449                 } else {
450                     // not a late pass, but still valid so don't report the error
451                     continue
452                 }
453                 None => {
454                     error!("unknown pass {}, skipping", *pass);
455
456                     continue
457                 },
458             };
459
460             // run it
461             krate = pass(krate);
462         }
463
464         tx.send(f(Output {
465             krate: krate,
466             renderinfo: renderinfo,
467             renderopts,
468             passes: passes
469         })).unwrap();
470     }));
471
472     match result {
473         Ok(()) => rx.recv().unwrap(),
474         Err(_) => panic::resume_unwind(Box::new(errors::FatalErrorMarker)),
475     }
476 }