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