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