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