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