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