]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Add comment about the lack of `ExpnData` serialization for proc-macro crates
[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 #![recursion_limit = "256"]
16
17 #[macro_use]
18 extern crate lazy_static;
19 extern crate rustc_ast;
20 extern crate rustc_ast_pretty;
21 extern crate rustc_attr;
22 extern crate rustc_data_structures;
23 extern crate rustc_driver;
24 extern crate rustc_errors;
25 extern crate rustc_expand;
26 extern crate rustc_feature;
27 extern crate rustc_hir;
28 extern crate rustc_hir_pretty;
29 extern crate rustc_index;
30 extern crate rustc_infer;
31 extern crate rustc_interface;
32 extern crate rustc_lexer;
33 extern crate rustc_lint;
34 extern crate rustc_metadata;
35 extern crate rustc_middle;
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_trait_selection;
43 extern crate rustc_typeck;
44 extern crate test as testing;
45 #[macro_use]
46 extern crate tracing as 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::getopts;
55 use rustc_session::{early_error, early_warn};
56
57 #[macro_use]
58 mod externalfiles;
59
60 mod clean;
61 mod config;
62 mod core;
63 mod docfs;
64 mod doctree;
65 #[macro_use]
66 mod error;
67 mod fold;
68 crate mod formats;
69 pub mod html;
70 mod json;
71 mod markdown;
72 mod passes;
73 mod test;
74 mod theme;
75 mod visit_ast;
76 mod visit_lib;
77
78 struct Output {
79     krate: clean::Crate,
80     renderinfo: config::RenderInfo,
81     renderopts: config::RenderOptions,
82 }
83
84 pub fn main() {
85     let thread_stack_size: usize = if cfg!(target_os = "haiku") {
86         16_000_000 // 16MB on Haiku
87     } else {
88         32_000_000 // 32MB on other platforms
89     };
90     rustc_driver::set_sigpipe_handler();
91     rustc_driver::install_ice_hook();
92     rustc_driver::init_env_logger("RUSTDOC_LOG");
93
94     let res = std::thread::Builder::new()
95         .stack_size(thread_stack_size)
96         .spawn(move || get_args().map(|args| main_args(&args)).unwrap_or(1))
97         .unwrap()
98         .join()
99         .unwrap_or(rustc_driver::EXIT_FAILURE);
100     process::exit(res);
101 }
102
103 fn get_args() -> Option<Vec<String>> {
104     env::args_os()
105         .enumerate()
106         .map(|(i, arg)| {
107             arg.into_string()
108                 .map_err(|arg| {
109                     early_warn(
110                         ErrorOutputType::default(),
111                         &format!("Argument {} is not valid Unicode: {:?}", i, arg),
112                     );
113                 })
114                 .ok()
115         })
116         .collect()
117 }
118
119 fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
120 where
121     F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
122 {
123     RustcOptGroup::stable(name, f)
124 }
125
126 fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
127 where
128     F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
129 {
130     RustcOptGroup::unstable(name, f)
131 }
132
133 fn opts() -> Vec<RustcOptGroup> {
134     vec![
135         stable("h", |o| o.optflag("h", "help", "show this help message")),
136         stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
137         stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
138         stable("r", |o| {
139             o.optopt("r", "input-format", "the input type of the specified file", "[rust]")
140         }),
141         stable("w", |o| o.optopt("w", "output-format", "the output type to write", "[html]")),
142         stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
143         stable("crate-name", |o| {
144             o.optopt("", "crate-name", "specify the name of this crate", "NAME")
145         }),
146         make_crate_type_option(),
147         stable("L", |o| {
148             o.optmulti("L", "library-path", "directory to add to crate search path", "DIR")
149         }),
150         stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
151         stable("extern", |o| o.optmulti("", "extern", "pass an --extern to rustc", "NAME[=PATH]")),
152         unstable("extern-html-root-url", |o| {
153             o.optmulti("", "extern-html-root-url", "base URL to use for dependencies", "NAME=URL")
154         }),
155         stable("plugin-path", |o| o.optmulti("", "plugin-path", "removed", "DIR")),
156         stable("C", |o| {
157             o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
158         }),
159         stable("passes", |o| {
160             o.optmulti(
161                 "",
162                 "passes",
163                 "list of passes to also run, you might want to pass it multiple times; a value of \
164                         `list` will print available passes",
165                 "PASSES",
166             )
167         }),
168         stable("plugins", |o| o.optmulti("", "plugins", "removed", "PLUGINS")),
169         stable("no-default", |o| o.optflag("", "no-defaults", "don't run the default passes")),
170         stable("document-private-items", |o| {
171             o.optflag("", "document-private-items", "document private items")
172         }),
173         unstable("document-hidden-items", |o| {
174             o.optflag("", "document-hidden-items", "document items that have doc(hidden)")
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         stable("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 program, rather than alphabetically",
274             )
275         }),
276         stable("theme", |o| {
277             o.optmulti(
278                 "",
279                 "theme",
280                 "additional themes which will be added to the generated docs",
281                 "FILES",
282             )
283         }),
284         stable("check-theme", |o| {
285             o.optmulti("", "check-theme", "check if given theme is valid", "FILES")
286         }),
287         unstable("resource-suffix", |o| {
288             o.optopt(
289                 "",
290                 "resource-suffix",
291                 "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
292                       \"light-suffix.css\"",
293                 "PATH",
294             )
295         }),
296         stable("edition", |o| {
297             o.optopt(
298                 "",
299                 "edition",
300                 "edition to use when compiling rust code (default: 2015)",
301                 "EDITION",
302             )
303         }),
304         stable("color", |o| {
305             o.optopt(
306                 "",
307                 "color",
308                 "Configure coloring of output:
309                                           auto   = colorize, if output goes to a tty (default);
310                                           always = always colorize output;
311                                           never  = never colorize output",
312                 "auto|always|never",
313             )
314         }),
315         stable("error-format", |o| {
316             o.optopt(
317                 "",
318                 "error-format",
319                 "How errors and other messages are produced",
320                 "human|json|short",
321             )
322         }),
323         stable("json", |o| {
324             o.optopt("", "json", "Configure the structure of JSON diagnostics", "CONFIG")
325         }),
326         unstable("disable-minification", |o| {
327             o.optflag("", "disable-minification", "Disable minification applied on JS files")
328         }),
329         stable("warn", |o| o.optmulti("W", "warn", "Set lint warnings", "OPT")),
330         stable("allow", |o| o.optmulti("A", "allow", "Set lint allowed", "OPT")),
331         stable("deny", |o| o.optmulti("D", "deny", "Set lint denied", "OPT")),
332         stable("forbid", |o| o.optmulti("F", "forbid", "Set lint forbidden", "OPT")),
333         stable("cap-lints", |o| {
334             o.optmulti(
335                 "",
336                 "cap-lints",
337                 "Set the most restrictive lint level. \
338                  More restrictive lints are capped at this \
339                  level. By default, it is at `forbid` level.",
340                 "LEVEL",
341             )
342         }),
343         unstable("index-page", |o| {
344             o.optopt("", "index-page", "Markdown file to be used as index page", "PATH")
345         }),
346         unstable("enable-index-page", |o| {
347             o.optflag("", "enable-index-page", "To enable generation of the index page")
348         }),
349         unstable("static-root-path", |o| {
350             o.optopt(
351                 "",
352                 "static-root-path",
353                 "Path string to force loading static files from in output pages. \
354                         If not set, uses combinations of '../' to reach the documentation root.",
355                 "PATH",
356             )
357         }),
358         unstable("disable-per-crate-search", |o| {
359             o.optflag(
360                 "",
361                 "disable-per-crate-search",
362                 "disables generating the crate selector on the search box",
363             )
364         }),
365         unstable("persist-doctests", |o| {
366             o.optopt(
367                 "",
368                 "persist-doctests",
369                 "Directory to persist doctest executables into",
370                 "PATH",
371             )
372         }),
373         unstable("show-coverage", |o| {
374             o.optflag(
375                 "",
376                 "show-coverage",
377                 "calculate percentage of public items with documentation",
378             )
379         }),
380         unstable("enable-per-target-ignores", |o| {
381             o.optflag(
382                 "",
383                 "enable-per-target-ignores",
384                 "parse ignore-foo for ignoring doctests on a per-target basis",
385             )
386         }),
387         unstable("runtool", |o| {
388             o.optopt(
389                 "",
390                 "runtool",
391                 "",
392                 "The tool to run tests with when building for a different target than host",
393             )
394         }),
395         unstable("runtool-arg", |o| {
396             o.optmulti(
397                 "",
398                 "runtool-arg",
399                 "",
400                 "One (of possibly many) arguments to pass to the runtool",
401             )
402         }),
403         unstable("test-builder", |o| {
404             o.optflag(
405                 "",
406                 "test-builder",
407                 "specified the rustc-like binary to use as the test builder",
408             )
409         }),
410     ]
411 }
412
413 fn usage(argv0: &str) {
414     let mut options = getopts::Options::new();
415     for option in opts() {
416         (option.apply)(&mut options);
417     }
418     println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
419 }
420
421 fn main_args(args: &[String]) -> i32 {
422     let mut options = getopts::Options::new();
423     for option in opts() {
424         (option.apply)(&mut options);
425     }
426     let matches = match options.parse(&args[1..]) {
427         Ok(m) => m,
428         Err(err) => {
429             early_error(ErrorOutputType::default(), &err.to_string());
430         }
431     };
432     let options = match config::Options::from_matches(&matches) {
433         Ok(opts) => opts,
434         Err(code) => return code,
435     };
436     rustc_interface::interface::setup_callbacks_and_run_in_default_thread_pool_with_globals(
437         options.edition,
438         move || main_options(options),
439     )
440 }
441
442 fn wrap_return(diag: &rustc_errors::Handler, res: Result<(), String>) -> i32 {
443     match res {
444         Ok(()) => 0,
445         Err(err) => {
446             if !err.is_empty() {
447                 diag.struct_err(&err).emit();
448             }
449             1
450         }
451     }
452 }
453
454 fn run_renderer<T: formats::FormatRenderer>(
455     krate: clean::Crate,
456     renderopts: config::RenderOptions,
457     render_info: config::RenderInfo,
458     diag: &rustc_errors::Handler,
459     edition: rustc_span::edition::Edition,
460 ) -> i32 {
461     match formats::run_format::<T>(krate, renderopts, render_info, &diag, edition) {
462         Ok(_) => rustc_driver::EXIT_SUCCESS,
463         Err(e) => {
464             let mut msg = diag.struct_err(&format!("couldn't generate documentation: {}", e.error));
465             let file = e.file.display().to_string();
466             if file.is_empty() {
467                 msg.emit()
468             } else {
469                 msg.note(&format!("failed to create or modify \"{}\"", file)).emit()
470             }
471             rustc_driver::EXIT_FAILURE
472         }
473     }
474 }
475
476 fn main_options(options: config::Options) -> i32 {
477     let diag = core::new_handler(options.error_format, None, &options.debugging_options);
478
479     match (options.should_test, options.markdown_input()) {
480         (true, true) => return wrap_return(&diag, markdown::test(options)),
481         (true, false) => return wrap_return(&diag, test::run(options)),
482         (false, true) => {
483             return wrap_return(
484                 &diag,
485                 markdown::render(&options.input, options.render_options, options.edition),
486             );
487         }
488         (false, false) => {}
489     }
490
491     // need to move these items separately because we lose them by the time the closure is called,
492     // but we can't crates the Handler ahead of time because it's not Send
493     let diag_opts = (options.error_format, options.edition, options.debugging_options.clone());
494     let show_coverage = options.show_coverage;
495
496     // First, parse the crate and extract all relevant information.
497     info!("starting to run rustc");
498
499     // Interpret the input file as a rust source file, passing it through the
500     // compiler all the way through the analysis passes. The rustdoc output is
501     // then generated from the cleaned AST of the crate. This runs all the
502     // plug/cleaning passes.
503     let result = rustc_driver::catch_fatal_errors(move || {
504         let crate_name = options.crate_name.clone();
505         let crate_version = options.crate_version.clone();
506         let output_format = options.output_format;
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         let out = Output { krate, renderinfo, renderopts };
518
519         if show_coverage {
520             // if we ran coverage, bail early, we don't need to also generate docs at this point
521             // (also we didn't load in any of the useful passes)
522             return rustc_driver::EXIT_SUCCESS;
523         }
524
525         let Output { krate, renderinfo, renderopts } = out;
526         info!("going to format");
527         let (error_format, edition, debugging_options) = diag_opts;
528         let diag = core::new_handler(error_format, None, &debugging_options);
529         match output_format {
530             None | Some(config::OutputFormat::Html) => {
531                 run_renderer::<html::render::Context>(krate, renderopts, renderinfo, &diag, edition)
532             }
533             Some(config::OutputFormat::Json) => {
534                 run_renderer::<json::JsonRenderer>(krate, renderopts, renderinfo, &diag, edition)
535             }
536         }
537     });
538
539     match result {
540         Ok(output) => output,
541         Err(_) => panic::resume_unwind(Box::new(rustc_errors::FatalErrorMarker)),
542     }
543 }