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