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