]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Rollup merge of #41077 - petrochenkov:boundparen, r=nikomatsakis
[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 #![crate_name = "rustdoc"]
12 #![unstable(feature = "rustc_private", issue = "27812")]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16        html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
17        html_root_url = "https://doc.rust-lang.org/nightly/",
18        html_playground_url = "https://play.rust-lang.org/")]
19 #![deny(warnings)]
20
21 #![feature(box_patterns)]
22 #![feature(box_syntax)]
23 #![feature(libc)]
24 #![feature(rustc_private)]
25 #![feature(set_stdio)]
26 #![feature(slice_patterns)]
27 #![feature(staged_api)]
28 #![feature(test)]
29 #![feature(unicode)]
30 #![feature(vec_remove_item)]
31
32 extern crate arena;
33 extern crate getopts;
34 extern crate env_logger;
35 extern crate libc;
36 extern crate rustc;
37 extern crate rustc_data_structures;
38 extern crate rustc_trans;
39 extern crate rustc_driver;
40 extern crate rustc_resolve;
41 extern crate rustc_lint;
42 extern crate rustc_back;
43 extern crate rustc_metadata;
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
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::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 struct Output {
97     krate: clean::Crate,
98     renderinfo: html::render::RenderInfo,
99     passes: Vec<String>,
100 }
101
102 pub fn main() {
103     const STACK_SIZE: usize = 32_000_000; // 32MB
104     env_logger::init().unwrap();
105     let res = std::thread::Builder::new().stack_size(STACK_SIZE).spawn(move || {
106         let s = env::args().collect::<Vec<_>>();
107         main_args(&s)
108     }).unwrap().join().unwrap_or(101);
109     process::exit(res as i32);
110 }
111
112 fn stable(g: getopts::OptGroup) -> RustcOptGroup { RustcOptGroup::stable(g) }
113 fn unstable(g: getopts::OptGroup) -> RustcOptGroup { RustcOptGroup::unstable(g) }
114
115 pub fn opts() -> Vec<RustcOptGroup> {
116     use getopts::*;
117     vec![
118         stable(optflag("h", "help", "show this help message")),
119         stable(optflag("V", "version", "print rustdoc's version")),
120         stable(optflag("v", "verbose", "use verbose output")),
121         stable(optopt("r", "input-format", "the input type of the specified file",
122                       "[rust]")),
123         stable(optopt("w", "output-format", "the output type to write",
124                       "[html]")),
125         stable(optopt("o", "output", "where to place the output", "PATH")),
126         stable(optopt("", "crate-name", "specify the name of this crate", "NAME")),
127         stable(optmulti("L", "library-path", "directory to add to crate search path",
128                         "DIR")),
129         stable(optmulti("", "cfg", "pass a --cfg to rustc", "")),
130         stable(optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH")),
131         stable(optmulti("", "plugin-path", "directory to load plugins from", "DIR")),
132         stable(optmulti("", "passes",
133                         "list of passes to also run, you might want \
134                          to pass it multiple times; a value of `list` \
135                          will print available passes",
136                         "PASSES")),
137         stable(optmulti("", "plugins", "space separated list of plugins to also load",
138                         "PLUGINS")),
139         stable(optflag("", "no-defaults", "don't run the default passes")),
140         stable(optflag("", "test", "run code examples as tests")),
141         stable(optmulti("", "test-args", "arguments to pass to the test runner",
142                         "ARGS")),
143         stable(optopt("", "target", "target triple to document", "TRIPLE")),
144         stable(optmulti("", "markdown-css",
145                         "CSS files to include via <link> in a rendered Markdown file",
146                         "FILES")),
147         stable(optmulti("", "html-in-header",
148                         "files to include inline in the <head> section of a rendered Markdown file \
149                          or generated documentation",
150                         "FILES")),
151         stable(optmulti("", "html-before-content",
152                         "files to include inline between <body> and the content of a rendered \
153                          Markdown file or generated documentation",
154                         "FILES")),
155         stable(optmulti("", "html-after-content",
156                         "files to include inline between the content and </body> of a rendered \
157                          Markdown file or generated documentation",
158                         "FILES")),
159         stable(optopt("", "markdown-playground-url",
160                       "URL to send code snippets to", "URL")),
161         stable(optflag("", "markdown-no-toc", "don't include table of contents")),
162         unstable(optopt("e", "extend-css",
163                         "to redefine some css rules with a given file to generate doc with your \
164                          own theme", "PATH")),
165         unstable(optmulti("Z", "",
166                           "internal and debugging options (only on nightly build)", "FLAG")),
167         stable(optopt("", "sysroot", "Override the system root", "PATH")),
168         unstable(optopt("", "playground-url",
169                         "URL to send code snippets to, may be reset by --markdown-playground-url \
170                          or `#![doc(html_playground_url=...)]`",
171                         "URL")),
172     ]
173 }
174
175 pub fn usage(argv0: &str) {
176     println!("{}",
177              getopts::usage(&format!("{} [options] <input>", argv0),
178                             &opts().into_iter()
179                                    .map(|x| x.opt_group)
180                                    .collect::<Vec<getopts::OptGroup>>()));
181 }
182
183 pub fn main_args(args: &[String]) -> isize {
184     let all_groups: Vec<getopts::OptGroup> = opts()
185                                              .into_iter()
186                                              .map(|x| x.opt_group)
187                                              .collect();
188     let matches = match getopts::getopts(&args[1..], &all_groups) {
189         Ok(m) => m,
190         Err(err) => {
191             print_error(err);
192             return 1;
193         }
194     };
195     // Check for unstable options.
196     nightly_options::check_nightly_options(&matches, &opts());
197
198     if matches.opt_present("h") || matches.opt_present("help") {
199         usage("rustdoc");
200         return 0;
201     } else if matches.opt_present("version") {
202         rustc_driver::version("rustdoc", &matches);
203         return 0;
204     }
205
206     if matches.opt_strs("passes") == ["list"] {
207         println!("Available passes for running rustdoc:");
208         for &(name, _, description) in passes::PASSES {
209             println!("{:>20} - {}", name, description);
210         }
211         println!("\nDefault passes for rustdoc:");
212         for &name in passes::DEFAULT_PASSES {
213             println!("{:>20}", name);
214         }
215         return 0;
216     }
217
218     if matches.free.is_empty() {
219         print_error("missing file operand");
220         return 1;
221     }
222     if matches.free.len() > 1 {
223         print_error("too many file operands");
224         return 1;
225     }
226     let input = &matches.free[0];
227
228     let mut libs = SearchPaths::new();
229     for s in &matches.opt_strs("L") {
230         libs.add_path(s, ErrorOutputType::default());
231     }
232     let externs = match parse_externs(&matches) {
233         Ok(ex) => ex,
234         Err(err) => {
235             print_error(err);
236             return 1;
237         }
238     };
239
240     let test_args = matches.opt_strs("test-args");
241     let test_args: Vec<String> = test_args.iter()
242                                           .flat_map(|s| s.split_whitespace())
243                                           .map(|s| s.to_string())
244                                           .collect();
245
246     let should_test = matches.opt_present("test");
247     let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
248
249     let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
250     let css_file_extension = matches.opt_str("e").map(|s| PathBuf::from(&s));
251     let cfgs = matches.opt_strs("cfg");
252
253     if let Some(ref p) = css_file_extension {
254         if !p.is_file() {
255             writeln!(
256                 &mut io::stderr(),
257                 "rustdoc: option --extend-css argument must be a file."
258             ).unwrap();
259             return 1;
260         }
261     }
262
263     let external_html = match ExternalHtml::load(
264             &matches.opt_strs("html-in-header"),
265             &matches.opt_strs("html-before-content"),
266             &matches.opt_strs("html-after-content")) {
267         Some(eh) => eh,
268         None => return 3,
269     };
270     let crate_name = matches.opt_str("crate-name");
271     let playground_url = matches.opt_str("playground-url");
272     let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
273
274     match (should_test, markdown_input) {
275         (true, true) => {
276             return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot)
277         }
278         (true, false) => {
279             return test::run(input, cfgs, libs, externs, test_args, crate_name, maybe_sysroot)
280         }
281         (false, true) => return markdown::render(input,
282                                                  output.unwrap_or(PathBuf::from("doc")),
283                                                  &matches, &external_html,
284                                                  !matches.opt_present("markdown-no-toc")),
285         (false, false) => {}
286     }
287
288     let output_format = matches.opt_str("w");
289     let res = acquire_input(input, externs, &matches, move |out| {
290         let Output { krate, passes, renderinfo } = out;
291         info!("going to format");
292         match output_format.as_ref().map(|s| &**s) {
293             Some("html") | None => {
294                 html::render::run(krate, &external_html, playground_url,
295                                   output.unwrap_or(PathBuf::from("doc")),
296                                   passes.into_iter().collect(),
297                                   css_file_extension,
298                                   renderinfo)
299                     .expect("failed to generate documentation");
300                 0
301             }
302             Some(s) => {
303                 print_error(format!("unknown output format: {}", s));
304                 1
305             }
306         }
307     });
308     res.unwrap_or_else(|s| {
309         print_error(format!("input error: {}", s));
310         1
311     })
312 }
313
314 /// Prints an uniformised error message on the standard error output
315 fn print_error<T>(error_message: T) where T: Display {
316     writeln!(
317         &mut io::stderr(),
318         "rustdoc: {}\nTry 'rustdoc --help' for more information.",
319         error_message
320     ).unwrap();
321 }
322
323 /// Looks inside the command line arguments to extract the relevant input format
324 /// and files and then generates the necessary rustdoc output for formatting.
325 fn acquire_input<R, F>(input: &str,
326                        externs: Externs,
327                        matches: &getopts::Matches,
328                        f: F)
329                        -> Result<R, String>
330 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
331     match matches.opt_str("r").as_ref().map(|s| &**s) {
332         Some("rust") => Ok(rust_input(input, externs, matches, f)),
333         Some(s) => Err(format!("unknown input format: {}", s)),
334         None => Ok(rust_input(input, externs, matches, f))
335     }
336 }
337
338 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
339 /// returns a map mapping crate names to their paths or else an
340 /// error message.
341 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
342     let mut externs = BTreeMap::new();
343     for arg in &matches.opt_strs("extern") {
344         let mut parts = arg.splitn(2, '=');
345         let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
346         let location = parts.next()
347                                  .ok_or("--extern value must be of the format `foo=bar`"
348                                     .to_string())?;
349         let name = name.to_string();
350         externs.entry(name).or_insert_with(BTreeSet::new).insert(location.to_string());
351     }
352     Ok(Externs::new(externs))
353 }
354
355 /// Interprets the input file as a rust source file, passing it through the
356 /// compiler all the way through the analysis passes. The rustdoc output is then
357 /// generated from the cleaned AST of the crate.
358 ///
359 /// This form of input will run all of the plug/cleaning passes
360 fn rust_input<R, F>(cratefile: &str, externs: Externs, matches: &getopts::Matches, f: F) -> R
361 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
362     let mut default_passes = !matches.opt_present("no-defaults");
363     let mut passes = matches.opt_strs("passes");
364     let mut plugins = matches.opt_strs("plugins");
365
366     // First, parse the crate and extract all relevant information.
367     let mut paths = SearchPaths::new();
368     for s in &matches.opt_strs("L") {
369         paths.add_path(s, ErrorOutputType::default());
370     }
371     let cfgs = matches.opt_strs("cfg");
372     let triple = matches.opt_str("target");
373     let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
374     let crate_name = matches.opt_str("crate-name");
375     let plugin_path = matches.opt_str("plugin-path");
376
377     let cr = PathBuf::from(cratefile);
378     info!("starting to run rustc");
379
380     let (tx, rx) = channel();
381     rustc_driver::monitor(move || {
382         use rustc::session::config::Input;
383
384         let (mut krate, renderinfo) =
385             core::run_core(paths, cfgs, externs, Input::File(cr), triple, maybe_sysroot);
386
387         info!("finished with rustc");
388
389         if let Some(name) = crate_name {
390             krate.name = name
391         }
392
393         // Process all of the crate attributes, extracting plugin metadata along
394         // with the passes which we are supposed to run.
395         for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
396             let name = attr.name().map(|s| s.as_str());
397             let name = name.as_ref().map(|s| &s[..]);
398             if attr.is_word() {
399                 if name == Some("no_default_passes") {
400                     default_passes = false;
401                 }
402             } else if let Some(value) = attr.value_str() {
403                 let sink = match name {
404                     Some("passes") => &mut passes,
405                     Some("plugins") => &mut plugins,
406                     _ => continue,
407                 };
408                 for p in value.as_str().split_whitespace() {
409                     sink.push(p.to_string());
410                 }
411             }
412         }
413
414         if default_passes {
415             for name in passes::DEFAULT_PASSES.iter().rev() {
416                 passes.insert(0, name.to_string());
417             }
418         }
419
420         // Load all plugins/passes into a PluginManager
421         let path = plugin_path.unwrap_or("/tmp/rustdoc/plugins".to_string());
422         let mut pm = plugins::PluginManager::new(PathBuf::from(path));
423         for pass in &passes {
424             let plugin = match passes::PASSES.iter()
425                                              .position(|&(p, ..)| {
426                                                  p == *pass
427                                              }) {
428                 Some(i) => passes::PASSES[i].1,
429                 None => {
430                     error!("unknown pass {}, skipping", *pass);
431                     continue
432                 },
433             };
434             pm.add_plugin(plugin);
435         }
436         info!("loading plugins...");
437         for pname in plugins {
438             pm.load_plugin(pname);
439         }
440
441         // Run everything!
442         info!("Executing passes/plugins");
443         let krate = pm.run_plugins(krate);
444
445         tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes })).unwrap();
446     });
447     rx.recv().unwrap()
448 }