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