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/")]
16 #![cfg_attr(stage0, feature(dyn_trait))]
18 #![feature(ascii_ctype)]
19 #![feature(rustc_private)]
20 #![feature(box_patterns)]
21 #![feature(box_syntax)]
22 #![feature(fs_read_write)]
23 #![feature(set_stdio)]
24 #![feature(slice_sort_by_cached_key)]
26 #![feature(vec_remove_item)]
27 #![feature(entry_and_modify)]
31 extern crate env_logger;
33 extern crate rustc_data_structures;
34 extern crate rustc_const_math;
35 extern crate rustc_trans_utils;
36 extern crate rustc_driver;
37 extern crate rustc_resolve;
38 extern crate rustc_lint;
39 extern crate rustc_metadata;
40 extern crate rustc_target;
41 extern crate rustc_typeck;
42 extern crate serialize;
43 #[macro_use] extern crate syntax;
44 extern crate syntax_pos;
45 extern crate test as testing;
46 #[macro_use] extern crate log;
47 extern crate rustc_errors as errors;
48 extern crate pulldown_cmark;
51 extern crate serialize as rustc_serialize; // used by deriving
53 use errors::ColorConfig;
55 use std::collections::{BTreeMap, BTreeSet};
56 use std::default::Default;
58 use std::fmt::Display;
61 use std::path::{Path, PathBuf};
63 use std::sync::mpsc::channel;
65 use syntax::edition::Edition;
66 use externalfiles::ExternalHtml;
67 use rustc::session::search_paths::SearchPaths;
68 use rustc::session::config::{ErrorOutputType, RustcOptGroup, Externs, CodegenOptions};
69 use rustc::session::config::{nightly_options, build_codegen_options};
70 use rustc_target::spec::TargetTriple;
73 pub mod externalfiles;
97 use clean::AttributesExt;
101 renderinfo: html::render::RenderInfo,
106 const STACK_SIZE: usize = 32_000_000; // 32MB
107 rustc_driver::set_sigpipe_handler();
109 let res = std::thread::Builder::new().stack_size(STACK_SIZE).spawn(move || {
110 syntax::with_globals(move || {
111 get_args().map(|args| main_args(&args)).unwrap_or(1)
113 }).unwrap().join().unwrap_or(101);
114 process::exit(res as i32);
117 fn get_args() -> Option<Vec<String>> {
118 env::args_os().enumerate()
119 .map(|(i, arg)| arg.into_string().map_err(|arg| {
120 print_error(format!("Argument {} is not valid Unicode: {:?}", i, arg));
125 fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
126 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
128 RustcOptGroup::stable(name, f)
131 fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
132 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
134 RustcOptGroup::unstable(name, f)
137 pub fn opts() -> Vec<RustcOptGroup> {
139 stable("h", |o| o.optflag("h", "help", "show this help message")),
140 stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
141 stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
143 o.optopt("r", "input-format", "the input type of the specified file",
147 o.optopt("w", "output-format", "the output type to write", "[html]")
149 stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
150 stable("crate-name", |o| {
151 o.optopt("", "crate-name", "specify the name of this crate", "NAME")
154 o.optmulti("L", "library-path", "directory to add to crate search path",
157 stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
158 stable("extern", |o| {
159 o.optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH")
161 stable("plugin-path", |o| {
162 o.optmulti("", "plugin-path", "directory to load plugins from", "DIR")
165 o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
167 stable("passes", |o| {
168 o.optmulti("", "passes",
169 "list of passes to also run, you might want \
170 to pass it multiple times; a value of `list` \
171 will print available passes",
174 stable("plugins", |o| {
175 o.optmulti("", "plugins", "space separated list of plugins to also load",
178 stable("no-default", |o| {
179 o.optflag("", "no-defaults", "don't run the default passes")
181 stable("document-private-items", |o| {
182 o.optflag("", "document-private-items", "document private items")
184 stable("test", |o| o.optflag("", "test", "run code examples as tests")),
185 stable("test-args", |o| {
186 o.optmulti("", "test-args", "arguments to pass to the test runner",
189 stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
190 stable("markdown-css", |o| {
191 o.optmulti("", "markdown-css",
192 "CSS files to include via <link> in a rendered Markdown file",
195 stable("html-in-header", |o| {
196 o.optmulti("", "html-in-header",
197 "files to include inline in the <head> section of a rendered Markdown file \
198 or generated documentation",
201 stable("html-before-content", |o| {
202 o.optmulti("", "html-before-content",
203 "files to include inline between <body> and the content of a rendered \
204 Markdown file or generated documentation",
207 stable("html-after-content", |o| {
208 o.optmulti("", "html-after-content",
209 "files to include inline between the content and </body> of a rendered \
210 Markdown file or generated documentation",
213 unstable("markdown-before-content", |o| {
214 o.optmulti("", "markdown-before-content",
215 "files to include inline between <body> and the content of a rendered \
216 Markdown file or generated documentation",
219 unstable("markdown-after-content", |o| {
220 o.optmulti("", "markdown-after-content",
221 "files to include inline between the content and </body> of a rendered \
222 Markdown file or generated documentation",
225 stable("markdown-playground-url", |o| {
226 o.optopt("", "markdown-playground-url",
227 "URL to send code snippets to", "URL")
229 stable("markdown-no-toc", |o| {
230 o.optflag("", "markdown-no-toc", "don't include table of contents")
233 o.optopt("e", "extend-css",
234 "To add some CSS rules with a given file to generate doc with your \
235 own theme. However, your theme might break if the rustdoc's generated HTML \
236 changes, so be careful!", "PATH")
240 "internal and debugging options (only on nightly build)", "FLAG")
242 stable("sysroot", |o| {
243 o.optopt("", "sysroot", "Override the system root", "PATH")
245 unstable("playground-url", |o| {
246 o.optopt("", "playground-url",
247 "URL to send code snippets to, may be reset by --markdown-playground-url \
248 or `#![doc(html_playground_url=...)]`",
251 unstable("display-warnings", |o| {
252 o.optflag("", "display-warnings", "to print code warnings when testing doc")
254 unstable("crate-version", |o| {
255 o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
257 unstable("linker", |o| {
258 o.optopt("", "linker", "linker used for building executable test code", "PATH")
260 unstable("sort-modules-by-appearance", |o| {
261 o.optflag("", "sort-modules-by-appearance", "sort modules by where they appear in the \
262 program, rather than alphabetically")
264 unstable("themes", |o| {
265 o.optmulti("", "themes",
266 "additional themes which will be added to the generated docs",
269 unstable("theme-checker", |o| {
270 o.optmulti("", "theme-checker",
271 "check if given theme is valid",
274 unstable("resource-suffix", |o| {
277 "suffix to add to CSS and JavaScript files, e.g. \"light.css\" will become \
278 \"light-suffix.css\"",
281 unstable("edition", |o| {
282 o.optopt("", "edition",
283 "edition to use when compiling rust code (default: 2015)",
286 unstable("color", |o| {
289 "Configure coloring of output:
290 auto = colorize, if output goes to a tty (default);
291 always = always colorize output;
292 never = never colorize output",
295 unstable("error-format", |o| {
298 "How errors and other messages are produced",
304 pub fn usage(argv0: &str) {
305 let mut options = getopts::Options::new();
306 for option in opts() {
307 (option.apply)(&mut options);
309 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
312 pub fn main_args(args: &[String]) -> isize {
313 let mut options = getopts::Options::new();
314 for option in opts() {
315 (option.apply)(&mut options);
317 let matches = match options.parse(&args[1..]) {
324 // Check for unstable options.
325 nightly_options::check_nightly_options(&matches, &opts());
327 // check for deprecated options
328 check_deprecated_options(&matches);
330 if matches.opt_present("h") || matches.opt_present("help") {
333 } else if matches.opt_present("version") {
334 rustc_driver::version("rustdoc", &matches);
338 if matches.opt_strs("passes") == ["list"] {
339 println!("Available passes for running rustdoc:");
340 for &(name, _, description) in passes::PASSES {
341 println!("{:>20} - {}", name, description);
343 println!("\nDefault passes for rustdoc:");
344 for &name in passes::DEFAULT_PASSES {
345 println!("{:>20}", name);
350 let to_check = matches.opt_strs("theme-checker");
351 if !to_check.is_empty() {
352 let paths = theme::load_css_paths(include_bytes!("html/static/themes/light.css"));
355 println!("rustdoc: [theme-checker] Starting tests!");
356 for theme_file in to_check.iter() {
357 print!(" - Checking \"{}\"...", theme_file);
358 let (success, differences) = theme::test_theme_against(theme_file, &paths);
359 if !differences.is_empty() || !success {
362 if !differences.is_empty() {
363 println!("{}", differences.join("\n"));
375 if matches.free.is_empty() {
376 print_error("missing file operand");
379 if matches.free.len() > 1 {
380 print_error("too many file operands");
383 let input = &matches.free[0];
385 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
386 Some("auto") => ColorConfig::Auto,
387 Some("always") => ColorConfig::Always,
388 Some("never") => ColorConfig::Never,
389 None => ColorConfig::Auto,
391 print_error(&format!("argument for --color must be `auto`, `always` or `never` \
392 (instead was `{}`)", arg));
396 let error_format = match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
397 Some("human") => ErrorOutputType::HumanReadable(color),
398 Some("json") => ErrorOutputType::Json(false),
399 Some("pretty-json") => ErrorOutputType::Json(true),
400 Some("short") => ErrorOutputType::Short(color),
401 None => ErrorOutputType::HumanReadable(color),
403 print_error(&format!("argument for --error-format must be `human`, `json` or \
404 `short` (instead was `{}`)", arg));
409 let mut libs = SearchPaths::new();
410 for s in &matches.opt_strs("L") {
411 libs.add_path(s, error_format);
413 let externs = match parse_externs(&matches) {
421 let test_args = matches.opt_strs("test-args");
422 let test_args: Vec<String> = test_args.iter()
423 .flat_map(|s| s.split_whitespace())
424 .map(|s| s.to_string())
427 let should_test = matches.opt_present("test");
428 let markdown_input = Path::new(input).extension()
429 .map_or(false, |e| e == "md" || e == "markdown");
431 let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
432 let css_file_extension = matches.opt_str("e").map(|s| PathBuf::from(&s));
433 let cfgs = matches.opt_strs("cfg");
435 if let Some(ref p) = css_file_extension {
439 "rustdoc: option --extend-css argument must be a file."
445 let mut themes = Vec::new();
446 if matches.opt_present("themes") {
447 let paths = theme::load_css_paths(include_bytes!("html/static/themes/light.css"));
449 for (theme_file, theme_s) in matches.opt_strs("themes")
451 .map(|s| (PathBuf::from(&s), s.to_owned())) {
452 if !theme_file.is_file() {
453 println!("rustdoc: option --themes arguments must all be files");
456 let (success, ret) = theme::test_theme_against(&theme_file, &paths);
457 if !success || !ret.is_empty() {
458 println!("rustdoc: invalid theme: \"{}\"", theme_s);
459 println!(" Check what's wrong with the \"theme-checker\" option");
462 themes.push(theme_file);
466 let external_html = match ExternalHtml::load(
467 &matches.opt_strs("html-in-header"),
468 &matches.opt_strs("html-before-content"),
469 &matches.opt_strs("html-after-content"),
470 &matches.opt_strs("markdown-before-content"),
471 &matches.opt_strs("markdown-after-content")) {
475 let crate_name = matches.opt_str("crate-name");
476 let playground_url = matches.opt_str("playground-url");
477 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
478 let display_warnings = matches.opt_present("display-warnings");
479 let linker = matches.opt_str("linker").map(PathBuf::from);
480 let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
481 let resource_suffix = matches.opt_str("resource-suffix");
483 let edition = matches.opt_str("edition").unwrap_or("2015".to_string());
484 let edition = match edition.parse() {
487 print_error("could not parse edition");
492 let cg = build_codegen_options(&matches, ErrorOutputType::default());
494 match (should_test, markdown_input) {
496 return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot,
497 display_warnings, linker, edition, cg)
500 return test::run(Path::new(input), cfgs, libs, externs, test_args, crate_name,
501 maybe_sysroot, display_warnings, linker, edition, cg)
503 (false, true) => return markdown::render(Path::new(input),
504 output.unwrap_or(PathBuf::from("doc")),
505 &matches, &external_html,
506 !matches.opt_present("markdown-no-toc")),
510 let output_format = matches.opt_str("w");
512 let res = acquire_input(PathBuf::from(input), externs, edition, cg, &matches, error_format,
514 let Output { krate, passes, renderinfo } = out;
515 info!("going to format");
516 match output_format.as_ref().map(|s| &**s) {
517 Some("html") | None => {
518 html::render::run(krate, &external_html, playground_url,
519 output.unwrap_or(PathBuf::from("doc")),
520 resource_suffix.unwrap_or(String::new()),
521 passes.into_iter().collect(),
524 sort_modules_alphabetically,
526 .expect("failed to generate documentation");
530 print_error(format!("unknown output format: {}", s));
535 res.unwrap_or_else(|s| {
536 print_error(format!("input error: {}", s));
541 /// Prints an uniformized error message on the standard error output
542 fn print_error<T>(error_message: T) where T: Display {
545 "rustdoc: {}\nTry 'rustdoc --help' for more information.",
550 /// Looks inside the command line arguments to extract the relevant input format
551 /// and files and then generates the necessary rustdoc output for formatting.
552 fn acquire_input<R, F>(input: PathBuf,
556 matches: &getopts::Matches,
557 error_format: ErrorOutputType,
560 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
561 match matches.opt_str("r").as_ref().map(|s| &**s) {
562 Some("rust") => Ok(rust_input(input, externs, edition, cg, matches, error_format, f)),
563 Some(s) => Err(format!("unknown input format: {}", s)),
564 None => Ok(rust_input(input, externs, edition, cg, matches, error_format, f))
568 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
569 /// returns a map mapping crate names to their paths or else an
571 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
572 let mut externs = BTreeMap::new();
573 for arg in &matches.opt_strs("extern") {
574 let mut parts = arg.splitn(2, '=');
575 let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
576 let location = parts.next()
577 .ok_or("--extern value must be of the format `foo=bar`"
579 let name = name.to_string();
580 externs.entry(name).or_insert_with(BTreeSet::new).insert(location.to_string());
582 Ok(Externs::new(externs))
585 /// Interprets the input file as a rust source file, passing it through the
586 /// compiler all the way through the analysis passes. The rustdoc output is then
587 /// generated from the cleaned AST of the crate.
589 /// This form of input will run all of the plug/cleaning passes
590 fn rust_input<R, F>(cratefile: PathBuf,
594 matches: &getopts::Matches,
595 error_format: ErrorOutputType,
597 where R: 'static + Send,
598 F: 'static + Send + FnOnce(Output) -> R
600 let mut default_passes = !matches.opt_present("no-defaults");
601 let mut passes = matches.opt_strs("passes");
602 let mut plugins = matches.opt_strs("plugins");
604 // We hardcode in the passes here, as this is a new flag and we
605 // are generally deprecating passes.
606 if matches.opt_present("document-private-items") {
607 default_passes = false;
610 String::from("collapse-docs"),
611 String::from("unindent-comments"),
615 // First, parse the crate and extract all relevant information.
616 let mut paths = SearchPaths::new();
617 for s in &matches.opt_strs("L") {
618 paths.add_path(s, ErrorOutputType::default());
620 let cfgs = matches.opt_strs("cfg");
621 let triple = matches.opt_str("target").map(|target| {
622 if target.ends_with(".json") {
623 TargetTriple::TargetPath(PathBuf::from(target))
625 TargetTriple::TargetTriple(target)
628 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
629 let crate_name = matches.opt_str("crate-name");
630 let crate_version = matches.opt_str("crate-version");
631 let plugin_path = matches.opt_str("plugin-path");
633 info!("starting to run rustc");
634 let display_warnings = matches.opt_present("display-warnings");
636 let force_unstable_if_unmarked = matches.opt_strs("Z").iter().any(|x| {
637 *x == "force-unstable-if-unmarked"
640 let (tx, rx) = channel();
642 rustc_driver::monitor(move || syntax::with_globals(move || {
643 use rustc::session::config::Input;
645 let (mut krate, renderinfo) =
646 core::run_core(paths, cfgs, externs, Input::File(cratefile), triple, maybe_sysroot,
647 display_warnings, crate_name.clone(),
648 force_unstable_if_unmarked, edition, cg, error_format);
650 info!("finished with rustc");
652 if let Some(name) = crate_name {
656 krate.version = crate_version;
658 // Process all of the crate attributes, extracting plugin metadata along
659 // with the passes which we are supposed to run.
660 for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
661 let name = attr.name().map(|s| s.as_str());
662 let name = name.as_ref().map(|s| &s[..]);
664 if name == Some("no_default_passes") {
665 default_passes = false;
667 } else if let Some(value) = attr.value_str() {
668 let sink = match name {
669 Some("passes") => &mut passes,
670 Some("plugins") => &mut plugins,
673 for p in value.as_str().split_whitespace() {
674 sink.push(p.to_string());
680 for name in passes::DEFAULT_PASSES.iter().rev() {
681 passes.insert(0, name.to_string());
685 // Load all plugins/passes into a PluginManager
686 let path = plugin_path.unwrap_or("/tmp/rustdoc/plugins".to_string());
687 let mut pm = plugins::PluginManager::new(PathBuf::from(path));
688 for pass in &passes {
689 let plugin = match passes::PASSES.iter()
690 .position(|&(p, ..)| {
693 Some(i) => passes::PASSES[i].1,
695 error!("unknown pass {}, skipping", *pass);
699 pm.add_plugin(plugin);
701 info!("loading plugins...");
702 for pname in plugins {
703 pm.load_plugin(pname);
707 info!("Executing passes/plugins");
708 let krate = pm.run_plugins(krate);
710 tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes })).unwrap();
715 /// Prints deprecation warnings for deprecated options
716 fn check_deprecated_options(matches: &getopts::Matches) {
717 let deprecated_flags = [
726 for flag in deprecated_flags.into_iter() {
727 if matches.opt_present(flag) {
728 eprintln!("WARNING: the '{}' flag is considered deprecated", flag);
729 eprintln!("WARNING: please see https://github.com/rust-lang/rust/issues/44136");
733 if matches.opt_present("no-defaults") {
734 eprintln!("WARNING: (you may want to use --document-private-items)");