]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Rename `Item.node` to `Item.kind`
[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 #![feature(inner_deref)]
18 #![feature(never_type)]
19 #![feature(mem_take)]
20 #![feature(unicode_internals)]
21
22 #![recursion_limit="256"]
23
24 extern crate getopts;
25 extern crate env_logger;
26 extern crate rustc;
27 extern crate rustc_data_structures;
28 extern crate rustc_driver;
29 extern crate rustc_resolve;
30 extern crate rustc_lint;
31 extern crate rustc_interface;
32 extern crate rustc_metadata;
33 extern crate rustc_target;
34 extern crate rustc_typeck;
35 extern crate rustc_lexer;
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
48 use rustc::session::{early_warn, early_error};
49 use rustc::session::config::{ErrorOutputType, RustcOptGroup, make_crate_type_option};
50
51 #[macro_use]
52 mod externalfiles;
53
54 mod clean;
55 mod config;
56 mod core;
57 mod docfs;
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     crate mod sources;
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 }
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_from_env("RUSTDOC_LOG");
93     let res = std::thread::Builder::new().stack_size(thread_stack_size).spawn(move || {
94         get_args().map(|args| main_args(&args)).unwrap_or(1)
95     }).unwrap().join().unwrap_or(rustc_driver::EXIT_FAILURE);
96     process::exit(res);
97 }
98
99 fn get_args() -> Option<Vec<String>> {
100     env::args_os().enumerate()
101         .map(|(i, arg)| arg.into_string().map_err(|arg| {
102              early_warn(ErrorOutputType::default(),
103                         &format!("Argument {} is not valid Unicode: {:?}", i, arg));
104         }).ok())
105         .collect()
106 }
107
108 fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
109     where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
110 {
111     RustcOptGroup::stable(name, f)
112 }
113
114 fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
115     where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
116 {
117     RustcOptGroup::unstable(name, f)
118 }
119
120 fn opts() -> Vec<RustcOptGroup> {
121     vec![
122         stable("h", |o| o.optflag("h", "help", "show this help message")),
123         stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
124         stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
125         stable("r", |o| {
126             o.optopt("r", "input-format", "the input type of the specified file",
127                      "[rust]")
128         }),
129         stable("w", |o| {
130             o.optopt("w", "output-format", "the output type to write", "[html]")
131         }),
132         stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
133         stable("crate-name", |o| {
134             o.optopt("", "crate-name", "specify the name of this crate", "NAME")
135         }),
136         make_crate_type_option(),
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("sort-modules-by-appearance", |o| {
246             o.optflag("", "sort-modules-by-appearance", "sort modules by where they appear in the \
247                                                          program, rather than alphabetically")
248         }),
249         unstable("themes", |o| {
250             o.optmulti("", "themes",
251                        "additional themes which will be added to the generated docs",
252                        "FILES")
253         }),
254         unstable("theme-checker", |o| {
255             o.optmulti("", "theme-checker",
256                        "check if given theme is valid",
257                        "FILES")
258         }),
259         unstable("resource-suffix", |o| {
260             o.optopt("",
261                      "resource-suffix",
262                      "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
263                       \"light-suffix.css\"",
264                      "PATH")
265         }),
266         stable("edition", |o| {
267             o.optopt("", "edition",
268                      "edition to use when compiling rust code (default: 2015)",
269                      "EDITION")
270         }),
271         stable("color", |o| {
272             o.optopt("",
273                      "color",
274                      "Configure coloring of output:
275                                           auto   = colorize, if output goes to a tty (default);
276                                           always = always colorize output;
277                                           never  = never colorize output",
278                      "auto|always|never")
279         }),
280         stable("error-format", |o| {
281             o.optopt("",
282                      "error-format",
283                      "How errors and other messages are produced",
284                      "human|json|short")
285         }),
286         stable("json", |o| {
287             o.optopt("",
288                      "json",
289                      "Configure the structure of JSON diagnostics",
290                      "CONFIG")
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         unstable("generate-redirect-pages", |o| {
349             o.optflag("",
350                       "generate-redirect-pages",
351                       "Generate extra pages to support legacy URLs and tool links")
352         }),
353         unstable("show-coverage", |o| {
354             o.optflag("",
355                       "show-coverage",
356                       "calculate percentage of public items with documentation")
357         }),
358         unstable("enable-per-target-ignores", |o| {
359             o.optflag("",
360                       "enable-per-target-ignores",
361                       "parse ignore-foo for ignoring doctests on a per-target basis")
362         }),
363         unstable("runtool", |o| {
364             o.optopt("",
365                      "runtool",
366                      "",
367                      "The tool to run tests with when building for a different target than host")
368         }),
369         unstable("runtool-arg", |o| {
370             o.optmulti("",
371                        "runtool-arg",
372                        "",
373                        "One (of possibly many) arguments to pass to the runtool")
374         }),
375         unstable("test-builder", |o| {
376             o.optflag("",
377                       "test-builder",
378                       "specified the rustc-like binary to use as the test builder")
379         }),
380     ]
381 }
382
383 fn usage(argv0: &str) {
384     let mut options = getopts::Options::new();
385     for option in opts() {
386         (option.apply)(&mut options);
387     }
388     println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
389 }
390
391 fn main_args(args: &[String]) -> i32 {
392     let mut options = getopts::Options::new();
393     for option in opts() {
394         (option.apply)(&mut options);
395     }
396     let matches = match options.parse(&args[1..]) {
397         Ok(m) => m,
398         Err(err) => {
399             early_error(ErrorOutputType::default(), &err.to_string());
400         }
401     };
402     let options = match config::Options::from_matches(&matches) {
403         Ok(opts) => opts,
404         Err(code) => return code,
405     };
406     rustc_interface::interface::default_thread_pool(options.edition, move || {
407         main_options(options)
408     })
409 }
410
411 fn main_options(options: config::Options) -> i32 {
412     let diag = core::new_handler(options.error_format,
413                                  None,
414                                  options.debugging_options.treat_err_as_bug,
415                                  options.debugging_options.ui_testing);
416
417     match (options.should_test, options.markdown_input()) {
418         (true, true) => return markdown::test(options, &diag),
419         (true, false) => return test::run(options),
420         (false, true) => return markdown::render(options.input,
421                                                  options.render_options,
422                                                  &diag,
423                                                  options.edition),
424         (false, false) => {}
425     }
426
427     // need to move these items separately because we lose them by the time the closure is called,
428     // but we can't crates the Handler ahead of time because it's not Send
429     let diag_opts = (options.error_format,
430                      options.debugging_options.treat_err_as_bug,
431                      options.debugging_options.ui_testing,
432                      options.edition);
433     let show_coverage = options.show_coverage;
434     rust_input(options, move |out| {
435         if show_coverage {
436             // if we ran coverage, bail early, we don't need to also generate docs at this point
437             // (also we didn't load in any of the useful passes)
438             return rustc_driver::EXIT_SUCCESS;
439         }
440
441         let Output { krate, renderinfo, renderopts } = out;
442         info!("going to format");
443         let (error_format, treat_err_as_bug, ui_testing, edition) = diag_opts;
444         let diag = core::new_handler(error_format, None, treat_err_as_bug, ui_testing);
445         match html::render::run(
446             krate,
447             renderopts,
448             renderinfo,
449             &diag,
450             edition,
451         ) {
452             Ok(_) => rustc_driver::EXIT_SUCCESS,
453             Err(e) => {
454                 diag.struct_err(&format!("couldn't generate documentation: {}", e.error))
455                     .note(&format!("failed to create or modify \"{}\"", e.file.display()))
456                     .emit();
457                 rustc_driver::EXIT_FAILURE
458             }
459         }
460     })
461 }
462
463 /// Interprets the input file as a rust source file, passing it through the
464 /// compiler all the way through the analysis passes. The rustdoc output is then
465 /// generated from the cleaned AST of the crate.
466 ///
467 /// This form of input will run all of the plug/cleaning passes
468 fn rust_input<R, F>(options: config::Options, f: F) -> R
469 where R: 'static + Send,
470       F: 'static + Send + FnOnce(Output) -> R
471 {
472     // First, parse the crate and extract all relevant information.
473     info!("starting to run rustc");
474
475     let result = rustc_driver::catch_fatal_errors(move || {
476         let crate_name = options.crate_name.clone();
477         let crate_version = options.crate_version.clone();
478         let (mut krate, renderinfo, renderopts) = core::run_core(options);
479
480         info!("finished with rustc");
481
482         if let Some(name) = crate_name {
483             krate.name = name
484         }
485
486         krate.version = crate_version;
487
488         f(Output {
489             krate: krate,
490             renderinfo: renderinfo,
491             renderopts,
492         })
493     });
494
495     match result {
496         Ok(output) => output,
497         Err(_) => panic::resume_unwind(Box::new(errors::FatalErrorMarker)),
498     }
499 }