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