]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Various minor/cosmetic improvements to code
[rust.git] / src / librustdoc / lib.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
12        html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
13        html_root_url = "https://doc.rust-lang.org/nightly/",
14        html_playground_url = "https://play.rust-lang.org/")]
15
16 #![feature(rustc_private)]
17 #![feature(box_patterns)]
18 #![feature(box_syntax)]
19 #![feature(nll)]
20 #![feature(set_stdio)]
21 #![feature(slice_sort_by_cached_key)]
22 #![feature(test)]
23 #![feature(vec_remove_item)]
24 #![feature(ptr_offset_from)]
25 #![feature(crate_visibility_modifier)]
26 #![feature(const_fn)]
27 #![feature(drain_filter)]
28
29 #![recursion_limit="256"]
30
31 extern crate arena;
32 extern crate getopts;
33 extern crate env_logger;
34 extern crate rustc;
35 extern crate rustc_data_structures;
36 extern crate rustc_codegen_utils;
37 extern crate rustc_driver;
38 extern crate rustc_resolve;
39 extern crate rustc_lint;
40 extern crate rustc_metadata;
41 extern crate rustc_target;
42 extern crate rustc_typeck;
43 extern crate serialize;
44 #[macro_use] extern crate syntax;
45 extern crate syntax_pos;
46 extern crate test as testing;
47 #[macro_use] extern crate log;
48 extern crate rustc_errors as errors;
49 extern crate pulldown_cmark;
50 extern crate tempfile;
51 extern crate minifier;
52 extern crate parking_lot;
53
54 extern crate serialize as rustc_serialize; // used by deriving
55
56 use std::default::Default;
57 use std::env;
58 use std::panic;
59 use std::process;
60 use std::sync::mpsc::channel;
61
62 use rustc::session::{early_warn, early_error};
63 use rustc::session::config::{ErrorOutputType, RustcOptGroup};
64
65 #[macro_use]
66 mod externalfiles;
67
68 mod clean;
69 mod config;
70 mod core;
71 mod doctree;
72 mod fold;
73 pub mod html {
74     crate mod highlight;
75     crate mod escape;
76     crate mod item_type;
77     crate mod format;
78     crate mod layout;
79     pub mod markdown;
80     crate mod render;
81     crate mod static_files;
82     crate mod toc;
83 }
84 mod markdown;
85 mod passes;
86 mod visit_ast;
87 mod visit_lib;
88 mod test;
89 mod theme;
90
91 struct Output {
92     krate: clean::Crate,
93     renderinfo: html::render::RenderInfo,
94     renderopts: config::RenderOptions,
95     passes: Vec<String>,
96 }
97
98 pub fn main() {
99     let thread_stack_size: usize = if cfg!(target_os = "haiku") {
100         16_000_000 // 16MB on Haiku
101     } else {
102         32_000_000 // 32MB on other platforms
103     };
104     rustc_driver::set_sigpipe_handler();
105     env_logger::init();
106     let res = std::thread::Builder::new().stack_size(thread_stack_size).spawn(move || {
107         syntax::with_globals(move || {
108             get_args().map(|args| main_args(&args)).unwrap_or(1)
109         })
110     }).unwrap().join().unwrap_or(rustc_driver::EXIT_FAILURE);
111     process::exit(res as i32);
112 }
113
114 fn get_args() -> Option<Vec<String>> {
115     env::args_os().enumerate()
116         .map(|(i, arg)| arg.into_string().map_err(|arg| {
117              early_warn(ErrorOutputType::default(),
118                         &format!("Argument {} is not valid Unicode: {:?}", i, arg));
119         }).ok())
120         .collect()
121 }
122
123 fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
124     where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
125 {
126     RustcOptGroup::stable(name, f)
127 }
128
129 fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
130     where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
131 {
132     RustcOptGroup::unstable(name, f)
133 }
134
135 fn opts() -> Vec<RustcOptGroup> {
136     vec![
137         stable("h", |o| o.optflag("h", "help", "show this help message")),
138         stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
139         stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
140         stable("r", |o| {
141             o.optopt("r", "input-format", "the input type of the specified file",
142                      "[rust]")
143         }),
144         stable("w", |o| {
145             o.optopt("w", "output-format", "the output type to write", "[html]")
146         }),
147         stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
148         stable("crate-name", |o| {
149             o.optopt("", "crate-name", "specify the name of this crate", "NAME")
150         }),
151         stable("L", |o| {
152             o.optmulti("L", "library-path", "directory to add to crate search path",
153                        "DIR")
154         }),
155         stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
156         stable("extern", |o| {
157             o.optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH")
158         }),
159         unstable("extern-html-root-url", |o| {
160             o.optmulti("", "extern-html-root-url",
161                        "base URL to use for dependencies", "NAME=URL")
162         }),
163         stable("plugin-path", |o| {
164             o.optmulti("", "plugin-path", "removed", "DIR")
165         }),
166         stable("C", |o| {
167             o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
168         }),
169         stable("passes", |o| {
170             o.optmulti("", "passes",
171                        "list of passes to also run, you might want \
172                         to pass it multiple times; a value of `list` \
173                         will print available passes",
174                        "PASSES")
175         }),
176         stable("plugins", |o| {
177             o.optmulti("", "plugins", "removed",
178                        "PLUGINS")
179         }),
180         stable("no-default", |o| {
181             o.optflag("", "no-defaults", "don't run the default passes")
182         }),
183         stable("document-private-items", |o| {
184             o.optflag("", "document-private-items", "document private items")
185         }),
186         stable("test", |o| o.optflag("", "test", "run code examples as tests")),
187         stable("test-args", |o| {
188             o.optmulti("", "test-args", "arguments to pass to the test runner",
189                        "ARGS")
190         }),
191         stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
192         stable("markdown-css", |o| {
193             o.optmulti("", "markdown-css",
194                        "CSS files to include via <link> in a rendered Markdown file",
195                        "FILES")
196         }),
197         stable("html-in-header", |o|  {
198             o.optmulti("", "html-in-header",
199                        "files to include inline in the <head> section of a rendered Markdown file \
200                         or generated documentation",
201                        "FILES")
202         }),
203         stable("html-before-content", |o| {
204             o.optmulti("", "html-before-content",
205                        "files to include inline between <body> and the content of a rendered \
206                         Markdown file or generated documentation",
207                        "FILES")
208         }),
209         stable("html-after-content", |o| {
210             o.optmulti("", "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         unstable("markdown-before-content", |o| {
216             o.optmulti("", "markdown-before-content",
217                        "files to include inline between <body> and the content of a rendered \
218                         Markdown file or generated documentation",
219                        "FILES")
220         }),
221         unstable("markdown-after-content", |o| {
222             o.optmulti("", "markdown-after-content",
223                        "files to include inline between the content and </body> of a rendered \
224                         Markdown file or generated documentation",
225                        "FILES")
226         }),
227         stable("markdown-playground-url", |o| {
228             o.optopt("", "markdown-playground-url",
229                      "URL to send code snippets to", "URL")
230         }),
231         stable("markdown-no-toc", |o| {
232             o.optflag("", "markdown-no-toc", "don't include table of contents")
233         }),
234         stable("e", |o| {
235             o.optopt("e", "extend-css",
236                      "To add some CSS rules with a given file to generate doc with your \
237                       own theme. However, your theme might break if the rustdoc's generated HTML \
238                       changes, so be careful!", "PATH")
239         }),
240         unstable("Z", |o| {
241             o.optmulti("Z", "",
242                        "internal and debugging options (only on nightly build)", "FLAG")
243         }),
244         stable("sysroot", |o| {
245             o.optopt("", "sysroot", "Override the system root", "PATH")
246         }),
247         unstable("playground-url", |o| {
248             o.optopt("", "playground-url",
249                      "URL to send code snippets to, may be reset by --markdown-playground-url \
250                       or `#![doc(html_playground_url=...)]`",
251                      "URL")
252         }),
253         unstable("display-warnings", |o| {
254             o.optflag("", "display-warnings", "to print code warnings when testing doc")
255         }),
256         unstable("crate-version", |o| {
257             o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
258         }),
259         unstable("linker", |o| {
260             o.optopt("", "linker", "linker used for building executable test code", "PATH")
261         }),
262         unstable("sort-modules-by-appearance", |o| {
263             o.optflag("", "sort-modules-by-appearance", "sort modules by where they appear in the \
264                                                          program, rather than alphabetically")
265         }),
266         unstable("themes", |o| {
267             o.optmulti("", "themes",
268                        "additional themes which will be added to the generated docs",
269                        "FILES")
270         }),
271         unstable("theme-checker", |o| {
272             o.optmulti("", "theme-checker",
273                        "check if given theme is valid",
274                        "FILES")
275         }),
276         unstable("resource-suffix", |o| {
277             o.optopt("",
278                      "resource-suffix",
279                      "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
280                       \"light-suffix.css\"",
281                      "PATH")
282         }),
283         stable("edition", |o| {
284             o.optopt("", "edition",
285                      "edition to use when compiling rust code (default: 2015)",
286                      "EDITION")
287         }),
288         stable("color", |o| {
289             o.optopt("",
290                      "color",
291                      "Configure coloring of output:
292                                           auto   = colorize, if output goes to a tty (default);
293                                           always = always colorize output;
294                                           never  = never colorize output",
295                      "auto|always|never")
296         }),
297         stable("error-format", |o| {
298             o.optopt("",
299                      "error-format",
300                      "How errors and other messages are produced",
301                      "human|json|short")
302         }),
303         unstable("disable-minification", |o| {
304              o.optflag("",
305                        "disable-minification",
306                        "Disable minification applied on JS files")
307         }),
308         stable("warn", |o| {
309             o.optmulti("W", "warn", "Set lint warnings", "OPT")
310         }),
311         stable("allow", |o| {
312             o.optmulti("A", "allow", "Set lint allowed", "OPT")
313         }),
314         stable("deny", |o| {
315             o.optmulti("D", "deny", "Set lint denied", "OPT")
316         }),
317         stable("forbid", |o| {
318             o.optmulti("F", "forbid", "Set lint forbidden", "OPT")
319         }),
320         stable("cap-lints", |o| {
321             o.optmulti(
322                 "",
323                 "cap-lints",
324                 "Set the most restrictive lint level. \
325                  More restrictive lints are capped at this \
326                  level. By default, it is at `forbid` level.",
327                 "LEVEL",
328             )
329         }),
330         unstable("index-page", |o| {
331              o.optopt("",
332                       "index-page",
333                       "Markdown file to be used as index page",
334                       "PATH")
335         }),
336         unstable("enable-index-page", |o| {
337              o.optflag("",
338                        "enable-index-page",
339                        "To enable generation of the index page")
340         }),
341     ]
342 }
343
344 fn usage(argv0: &str) {
345     let mut options = getopts::Options::new();
346     for option in opts() {
347         (option.apply)(&mut options);
348     }
349     println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
350 }
351
352 fn main_args(args: &[String]) -> isize {
353     let mut options = getopts::Options::new();
354     for option in opts() {
355         (option.apply)(&mut options);
356     }
357     let matches = match options.parse(&args[1..]) {
358         Ok(m) => m,
359         Err(err) => {
360             early_error(ErrorOutputType::default(), &err.to_string());
361         }
362     };
363     let options = match config::Options::from_matches(&matches) {
364         Ok(opts) => opts,
365         Err(code) => return code,
366     };
367
368     let diag = core::new_handler(options.error_format,
369                                  None,
370                                  options.debugging_options.treat_err_as_bug,
371                                  options.debugging_options.ui_testing);
372
373     match (options.should_test, options.markdown_input()) {
374         (true, true) => return markdown::test(options, &diag),
375         (true, false) => return test::run(options),
376         (false, true) => return markdown::render(options.input, options.render_options, &diag),
377         (false, false) => {}
378     }
379
380     // need to move these items separately because we lose them by the time the closure is called,
381     // but we can't crates the Handler ahead of time because it's not Send
382     let diag_opts = (options.error_format,
383                      options.debugging_options.treat_err_as_bug,
384                      options.debugging_options.ui_testing);
385     rust_input(options, move |out| {
386         let Output { krate, passes, renderinfo, renderopts } = out;
387         info!("going to format");
388         let (error_format, treat_err_as_bug, ui_testing) = diag_opts;
389         let diag = core::new_handler(error_format, None, treat_err_as_bug, ui_testing);
390         match html::render::run(
391             krate,
392             renderopts,
393             passes.into_iter().collect(),
394             renderinfo,
395             &diag,
396         ) {
397             Ok(_) => rustc_driver::EXIT_SUCCESS,
398             Err(e) => {
399                 diag.struct_err(&format!("couldn't generate documentation: {}", e.error))
400                     .note(&format!("failed to create or modify \"{}\"", e.file.display()))
401                     .emit();
402                 rustc_driver::EXIT_FAILURE
403             }
404         }
405     })
406 }
407
408 /// Interprets the input file as a rust source file, passing it through the
409 /// compiler all the way through the analysis passes. The rustdoc output is then
410 /// generated from the cleaned AST of the crate.
411 ///
412 /// This form of input will run all of the plug/cleaning passes
413 fn rust_input<R, F>(options: config::Options, f: F) -> R
414 where R: 'static + Send,
415       F: 'static + Send + FnOnce(Output) -> R
416 {
417     // First, parse the crate and extract all relevant information.
418     info!("starting to run rustc");
419
420     let (tx, rx) = channel();
421
422     let result = rustc_driver::monitor(move || syntax::with_globals(move || {
423         let crate_name = options.crate_name.clone();
424         let crate_version = options.crate_version.clone();
425         let (mut krate, renderinfo, renderopts, passes) = core::run_core(options);
426
427         info!("finished with rustc");
428
429         if let Some(name) = crate_name {
430             krate.name = name
431         }
432
433         krate.version = crate_version;
434
435         info!("Executing passes");
436
437         for pass in &passes {
438             // determine if we know about this pass
439             let pass = match passes::find_pass(pass) {
440                 Some(pass) => if let Some(pass) = pass.late_fn() {
441                     pass
442                 } else {
443                     // not a late pass, but still valid so don't report the error
444                     continue
445                 }
446                 None => {
447                     error!("unknown pass {}, skipping", *pass);
448
449                     continue
450                 },
451             };
452
453             // run it
454             krate = pass(krate);
455         }
456
457         tx.send(f(Output {
458             krate: krate,
459             renderinfo: renderinfo,
460             renderopts,
461             passes: passes
462         })).unwrap();
463     }));
464
465     match result {
466         Ok(()) => rx.recv().unwrap(),
467         Err(_) => panic::resume_unwind(Box::new(errors::FatalErrorMarker)),
468     }
469 }