]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Rollup merge of #48258 - nrc:save-proc-nested, r=eddyb
[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 #![deny(warnings)]
16
17 #![feature(ascii_ctype)]
18 #![feature(rustc_private)]
19 #![feature(box_patterns)]
20 #![feature(box_syntax)]
21 #![feature(fs_read_write)]
22 #![feature(set_stdio)]
23 #![feature(slice_patterns)]
24 #![feature(test)]
25 #![feature(unicode)]
26 #![feature(vec_remove_item)]
27 #![feature(entry_and_modify)]
28
29 extern crate arena;
30 extern crate getopts;
31 extern crate env_logger;
32 extern crate rustc;
33 extern crate rustc_data_structures;
34 extern crate rustc_const_math;
35 extern crate rustc_trans_utils;
36 extern crate rustc_driver;
37 extern crate rustc_resolve;
38 extern crate rustc_lint;
39 extern crate rustc_back;
40 extern crate rustc_metadata;
41 extern crate rustc_typeck;
42 extern crate serialize;
43 #[macro_use] extern crate syntax;
44 extern crate syntax_pos;
45 extern crate test as testing;
46 extern crate std_unicode;
47 #[macro_use] extern crate log;
48 extern crate rustc_errors as errors;
49 extern crate pulldown_cmark;
50 extern crate tempdir;
51
52 extern crate serialize as rustc_serialize; // used by deriving
53
54 use std::collections::{BTreeMap, BTreeSet};
55 use std::default::Default;
56 use std::env;
57 use std::fmt::Display;
58 use std::io;
59 use std::io::Write;
60 use std::path::{Path, PathBuf};
61 use std::process;
62 use std::sync::mpsc::channel;
63
64 use externalfiles::ExternalHtml;
65 use rustc::session::search_paths::SearchPaths;
66 use rustc::session::config::{ErrorOutputType, RustcOptGroup, nightly_options, Externs};
67
68 #[macro_use]
69 pub mod externalfiles;
70
71 pub mod clean;
72 pub mod core;
73 pub mod doctree;
74 pub mod fold;
75 pub mod html {
76     pub mod highlight;
77     pub mod escape;
78     pub mod item_type;
79     pub mod format;
80     pub mod layout;
81     pub mod markdown;
82     pub mod render;
83     pub mod toc;
84 }
85 pub mod markdown;
86 pub mod passes;
87 pub mod plugins;
88 pub mod visit_ast;
89 pub mod visit_lib;
90 pub mod test;
91 pub mod theme;
92
93 use clean::AttributesExt;
94
95 struct Output {
96     krate: clean::Crate,
97     renderinfo: html::render::RenderInfo,
98     passes: Vec<String>,
99 }
100
101 pub fn main() {
102     const STACK_SIZE: usize = 32_000_000; // 32MB
103     env_logger::init().unwrap();
104     let res = std::thread::Builder::new().stack_size(STACK_SIZE).spawn(move || {
105         get_args().map(|args| main_args(&args)).unwrap_or(1)
106     }).unwrap().join().unwrap_or(101);
107     process::exit(res as i32);
108 }
109
110 fn get_args() -> Option<Vec<String>> {
111     env::args_os().enumerate()
112         .map(|(i, arg)| arg.into_string().map_err(|arg| {
113              print_error(format!("Argument {} is not valid Unicode: {:?}", i, arg));
114         }).ok())
115         .collect()
116 }
117
118 fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
119     where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
120 {
121     RustcOptGroup::stable(name, f)
122 }
123
124 fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
125     where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
126 {
127     RustcOptGroup::unstable(name, f)
128 }
129
130 pub fn opts() -> Vec<RustcOptGroup> {
131     vec![
132         stable("h", |o| o.optflag("h", "help", "show this help message")),
133         stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
134         stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
135         stable("r", |o| {
136             o.optopt("r", "input-format", "the input type of the specified file",
137                      "[rust]")
138         }),
139         stable("w", |o| {
140             o.optopt("w", "output-format", "the output type to write", "[html]")
141         }),
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         stable("L", |o| {
147             o.optmulti("L", "library-path", "directory to add to crate search path",
148                        "DIR")
149         }),
150         stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
151         stable("extern", |o| {
152             o.optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH")
153         }),
154         stable("plugin-path", |o| {
155             o.optmulti("", "plugin-path", "directory to load plugins from", "DIR")
156         }),
157         stable("passes", |o| {
158             o.optmulti("", "passes",
159                        "list of passes to also run, you might want \
160                         to pass it multiple times; a value of `list` \
161                         will print available passes",
162                        "PASSES")
163         }),
164         stable("plugins", |o| {
165             o.optmulti("", "plugins", "space separated list of plugins to also load",
166                        "PLUGINS")
167         }),
168         stable("no-default", |o| {
169             o.optflag("", "no-defaults", "don't run the default passes")
170         }),
171         stable("document-private-items", |o| {
172             o.optflag("", "document-private-items", "document private items")
173         }),
174         stable("test", |o| o.optflag("", "test", "run code examples as tests")),
175         stable("test-args", |o| {
176             o.optmulti("", "test-args", "arguments to pass to the test runner",
177                        "ARGS")
178         }),
179         stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
180         stable("markdown-css", |o| {
181             o.optmulti("", "markdown-css",
182                        "CSS files to include via <link> in a rendered Markdown file",
183                        "FILES")
184         }),
185         stable("html-in-header", |o|  {
186             o.optmulti("", "html-in-header",
187                        "files to include inline in the <head> section of a rendered Markdown file \
188                         or generated documentation",
189                        "FILES")
190         }),
191         stable("html-before-content", |o| {
192             o.optmulti("", "html-before-content",
193                        "files to include inline between <body> and the content of a rendered \
194                         Markdown file or generated documentation",
195                        "FILES")
196         }),
197         stable("html-after-content", |o| {
198             o.optmulti("", "html-after-content",
199                        "files to include inline between the content and </body> of a rendered \
200                         Markdown file or generated documentation",
201                        "FILES")
202         }),
203         unstable("markdown-before-content", |o| {
204             o.optmulti("", "markdown-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         unstable("markdown-after-content", |o| {
210             o.optmulti("", "markdown-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         stable("markdown-playground-url", |o| {
216             o.optopt("", "markdown-playground-url",
217                      "URL to send code snippets to", "URL")
218         }),
219         stable("markdown-no-toc", |o| {
220             o.optflag("", "markdown-no-toc", "don't include table of contents")
221         }),
222         stable("e", |o| {
223             o.optopt("e", "extend-css",
224                      "To add some CSS rules with a given file to generate doc with your \
225                       own theme. However, your theme might break if the rustdoc's generated HTML \
226                       changes, so be careful!", "PATH")
227         }),
228         unstable("Z", |o| {
229             o.optmulti("Z", "",
230                        "internal and debugging options (only on nightly build)", "FLAG")
231         }),
232         stable("sysroot", |o| {
233             o.optopt("", "sysroot", "Override the system root", "PATH")
234         }),
235         unstable("playground-url", |o| {
236             o.optopt("", "playground-url",
237                      "URL to send code snippets to, may be reset by --markdown-playground-url \
238                       or `#![doc(html_playground_url=...)]`",
239                      "URL")
240         }),
241         unstable("display-warnings", |o| {
242             o.optflag("", "display-warnings", "to print code warnings when testing doc")
243         }),
244         unstable("crate-version", |o| {
245             o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
246         }),
247         unstable("linker", |o| {
248             o.optopt("", "linker", "linker used for building executable test code", "PATH")
249         }),
250         unstable("sort-modules-by-appearance", |o| {
251             o.optflag("", "sort-modules-by-appearance", "sort modules by where they appear in the \
252                                                          program, rather than alphabetically")
253         }),
254         unstable("themes", |o| {
255             o.optmulti("", "themes",
256                        "additional themes which will be added to the generated docs",
257                        "FILES")
258         }),
259         unstable("theme-checker", |o| {
260             o.optmulti("", "theme-checker",
261                        "check if given theme is valid",
262                        "FILES")
263         }),
264     ]
265 }
266
267 pub fn usage(argv0: &str) {
268     let mut options = getopts::Options::new();
269     for option in opts() {
270         (option.apply)(&mut options);
271     }
272     println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
273 }
274
275 pub fn main_args(args: &[String]) -> isize {
276     let mut options = getopts::Options::new();
277     for option in opts() {
278         (option.apply)(&mut options);
279     }
280     let matches = match options.parse(&args[1..]) {
281         Ok(m) => m,
282         Err(err) => {
283             print_error(err);
284             return 1;
285         }
286     };
287     // Check for unstable options.
288     nightly_options::check_nightly_options(&matches, &opts());
289
290     // check for deprecated options
291     check_deprecated_options(&matches);
292
293     if matches.opt_present("h") || matches.opt_present("help") {
294         usage("rustdoc");
295         return 0;
296     } else if matches.opt_present("version") {
297         rustc_driver::version("rustdoc", &matches);
298         return 0;
299     }
300
301     if matches.opt_strs("passes") == ["list"] {
302         println!("Available passes for running rustdoc:");
303         for &(name, _, description) in passes::PASSES {
304             println!("{:>20} - {}", name, description);
305         }
306         println!("\nDefault passes for rustdoc:");
307         for &name in passes::DEFAULT_PASSES {
308             println!("{:>20}", name);
309         }
310         return 0;
311     }
312
313     let to_check = matches.opt_strs("theme-checker");
314     if !to_check.is_empty() {
315         let paths = theme::load_css_paths(include_bytes!("html/static/themes/main.css"));
316         let mut errors = 0;
317
318         println!("rustdoc: [theme-checker] Starting tests!");
319         for theme_file in to_check.iter() {
320             print!(" - Checking \"{}\"...", theme_file);
321             let (success, differences) = theme::test_theme_against(theme_file, &paths);
322             if !differences.is_empty() || !success {
323                 println!(" FAILED");
324                 errors += 1;
325                 if !differences.is_empty() {
326                     println!("{}", differences.join("\n"));
327                 }
328             } else {
329                 println!(" OK");
330             }
331         }
332         if errors != 0 {
333             return 1;
334         }
335         return 0;
336     }
337
338     if matches.free.is_empty() {
339         print_error("missing file operand");
340         return 1;
341     }
342     if matches.free.len() > 1 {
343         print_error("too many file operands");
344         return 1;
345     }
346     let input = &matches.free[0];
347
348     let mut libs = SearchPaths::new();
349     for s in &matches.opt_strs("L") {
350         libs.add_path(s, ErrorOutputType::default());
351     }
352     let externs = match parse_externs(&matches) {
353         Ok(ex) => ex,
354         Err(err) => {
355             print_error(err);
356             return 1;
357         }
358     };
359
360     let test_args = matches.opt_strs("test-args");
361     let test_args: Vec<String> = test_args.iter()
362                                           .flat_map(|s| s.split_whitespace())
363                                           .map(|s| s.to_string())
364                                           .collect();
365
366     let should_test = matches.opt_present("test");
367     let markdown_input = Path::new(input).extension()
368         .map_or(false, |e| e == "md" || e == "markdown");
369
370     let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
371     let css_file_extension = matches.opt_str("e").map(|s| PathBuf::from(&s));
372     let cfgs = matches.opt_strs("cfg");
373
374     if let Some(ref p) = css_file_extension {
375         if !p.is_file() {
376             writeln!(
377                 &mut io::stderr(),
378                 "rustdoc: option --extend-css argument must be a file."
379             ).unwrap();
380             return 1;
381         }
382     }
383
384     let mut themes = Vec::new();
385     if matches.opt_present("themes") {
386         let paths = theme::load_css_paths(include_bytes!("html/static/themes/main.css"));
387
388         for (theme_file, theme_s) in matches.opt_strs("themes")
389                                             .iter()
390                                             .map(|s| (PathBuf::from(&s), s.to_owned())) {
391             if !theme_file.is_file() {
392                 println!("rustdoc: option --themes arguments must all be files");
393                 return 1;
394             }
395             let (success, ret) = theme::test_theme_against(&theme_file, &paths);
396             if !success || !ret.is_empty() {
397                 println!("rustdoc: invalid theme: \"{}\"", theme_s);
398                 println!("         Check what's wrong with the \"theme-checker\" option");
399                 return 1;
400             }
401             themes.push(theme_file);
402         }
403     }
404
405     let external_html = match ExternalHtml::load(
406             &matches.opt_strs("html-in-header"),
407             &matches.opt_strs("html-before-content"),
408             &matches.opt_strs("html-after-content"),
409             &matches.opt_strs("markdown-before-content"),
410             &matches.opt_strs("markdown-after-content")) {
411         Some(eh) => eh,
412         None => return 3,
413     };
414     let crate_name = matches.opt_str("crate-name");
415     let playground_url = matches.opt_str("playground-url");
416     let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
417     let display_warnings = matches.opt_present("display-warnings");
418     let linker = matches.opt_str("linker").map(PathBuf::from);
419     let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
420
421     match (should_test, markdown_input) {
422         (true, true) => {
423             return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot,
424                                   display_warnings, linker)
425         }
426         (true, false) => {
427             return test::run(Path::new(input), cfgs, libs, externs, test_args, crate_name,
428                              maybe_sysroot, display_warnings, linker)
429         }
430         (false, true) => return markdown::render(Path::new(input),
431                                                  output.unwrap_or(PathBuf::from("doc")),
432                                                  &matches, &external_html,
433                                                  !matches.opt_present("markdown-no-toc")),
434         (false, false) => {}
435     }
436
437     let output_format = matches.opt_str("w");
438     let res = acquire_input(PathBuf::from(input), externs, &matches, move |out| {
439         let Output { krate, passes, renderinfo } = out;
440         info!("going to format");
441         match output_format.as_ref().map(|s| &**s) {
442             Some("html") | None => {
443                 html::render::run(krate, &external_html, playground_url,
444                                   output.unwrap_or(PathBuf::from("doc")),
445                                   passes.into_iter().collect(),
446                                   css_file_extension,
447                                   renderinfo,
448                                   sort_modules_alphabetically,
449                                   themes)
450                     .expect("failed to generate documentation");
451                 0
452             }
453             Some(s) => {
454                 print_error(format!("unknown output format: {}", s));
455                 1
456             }
457         }
458     });
459     res.unwrap_or_else(|s| {
460         print_error(format!("input error: {}", s));
461         1
462     })
463 }
464
465 /// Prints an uniformized error message on the standard error output
466 fn print_error<T>(error_message: T) where T: Display {
467     writeln!(
468         &mut io::stderr(),
469         "rustdoc: {}\nTry 'rustdoc --help' for more information.",
470         error_message
471     ).unwrap();
472 }
473
474 /// Looks inside the command line arguments to extract the relevant input format
475 /// and files and then generates the necessary rustdoc output for formatting.
476 fn acquire_input<R, F>(input: PathBuf,
477                        externs: Externs,
478                        matches: &getopts::Matches,
479                        f: F)
480                        -> Result<R, String>
481 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
482     match matches.opt_str("r").as_ref().map(|s| &**s) {
483         Some("rust") => Ok(rust_input(input, externs, matches, f)),
484         Some(s) => Err(format!("unknown input format: {}", s)),
485         None => Ok(rust_input(input, externs, matches, f))
486     }
487 }
488
489 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
490 /// returns a map mapping crate names to their paths or else an
491 /// error message.
492 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
493     let mut externs = BTreeMap::new();
494     for arg in &matches.opt_strs("extern") {
495         let mut parts = arg.splitn(2, '=');
496         let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
497         let location = parts.next()
498                                  .ok_or("--extern value must be of the format `foo=bar`"
499                                     .to_string())?;
500         let name = name.to_string();
501         externs.entry(name).or_insert_with(BTreeSet::new).insert(location.to_string());
502     }
503     Ok(Externs::new(externs))
504 }
505
506 /// Interprets the input file as a rust source file, passing it through the
507 /// compiler all the way through the analysis passes. The rustdoc output is then
508 /// generated from the cleaned AST of the crate.
509 ///
510 /// This form of input will run all of the plug/cleaning passes
511 fn rust_input<R, F>(cratefile: PathBuf, externs: Externs, matches: &getopts::Matches, f: F) -> R
512 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
513     let mut default_passes = !matches.opt_present("no-defaults");
514     let mut passes = matches.opt_strs("passes");
515     let mut plugins = matches.opt_strs("plugins");
516
517     // We hardcode in the passes here, as this is a new flag and we
518     // are generally deprecating passes.
519     if matches.opt_present("document-private-items") {
520         default_passes = false;
521
522         passes = vec![
523             String::from("collapse-docs"),
524             String::from("unindent-comments"),
525         ];
526     }
527
528     // First, parse the crate and extract all relevant information.
529     let mut paths = SearchPaths::new();
530     for s in &matches.opt_strs("L") {
531         paths.add_path(s, ErrorOutputType::default());
532     }
533     let cfgs = matches.opt_strs("cfg");
534     let triple = matches.opt_str("target");
535     let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
536     let crate_name = matches.opt_str("crate-name");
537     let crate_version = matches.opt_str("crate-version");
538     let plugin_path = matches.opt_str("plugin-path");
539
540     info!("starting to run rustc");
541     let display_warnings = matches.opt_present("display-warnings");
542
543     let force_unstable_if_unmarked = matches.opt_strs("Z").iter().any(|x| {
544         *x == "force-unstable-if-unmarked"
545     });
546
547     let (tx, rx) = channel();
548     rustc_driver::monitor(move || {
549         use rustc::session::config::Input;
550
551         let (mut krate, renderinfo) =
552             core::run_core(paths, cfgs, externs, Input::File(cratefile), triple, maybe_sysroot,
553                            display_warnings, crate_name.clone(),
554                            force_unstable_if_unmarked);
555
556         info!("finished with rustc");
557
558         if let Some(name) = crate_name {
559             krate.name = name
560         }
561
562         krate.version = crate_version;
563
564         // Process all of the crate attributes, extracting plugin metadata along
565         // with the passes which we are supposed to run.
566         for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
567             let name = attr.name().map(|s| s.as_str());
568             let name = name.as_ref().map(|s| &s[..]);
569             if attr.is_word() {
570                 if name == Some("no_default_passes") {
571                     default_passes = false;
572                 }
573             } else if let Some(value) = attr.value_str() {
574                 let sink = match name {
575                     Some("passes") => &mut passes,
576                     Some("plugins") => &mut plugins,
577                     _ => continue,
578                 };
579                 for p in value.as_str().split_whitespace() {
580                     sink.push(p.to_string());
581                 }
582             }
583         }
584
585         if default_passes {
586             for name in passes::DEFAULT_PASSES.iter().rev() {
587                 passes.insert(0, name.to_string());
588             }
589         }
590
591         // Load all plugins/passes into a PluginManager
592         let path = plugin_path.unwrap_or("/tmp/rustdoc/plugins".to_string());
593         let mut pm = plugins::PluginManager::new(PathBuf::from(path));
594         for pass in &passes {
595             let plugin = match passes::PASSES.iter()
596                                              .position(|&(p, ..)| {
597                                                  p == *pass
598                                              }) {
599                 Some(i) => passes::PASSES[i].1,
600                 None => {
601                     error!("unknown pass {}, skipping", *pass);
602                     continue
603                 },
604             };
605             pm.add_plugin(plugin);
606         }
607         info!("loading plugins...");
608         for pname in plugins {
609             pm.load_plugin(pname);
610         }
611
612         // Run everything!
613         info!("Executing passes/plugins");
614         let krate = pm.run_plugins(krate);
615
616         tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes })).unwrap();
617     });
618     rx.recv().unwrap()
619 }
620
621 /// Prints deprecation warnings for deprecated options
622 fn check_deprecated_options(matches: &getopts::Matches) {
623     let deprecated_flags = [
624        "input-format",
625        "output-format",
626        "plugin-path",
627        "plugins",
628        "no-defaults",
629        "passes",
630     ];
631
632     for flag in deprecated_flags.into_iter() {
633         if matches.opt_present(flag) {
634             eprintln!("WARNING: the '{}' flag is considered deprecated", flag);
635             eprintln!("WARNING: please see https://github.com/rust-lang/rust/issues/44136");
636         }
637     }
638
639     if matches.opt_present("no-defaults") {
640         eprintln!("WARNING: (you may want to use --document-private-items)");
641     }
642 }