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