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