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 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
12 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
13 html_root_url = "https://doc.rust-lang.org/nightly/",
14 html_playground_url = "https://play.rust-lang.org/")]
17 #![feature(ascii_ctype)]
18 #![feature(rustc_private)]
19 #![feature(box_patterns)]
20 #![feature(box_syntax)]
21 #![feature(fs_read_write)]
23 #![feature(set_stdio)]
24 #![feature(slice_patterns)]
27 #![feature(vec_remove_item)]
31 extern crate env_logger;
32 extern crate html_diff;
35 extern crate rustc_data_structures;
36 extern crate rustc_const_math;
37 extern crate rustc_trans_utils;
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 rustc_typeck;
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;
54 extern crate serialize as rustc_serialize; // used by deriving
56 use std::collections::{BTreeMap, BTreeSet};
57 use std::default::Default;
59 use std::fmt::Display;
62 use std::path::{Path, PathBuf};
64 use std::sync::mpsc::channel;
66 use rustc_driver::rustc_trans;
68 use externalfiles::ExternalHtml;
69 use rustc::session::search_paths::SearchPaths;
70 use rustc::session::config::{ErrorOutputType, RustcOptGroup, nightly_options,
74 pub mod externalfiles;
97 use clean::AttributesExt;
99 use html::markdown::RenderType;
103 renderinfo: html::render::RenderInfo,
108 const STACK_SIZE: usize = 32_000_000; // 32MB
109 env_logger::init().unwrap();
110 let res = std::thread::Builder::new().stack_size(STACK_SIZE).spawn(move || {
111 get_args().map(|args| main_args(&args)).unwrap_or(1)
112 }).unwrap().join().unwrap_or(101);
113 process::exit(res as i32);
116 fn get_args() -> Option<Vec<String>> {
117 env::args_os().enumerate()
118 .map(|(i, arg)| arg.into_string().map_err(|arg| {
119 print_error(format!("Argument {} is not valid Unicode: {:?}", i, arg));
124 fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
125 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
127 RustcOptGroup::stable(name, f)
130 fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
131 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
133 RustcOptGroup::unstable(name, f)
136 pub fn opts() -> Vec<RustcOptGroup> {
138 stable("h", |o| o.optflag("h", "help", "show this help message")),
139 stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
140 stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
142 o.optopt("r", "input-format", "the input type of the specified file",
146 o.optopt("w", "output-format", "the output type to write", "[html]")
148 stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
149 stable("crate-name", |o| {
150 o.optopt("", "crate-name", "specify the name of this crate", "NAME")
153 o.optmulti("L", "library-path", "directory to add to crate search path",
156 stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
157 stable("extern", |o| {
158 o.optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH")
160 stable("plugin-path", |o| {
161 o.optmulti("", "plugin-path", "directory to load plugins from", "DIR")
163 stable("passes", |o| {
164 o.optmulti("", "passes",
165 "list of passes to also run, you might want \
166 to pass it multiple times; a value of `list` \
167 will print available passes",
170 stable("plugins", |o| {
171 o.optmulti("", "plugins", "space separated list of plugins to also load",
174 stable("no-default", |o| {
175 o.optflag("", "no-defaults", "don't run the default passes")
177 stable("document-private-items", |o| {
178 o.optflag("", "document-private-items", "document private items")
180 stable("test", |o| o.optflag("", "test", "run code examples as tests")),
181 stable("test-args", |o| {
182 o.optmulti("", "test-args", "arguments to pass to the test runner",
185 stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
186 stable("markdown-css", |o| {
187 o.optmulti("", "markdown-css",
188 "CSS files to include via <link> in a rendered Markdown file",
191 stable("html-in-header", |o| {
192 o.optmulti("", "html-in-header",
193 "files to include inline in the <head> section of a rendered Markdown file \
194 or generated documentation",
197 stable("html-before-content", |o| {
198 o.optmulti("", "html-before-content",
199 "files to include inline between <body> and the content of a rendered \
200 Markdown file or generated documentation",
203 stable("html-after-content", |o| {
204 o.optmulti("", "html-after-content",
205 "files to include inline between the content and </body> of a rendered \
206 Markdown file or generated documentation",
209 unstable("markdown-before-content", |o| {
210 o.optmulti("", "markdown-before-content",
211 "files to include inline between <body> and the content of a rendered \
212 Markdown file or generated documentation",
215 unstable("markdown-after-content", |o| {
216 o.optmulti("", "markdown-after-content",
217 "files to include inline between the content and </body> of a rendered \
218 Markdown file or generated documentation",
221 stable("markdown-playground-url", |o| {
222 o.optopt("", "markdown-playground-url",
223 "URL to send code snippets to", "URL")
225 stable("markdown-no-toc", |o| {
226 o.optflag("", "markdown-no-toc", "don't include table of contents")
229 o.optopt("e", "extend-css",
230 "To add some CSS rules with a given file to generate doc with your \
231 own theme. However, your theme might break if the rustdoc's generated HTML \
232 changes, so be careful!", "PATH")
236 "internal and debugging options (only on nightly build)", "FLAG")
238 stable("sysroot", |o| {
239 o.optopt("", "sysroot", "Override the system root", "PATH")
241 unstable("playground-url", |o| {
242 o.optopt("", "playground-url",
243 "URL to send code snippets to, may be reset by --markdown-playground-url \
244 or `#![doc(html_playground_url=...)]`",
247 unstable("disable-commonmark", |o| {
248 o.optflag("", "disable-commonmark", "to disable commonmark doc rendering/testing")
250 unstable("display-warnings", |o| {
251 o.optflag("", "display-warnings", "to print code warnings when testing doc")
253 unstable("crate-version", |o| {
254 o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
256 unstable("linker", |o| {
257 o.optopt("", "linker", "linker used for building executable test code", "PATH")
259 unstable("sort-modules-by-appearance", |o| {
260 o.optflag("", "sort-modules-by-appearance", "sort modules by where they appear in the \
261 program, rather than alphabetically")
263 unstable("deny-render-differences", |o| {
264 o.optflag("", "deny-render-differences", "abort doc runs when markdown rendering \
265 differences are found")
270 pub fn usage(argv0: &str) {
271 let mut options = getopts::Options::new();
272 for option in opts() {
273 (option.apply)(&mut options);
275 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
278 pub fn main_args(args: &[String]) -> isize {
279 let mut options = getopts::Options::new();
280 for option in opts() {
281 (option.apply)(&mut options);
283 let matches = match options.parse(&args[1..]) {
290 // Check for unstable options.
291 nightly_options::check_nightly_options(&matches, &opts());
293 // check for deprecated options
294 check_deprecated_options(&matches);
296 if matches.opt_present("h") || matches.opt_present("help") {
299 } else if matches.opt_present("version") {
300 rustc_driver::version("rustdoc", &matches);
304 if matches.opt_strs("passes") == ["list"] {
305 println!("Available passes for running rustdoc:");
306 for &(name, _, description) in passes::PASSES {
307 println!("{:>20} - {}", name, description);
309 println!("\nDefault passes for rustdoc:");
310 for &name in passes::DEFAULT_PASSES {
311 println!("{:>20}", name);
316 if matches.free.is_empty() {
317 print_error("missing file operand");
320 if matches.free.len() > 1 {
321 print_error("too many file operands");
324 let input = &matches.free[0];
326 let mut libs = SearchPaths::new();
327 for s in &matches.opt_strs("L") {
328 libs.add_path(s, ErrorOutputType::default());
330 let externs = match parse_externs(&matches) {
338 let test_args = matches.opt_strs("test-args");
339 let test_args: Vec<String> = test_args.iter()
340 .flat_map(|s| s.split_whitespace())
341 .map(|s| s.to_string())
344 let should_test = matches.opt_present("test");
345 let markdown_input = Path::new(input).extension()
346 .map_or(false, |e| e == "md" || e == "markdown");
348 let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
349 let css_file_extension = matches.opt_str("e").map(|s| PathBuf::from(&s));
350 let cfgs = matches.opt_strs("cfg");
352 let render_type = if matches.opt_present("disable-commonmark") {
358 if let Some(ref p) = css_file_extension {
362 "rustdoc: option --extend-css argument must be a file."
368 let external_html = match ExternalHtml::load(
369 &matches.opt_strs("html-in-header"),
370 &matches.opt_strs("html-before-content"),
371 &matches.opt_strs("html-after-content"),
372 &matches.opt_strs("markdown-before-content"),
373 &matches.opt_strs("markdown-after-content"),
378 let crate_name = matches.opt_str("crate-name");
379 let playground_url = matches.opt_str("playground-url");
380 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
381 let display_warnings = matches.opt_present("display-warnings");
382 let linker = matches.opt_str("linker").map(PathBuf::from);
383 let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
385 match (should_test, markdown_input) {
387 return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot,
388 render_type, display_warnings, linker)
391 return test::run(Path::new(input), cfgs, libs, externs, test_args, crate_name,
392 maybe_sysroot, render_type, display_warnings, linker)
394 (false, true) => return markdown::render(Path::new(input),
395 output.unwrap_or(PathBuf::from("doc")),
396 &matches, &external_html,
397 !matches.opt_present("markdown-no-toc"),
402 let output_format = matches.opt_str("w");
403 let deny_render_differences = matches.opt_present("deny-render-differences");
404 let res = acquire_input(PathBuf::from(input), externs, &matches, move |out| {
405 let Output { krate, passes, renderinfo } = out;
406 info!("going to format");
407 match output_format.as_ref().map(|s| &**s) {
408 Some("html") | None => {
409 html::render::run(krate, &external_html, playground_url,
410 output.unwrap_or(PathBuf::from("doc")),
411 passes.into_iter().collect(),
415 sort_modules_alphabetically,
416 deny_render_differences)
417 .expect("failed to generate documentation");
421 print_error(format!("unknown output format: {}", s));
426 res.unwrap_or_else(|s| {
427 print_error(format!("input error: {}", s));
432 /// Prints an uniformized error message on the standard error output
433 fn print_error<T>(error_message: T) where T: Display {
436 "rustdoc: {}\nTry 'rustdoc --help' for more information.",
441 /// Looks inside the command line arguments to extract the relevant input format
442 /// and files and then generates the necessary rustdoc output for formatting.
443 fn acquire_input<R, F>(input: PathBuf,
445 matches: &getopts::Matches,
448 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
449 match matches.opt_str("r").as_ref().map(|s| &**s) {
450 Some("rust") => Ok(rust_input(input, externs, matches, f)),
451 Some(s) => Err(format!("unknown input format: {}", s)),
452 None => Ok(rust_input(input, externs, matches, f))
456 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
457 /// returns a map mapping crate names to their paths or else an
459 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
460 let mut externs = BTreeMap::new();
461 for arg in &matches.opt_strs("extern") {
462 let mut parts = arg.splitn(2, '=');
463 let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
464 let location = parts.next()
465 .ok_or("--extern value must be of the format `foo=bar`"
467 let name = name.to_string();
468 externs.entry(name).or_insert_with(BTreeSet::new).insert(location.to_string());
470 Ok(Externs::new(externs))
473 /// Interprets the input file as a rust source file, passing it through the
474 /// compiler all the way through the analysis passes. The rustdoc output is then
475 /// generated from the cleaned AST of the crate.
477 /// This form of input will run all of the plug/cleaning passes
478 fn rust_input<R, F>(cratefile: PathBuf, externs: Externs, matches: &getopts::Matches, f: F) -> R
479 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
480 let mut default_passes = !matches.opt_present("no-defaults");
481 let mut passes = matches.opt_strs("passes");
482 let mut plugins = matches.opt_strs("plugins");
484 // We hardcode in the passes here, as this is a new flag and we
485 // are generally deprecating passes.
486 if matches.opt_present("document-private-items") {
487 default_passes = false;
490 String::from("collapse-docs"),
491 String::from("unindent-comments"),
495 // First, parse the crate and extract all relevant information.
496 let mut paths = SearchPaths::new();
497 for s in &matches.opt_strs("L") {
498 paths.add_path(s, ErrorOutputType::default());
500 let cfgs = matches.opt_strs("cfg");
501 let triple = matches.opt_str("target");
502 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
503 let crate_name = matches.opt_str("crate-name");
504 let crate_version = matches.opt_str("crate-version");
505 let plugin_path = matches.opt_str("plugin-path");
506 let render_type = if matches.opt_present("enable-commonmark") {
512 info!("starting to run rustc");
513 let display_warnings = matches.opt_present("display-warnings");
515 let force_unstable_if_unmarked = matches.opt_strs("Z").iter().any(|x| {
516 *x == "force-unstable-if-unmarked"
519 let (tx, rx) = channel();
520 rustc_driver::monitor(move || {
521 use rustc::session::config::Input;
523 let (mut krate, renderinfo) =
524 core::run_core(paths, cfgs, externs, Input::File(cratefile), triple, maybe_sysroot,
525 display_warnings, force_unstable_if_unmarked, render_type);
527 info!("finished with rustc");
529 if let Some(name) = crate_name {
533 krate.version = crate_version;
535 // Process all of the crate attributes, extracting plugin metadata along
536 // with the passes which we are supposed to run.
537 for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
538 let name = attr.name().map(|s| s.as_str());
539 let name = name.as_ref().map(|s| &s[..]);
541 if name == Some("no_default_passes") {
542 default_passes = false;
544 } else if let Some(value) = attr.value_str() {
545 let sink = match name {
546 Some("passes") => &mut passes,
547 Some("plugins") => &mut plugins,
550 for p in value.as_str().split_whitespace() {
551 sink.push(p.to_string());
557 for name in passes::DEFAULT_PASSES.iter().rev() {
558 passes.insert(0, name.to_string());
562 // Load all plugins/passes into a PluginManager
563 let path = plugin_path.unwrap_or("/tmp/rustdoc/plugins".to_string());
564 let mut pm = plugins::PluginManager::new(PathBuf::from(path));
565 for pass in &passes {
566 let plugin = match passes::PASSES.iter()
567 .position(|&(p, ..)| {
570 Some(i) => passes::PASSES[i].1,
572 error!("unknown pass {}, skipping", *pass);
576 pm.add_plugin(plugin);
578 info!("loading plugins...");
579 for pname in plugins {
580 pm.load_plugin(pname);
584 info!("Executing passes/plugins");
585 let krate = pm.run_plugins(krate);
587 tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes })).unwrap();
592 /// Prints deprecation warnings for deprecated options
593 fn check_deprecated_options(matches: &getopts::Matches) {
594 let deprecated_flags = [
603 for flag in deprecated_flags.into_iter() {
604 if matches.opt_present(flag) {
605 eprintln!("WARNING: the '{}' flag is considered deprecated", flag);
606 eprintln!("WARNING: please see https://github.com/rust-lang/rust/issues/44136");
610 if matches.opt_present("no-defaults") {
611 eprintln!("WARNING: (you may want to use --document-private-items)");