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