]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
69d9748bb8832223f931d91583246e7ca7250374
[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(rustc_private)]
5 #![feature(arbitrary_self_types)]
6 #![feature(box_patterns)]
7 #![feature(box_syntax)]
8 #![feature(in_band_lifetimes)]
9 #![feature(nll)]
10 #![feature(set_stdio)]
11 #![feature(test)]
12 #![feature(vec_remove_item)]
13 #![feature(ptr_offset_from)]
14 #![feature(crate_visibility_modifier)]
15 #![feature(const_fn)]
16 #![feature(drain_filter)]
17 #![cfg_attr(bootstrap, feature(never_type))]
18 #![feature(unicode_internals)]
19
20 #![recursion_limit="256"]
21
22 extern crate getopts;
23 extern crate env_logger;
24 extern crate rustc;
25 extern crate rustc_data_structures;
26 extern crate rustc_driver;
27 extern crate rustc_error_codes;
28 extern crate rustc_index;
29 extern crate rustc_resolve;
30 extern crate rustc_lint;
31 extern crate rustc_interface;
32 extern crate rustc_metadata;
33 extern crate rustc_parse;
34 extern crate rustc_target;
35 extern crate rustc_typeck;
36 extern crate rustc_lexer;
37 extern crate serialize;
38 extern crate syntax;
39 extern crate syntax_expand;
40 extern crate syntax_pos;
41 extern crate test as testing;
42 #[macro_use] extern crate log;
43 extern crate rustc_errors as errors;
44
45 use std::default::Default;
46 use std::env;
47 use std::panic;
48 use std::process;
49
50 use rustc::session::{early_warn, early_error};
51 use rustc::session::config::{ErrorOutputType, RustcOptGroup, make_crate_type_option};
52
53 #[macro_use]
54 mod externalfiles;
55
56 mod clean;
57 mod config;
58 mod core;
59 mod docfs;
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     crate mod sources;
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 }
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_from_env("RUSTDOC_LOG");
95     let res = std::thread::Builder::new().stack_size(thread_stack_size).spawn(move || {
96         get_args().map(|args| main_args(&args)).unwrap_or(1)
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         make_crate_type_option(),
139         stable("L", |o| {
140             o.optmulti("L", "library-path", "directory to add to crate search path",
141                        "DIR")
142         }),
143         stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
144         stable("extern", |o| {
145             o.optmulti("", "extern", "pass an --extern to rustc", "NAME[=PATH]")
146         }),
147         unstable("extern-private", |o| {
148             o.optmulti("", "extern-private",
149                        "pass an --extern to rustc (compatibility only)", "NAME=PATH")
150         }),
151         unstable("extern-html-root-url", |o| {
152             o.optmulti("", "extern-html-root-url",
153                        "base URL to use for dependencies", "NAME=URL")
154         }),
155         stable("plugin-path", |o| {
156             o.optmulti("", "plugin-path", "removed", "DIR")
157         }),
158         stable("C", |o| {
159             o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
160         }),
161         stable("passes", |o| {
162             o.optmulti("", "passes",
163                        "list of passes to also run, you might want \
164                         to pass it multiple times; a value of `list` \
165                         will print available passes",
166                        "PASSES")
167         }),
168         stable("plugins", |o| {
169             o.optmulti("", "plugins", "removed",
170                        "PLUGINS")
171         }),
172         stable("no-default", |o| {
173             o.optflag("", "no-defaults", "don't run the default passes")
174         }),
175         stable("document-private-items", |o| {
176             o.optflag("", "document-private-items", "document private items")
177         }),
178         stable("test", |o| o.optflag("", "test", "run code examples as tests")),
179         stable("test-args", |o| {
180             o.optmulti("", "test-args", "arguments to pass to the test runner",
181                        "ARGS")
182         }),
183         stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
184         stable("markdown-css", |o| {
185             o.optmulti("", "markdown-css",
186                        "CSS files to include via <link> in a rendered Markdown file",
187                        "FILES")
188         }),
189         stable("html-in-header", |o|  {
190             o.optmulti("", "html-in-header",
191                        "files to include inline in the <head> section of a rendered Markdown file \
192                         or generated documentation",
193                        "FILES")
194         }),
195         stable("html-before-content", |o| {
196             o.optmulti("", "html-before-content",
197                        "files to include inline between <body> and the content of a rendered \
198                         Markdown file or generated documentation",
199                        "FILES")
200         }),
201         stable("html-after-content", |o| {
202             o.optmulti("", "html-after-content",
203                        "files to include inline between the content and </body> of a rendered \
204                         Markdown file or generated documentation",
205                        "FILES")
206         }),
207         unstable("markdown-before-content", |o| {
208             o.optmulti("", "markdown-before-content",
209                        "files to include inline between <body> and the content of a rendered \
210                         Markdown file or generated documentation",
211                        "FILES")
212         }),
213         unstable("markdown-after-content", |o| {
214             o.optmulti("", "markdown-after-content",
215                        "files to include inline between the content and </body> of a rendered \
216                         Markdown file or generated documentation",
217                        "FILES")
218         }),
219         stable("markdown-playground-url", |o| {
220             o.optopt("", "markdown-playground-url",
221                      "URL to send code snippets to", "URL")
222         }),
223         stable("markdown-no-toc", |o| {
224             o.optflag("", "markdown-no-toc", "don't include table of contents")
225         }),
226         stable("e", |o| {
227             o.optopt("e", "extend-css",
228                      "To add some CSS rules with a given file to generate doc with your \
229                       own theme. However, your theme might break if the rustdoc's generated HTML \
230                       changes, so be careful!", "PATH")
231         }),
232         unstable("Z", |o| {
233             o.optmulti("Z", "",
234                        "internal and debugging options (only on nightly build)", "FLAG")
235         }),
236         stable("sysroot", |o| {
237             o.optopt("", "sysroot", "Override the system root", "PATH")
238         }),
239         unstable("playground-url", |o| {
240             o.optopt("", "playground-url",
241                      "URL to send code snippets to, may be reset by --markdown-playground-url \
242                       or `#![doc(html_playground_url=...)]`",
243                      "URL")
244         }),
245         unstable("display-warnings", |o| {
246             o.optflag("", "display-warnings", "to print code warnings when testing doc")
247         }),
248         unstable("crate-version", |o| {
249             o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
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         stable("theme", |o| {
256             o.optmulti("", "theme",
257                        "additional themes which will be added to the generated docs",
258                        "FILES")
259         }),
260         stable("check-theme", |o| {
261             o.optmulti("", "check-theme",
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         stable("json", |o| {
293             o.optopt("",
294                      "json",
295                      "Configure the structure of JSON diagnostics",
296                      "CONFIG")
297         }),
298         unstable("disable-minification", |o| {
299              o.optflag("",
300                        "disable-minification",
301                        "Disable minification applied on JS files")
302         }),
303         stable("warn", |o| {
304             o.optmulti("W", "warn", "Set lint warnings", "OPT")
305         }),
306         stable("allow", |o| {
307             o.optmulti("A", "allow", "Set lint allowed", "OPT")
308         }),
309         stable("deny", |o| {
310             o.optmulti("D", "deny", "Set lint denied", "OPT")
311         }),
312         stable("forbid", |o| {
313             o.optmulti("F", "forbid", "Set lint forbidden", "OPT")
314         }),
315         stable("cap-lints", |o| {
316             o.optmulti(
317                 "",
318                 "cap-lints",
319                 "Set the most restrictive lint level. \
320                  More restrictive lints are capped at this \
321                  level. By default, it is at `forbid` level.",
322                 "LEVEL",
323             )
324         }),
325         unstable("index-page", |o| {
326              o.optopt("",
327                       "index-page",
328                       "Markdown file to be used as index page",
329                       "PATH")
330         }),
331         unstable("enable-index-page", |o| {
332              o.optflag("",
333                        "enable-index-page",
334                        "To enable generation of the index page")
335         }),
336         unstable("static-root-path", |o| {
337             o.optopt("",
338                      "static-root-path",
339                      "Path string to force loading static files from in output pages. \
340                       If not set, uses combinations of '../' to reach the documentation root.",
341                      "PATH")
342         }),
343         unstable("disable-per-crate-search", |o| {
344             o.optflag("",
345                       "disable-per-crate-search",
346                       "disables generating the crate selector on the search box")
347         }),
348         unstable("persist-doctests", |o| {
349              o.optopt("",
350                        "persist-doctests",
351                        "Directory to persist doctest executables into",
352                        "PATH")
353         }),
354         unstable("generate-redirect-pages", |o| {
355             o.optflag("",
356                       "generate-redirect-pages",
357                       "Generate extra pages to support legacy URLs and tool links")
358         }),
359         unstable("show-coverage", |o| {
360             o.optflag("",
361                       "show-coverage",
362                       "calculate percentage of public items with documentation")
363         }),
364         unstable("enable-per-target-ignores", |o| {
365             o.optflag("",
366                       "enable-per-target-ignores",
367                       "parse ignore-foo for ignoring doctests on a per-target basis")
368         }),
369         unstable("runtool", |o| {
370             o.optopt("",
371                      "runtool",
372                      "",
373                      "The tool to run tests with when building for a different target than host")
374         }),
375         unstable("runtool-arg", |o| {
376             o.optmulti("",
377                        "runtool-arg",
378                        "",
379                        "One (of possibly many) arguments to pass to the runtool")
380         }),
381         unstable("test-builder", |o| {
382             o.optflag("",
383                       "test-builder",
384                       "specified the rustc-like binary to use as the test builder")
385         }),
386     ]
387 }
388
389 fn usage(argv0: &str) {
390     let mut options = getopts::Options::new();
391     for option in opts() {
392         (option.apply)(&mut options);
393     }
394     println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
395 }
396
397 fn main_args(args: &[String]) -> i32 {
398     let mut options = getopts::Options::new();
399     for option in opts() {
400         (option.apply)(&mut options);
401     }
402     let matches = match options.parse(&args[1..]) {
403         Ok(m) => m,
404         Err(err) => {
405             early_error(ErrorOutputType::default(), &err.to_string());
406         }
407     };
408     let options = match config::Options::from_matches(&matches) {
409         Ok(opts) => opts,
410         Err(code) => return code,
411     };
412     rustc_interface::interface::default_thread_pool(options.edition, move || {
413         main_options(options)
414     })
415 }
416
417 fn main_options(options: config::Options) -> i32 {
418     let diag = core::new_handler(options.error_format,
419                                  None,
420                                  options.debugging_options.treat_err_as_bug,
421                                  options.debugging_options.ui_testing);
422
423     match (options.should_test, options.markdown_input()) {
424         (true, true) => return markdown::test(options, &diag),
425         (true, false) => return test::run(options),
426         (false, true) => return markdown::render(options.input,
427                                                  options.render_options,
428                                                  &diag,
429                                                  options.edition),
430         (false, false) => {}
431     }
432
433     // need to move these items separately because we lose them by the time the closure is called,
434     // but we can't crates the Handler ahead of time because it's not Send
435     let diag_opts = (options.error_format,
436                      options.debugging_options.treat_err_as_bug,
437                      options.debugging_options.ui_testing,
438                      options.edition);
439     let show_coverage = options.show_coverage;
440     rust_input(options, move |out| {
441         if show_coverage {
442             // if we ran coverage, bail early, we don't need to also generate docs at this point
443             // (also we didn't load in any of the useful passes)
444             return rustc_driver::EXIT_SUCCESS;
445         }
446
447         let Output { krate, renderinfo, renderopts } = out;
448         info!("going to format");
449         let (error_format, treat_err_as_bug, ui_testing, edition) = diag_opts;
450         let diag = core::new_handler(error_format, None, treat_err_as_bug, ui_testing);
451         match html::render::run(
452             krate,
453             renderopts,
454             renderinfo,
455             &diag,
456             edition,
457         ) {
458             Ok(_) => rustc_driver::EXIT_SUCCESS,
459             Err(e) => {
460                 diag.struct_err(&format!("couldn't generate documentation: {}", e.error))
461                     .note(&format!("failed to create or modify \"{}\"", e.file.display()))
462                     .emit();
463                 rustc_driver::EXIT_FAILURE
464             }
465         }
466     })
467 }
468
469 /// Interprets the input file as a rust source file, passing it through the
470 /// compiler all the way through the analysis passes. The rustdoc output is then
471 /// generated from the cleaned AST of the crate.
472 ///
473 /// This form of input will run all of the plug/cleaning passes
474 fn rust_input<R, F>(options: config::Options, f: F) -> R
475 where R: 'static + Send,
476       F: 'static + Send + FnOnce(Output) -> R
477 {
478     // First, parse the crate and extract all relevant information.
479     info!("starting to run rustc");
480
481     let result = rustc_driver::catch_fatal_errors(move || {
482         let crate_name = options.crate_name.clone();
483         let crate_version = options.crate_version.clone();
484         let (mut krate, renderinfo, renderopts) = core::run_core(options);
485
486         info!("finished with rustc");
487
488         if let Some(name) = crate_name {
489             krate.name = name
490         }
491
492         krate.version = crate_version;
493
494         f(Output {
495             krate,
496             renderinfo,
497             renderopts,
498         })
499     });
500
501     match result {
502         Ok(output) => output,
503         Err(_) => panic::resume_unwind(Box::new(errors::FatalErrorMarker)),
504     }
505 }