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