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.
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.
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))]
21 #![feature(box_patterns)]
22 #![feature(box_syntax)]
24 #![feature(rustc_private)]
25 #![feature(set_stdio)]
26 #![feature(slice_patterns)]
27 #![feature(staged_api)]
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;
52 extern crate serialize as rustc_serialize; // used by deriving
54 use std::collections::{BTreeMap, BTreeSet};
55 use std::default::Default;
57 use std::path::PathBuf;
59 use std::sync::mpsc::channel;
61 use externalfiles::ExternalHtml;
62 use rustc::session::search_paths::SearchPaths;
63 use rustc::session::config::{ErrorOutputType, RustcOptGroup, nightly_options,
67 pub mod externalfiles;
90 use clean::AttributesExt;
94 renderinfo: html::render::RenderInfo,
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<_>>();
103 }).unwrap().join().unwrap_or(101);
104 process::exit(res as i32);
107 fn stable(g: getopts::OptGroup) -> RustcOptGroup { RustcOptGroup::stable(g) }
108 fn unstable(g: getopts::OptGroup) -> RustcOptGroup { RustcOptGroup::unstable(g) }
110 pub fn opts() -> Vec<RustcOptGroup> {
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",
118 stable(optopt("w", "output-format", "the output type to write",
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",
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",
132 stable(optmulti("", "plugins", "space separated list of plugins to also load",
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",
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",
142 stable(optmulti("", "html-in-header",
143 "files to include inline in the <head> section of a rendered Markdown file \
144 or generated documentation",
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",
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",
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=...)]`",
170 pub fn usage(argv0: &str) {
172 getopts::usage(&format!("{} [options] <input>", argv0),
174 .map(|x| x.opt_group)
175 .collect::<Vec<getopts::OptGroup>>()));
178 pub fn main_args(args: &[String]) -> isize {
179 let all_groups: Vec<getopts::OptGroup> = opts()
181 .map(|x| x.opt_group)
183 let matches = match getopts::getopts(&args[1..], &all_groups) {
190 // Check for unstable options.
191 nightly_options::check_nightly_options(&matches, &opts());
193 if matches.opt_present("h") || matches.opt_present("help") {
196 } else if matches.opt_present("version") {
197 rustc_driver::version("rustdoc", &matches);
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);
206 println!("\nDefault passes for rustdoc:");
207 for &name in passes::DEFAULT_PASSES {
208 println!("{:>20}", name);
213 if matches.free.is_empty() {
214 println!("expected an input file to act on");
217 if matches.free.len() > 1 {
218 println!("only one input file may be specified");
221 let input = &matches.free[0];
223 let mut libs = SearchPaths::new();
224 for s in &matches.opt_strs("L") {
225 libs.add_path(s, ErrorOutputType::default());
227 let externs = match parse_externs(&matches) {
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())
241 let should_test = matches.opt_present("test");
242 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
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");
248 if let Some(ref p) = css_file_extension {
250 println!("{}", "--extend-css option must take a css file as input");
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")) {
262 let crate_name = matches.opt_str("crate-name");
263 let playground_url = matches.opt_str("playground-url");
265 match (should_test, markdown_input) {
267 return markdown::test(input, cfgs, libs, externs, test_args)
270 return test::run(input, cfgs, libs, externs, test_args, crate_name)
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")),
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(),
290 .expect("failed to generate documentation");
294 println!("unknown output format: {}", s);
299 res.unwrap_or_else(|s| {
300 println!("input error: {}", s);
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,
309 matches: &getopts::Matches,
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))
320 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
321 /// returns a map mapping crate names to their paths or else an
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`"
331 let name = name.to_string();
332 externs.entry(name).or_insert_with(BTreeSet::new).insert(location.to_string());
334 Ok(Externs::new(externs))
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.
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");
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());
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");
359 let cr = PathBuf::from(cratefile);
360 info!("starting to run rustc");
362 let (tx, rx) = channel();
363 rustc_driver::monitor(move || {
364 use rustc::session::config::Input;
366 let (mut krate, renderinfo) =
367 core::run_core(paths, cfgs, externs, Input::File(cr), triple, maybe_sysroot);
369 info!("finished with rustc");
371 if let Some(name) = crate_name {
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[..]);
381 if name == Some("no_default_passes") {
382 default_passes = false;
384 } else if let Some(value) = attr.value_str() {
385 let sink = match name {
386 Some("passes") => &mut passes,
387 Some("plugins") => &mut plugins,
390 for p in value.as_str().split_whitespace() {
391 sink.push(p.to_string());
397 for name in passes::DEFAULT_PASSES.iter().rev() {
398 passes.insert(0, name.to_string());
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, ..)| {
410 Some(i) => passes::PASSES[i].1,
412 error!("unknown pass {}, skipping", *pass);
416 pm.add_plugin(plugin);
418 info!("loading plugins...");
419 for pname in plugins {
420 pm.load_plugin(pname);
424 info!("Executing passes/plugins");
425 let krate = pm.run_plugins(krate);
427 tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes })).unwrap();