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