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 #![feature(ascii_ctype)]
17 #![feature(rustc_private)]
18 #![feature(box_patterns)]
19 #![feature(box_syntax)]
20 #![feature(fs_read_write)]
21 #![feature(iterator_find_map)]
22 #![feature(set_stdio)]
23 #![feature(slice_sort_by_cached_key)]
25 #![feature(vec_remove_item)]
26 #![feature(entry_and_modify)]
27 #![feature(ptr_offset_from)]
29 #![recursion_limit="256"]
33 extern crate env_logger;
35 extern crate rustc_data_structures;
36 extern crate rustc_codegen_utils;
37 extern crate rustc_driver;
38 extern crate rustc_resolve;
39 extern crate rustc_lint;
40 extern crate rustc_metadata;
41 extern crate rustc_target;
42 extern crate rustc_typeck;
43 extern crate serialize;
44 #[macro_use] extern crate syntax;
45 extern crate syntax_pos;
46 extern crate test as testing;
47 #[macro_use] extern crate log;
48 extern crate rustc_errors as errors;
49 extern crate pulldown_cmark;
50 extern crate tempfile;
51 extern crate minifier;
53 extern crate serialize as rustc_serialize; // used by deriving
55 use errors::ColorConfig;
57 use std::collections::{BTreeMap, BTreeSet};
58 use std::default::Default;
60 use std::path::{Path, PathBuf};
62 use std::sync::mpsc::channel;
64 use syntax::edition::Edition;
65 use externalfiles::ExternalHtml;
66 use rustc::session::{early_warn, early_error};
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 let thread_stack_size: usize = if cfg!(target_os = "haiku") {
107 16_000_000 // 16MB on Haiku
109 32_000_000 // 32MB on other platforms
111 rustc_driver::set_sigpipe_handler();
113 let res = std::thread::Builder::new().stack_size(thread_stack_size).spawn(move || {
114 syntax::with_globals(move || {
115 get_args().map(|args| main_args(&args)).unwrap_or(1)
117 }).unwrap().join().unwrap_or(101);
118 process::exit(res as i32);
121 fn get_args() -> Option<Vec<String>> {
122 env::args_os().enumerate()
123 .map(|(i, arg)| arg.into_string().map_err(|arg| {
124 early_warn(ErrorOutputType::default(),
125 &format!("Argument {} is not valid Unicode: {:?}", i, arg));
130 fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
131 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
133 RustcOptGroup::stable(name, f)
136 fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
137 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
139 RustcOptGroup::unstable(name, f)
142 pub fn opts() -> Vec<RustcOptGroup> {
144 stable("h", |o| o.optflag("h", "help", "show this help message")),
145 stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
146 stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
148 o.optopt("r", "input-format", "the input type of the specified file",
152 o.optopt("w", "output-format", "the output type to write", "[html]")
154 stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
155 stable("crate-name", |o| {
156 o.optopt("", "crate-name", "specify the name of this crate", "NAME")
159 o.optmulti("L", "library-path", "directory to add to crate search path",
162 stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
163 stable("extern", |o| {
164 o.optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH")
166 stable("plugin-path", |o| {
167 o.optmulti("", "plugin-path", "directory to load plugins from", "DIR")
170 o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
172 stable("passes", |o| {
173 o.optmulti("", "passes",
174 "list of passes to also run, you might want \
175 to pass it multiple times; a value of `list` \
176 will print available passes",
179 stable("plugins", |o| {
180 o.optmulti("", "plugins", "space separated list of plugins to also load",
183 stable("no-default", |o| {
184 o.optflag("", "no-defaults", "don't run the default passes")
186 stable("document-private-items", |o| {
187 o.optflag("", "document-private-items", "document private items")
189 stable("test", |o| o.optflag("", "test", "run code examples as tests")),
190 stable("test-args", |o| {
191 o.optmulti("", "test-args", "arguments to pass to the test runner",
194 stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
195 stable("markdown-css", |o| {
196 o.optmulti("", "markdown-css",
197 "CSS files to include via <link> in a rendered Markdown file",
200 stable("html-in-header", |o| {
201 o.optmulti("", "html-in-header",
202 "files to include inline in the <head> section of a rendered Markdown file \
203 or generated documentation",
206 stable("html-before-content", |o| {
207 o.optmulti("", "html-before-content",
208 "files to include inline between <body> and the content of a rendered \
209 Markdown file or generated documentation",
212 stable("html-after-content", |o| {
213 o.optmulti("", "html-after-content",
214 "files to include inline between the content and </body> of a rendered \
215 Markdown file or generated documentation",
218 unstable("markdown-before-content", |o| {
219 o.optmulti("", "markdown-before-content",
220 "files to include inline between <body> and the content of a rendered \
221 Markdown file or generated documentation",
224 unstable("markdown-after-content", |o| {
225 o.optmulti("", "markdown-after-content",
226 "files to include inline between the content and </body> of a rendered \
227 Markdown file or generated documentation",
230 stable("markdown-playground-url", |o| {
231 o.optopt("", "markdown-playground-url",
232 "URL to send code snippets to", "URL")
234 stable("markdown-no-toc", |o| {
235 o.optflag("", "markdown-no-toc", "don't include table of contents")
238 o.optopt("e", "extend-css",
239 "To add some CSS rules with a given file to generate doc with your \
240 own theme. However, your theme might break if the rustdoc's generated HTML \
241 changes, so be careful!", "PATH")
245 "internal and debugging options (only on nightly build)", "FLAG")
247 stable("sysroot", |o| {
248 o.optopt("", "sysroot", "Override the system root", "PATH")
250 unstable("playground-url", |o| {
251 o.optopt("", "playground-url",
252 "URL to send code snippets to, may be reset by --markdown-playground-url \
253 or `#![doc(html_playground_url=...)]`",
256 unstable("display-warnings", |o| {
257 o.optflag("", "display-warnings", "to print code warnings when testing doc")
259 unstable("crate-version", |o| {
260 o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
262 unstable("linker", |o| {
263 o.optopt("", "linker", "linker used for building executable test code", "PATH")
265 unstable("sort-modules-by-appearance", |o| {
266 o.optflag("", "sort-modules-by-appearance", "sort modules by where they appear in the \
267 program, rather than alphabetically")
269 unstable("themes", |o| {
270 o.optmulti("", "themes",
271 "additional themes which will be added to the generated docs",
274 unstable("theme-checker", |o| {
275 o.optmulti("", "theme-checker",
276 "check if given theme is valid",
279 unstable("resource-suffix", |o| {
282 "suffix to add to CSS and JavaScript files, e.g. \"light.css\" will become \
283 \"light-suffix.css\"",
286 unstable("edition", |o| {
287 o.optopt("", "edition",
288 "edition to use when compiling rust code (default: 2015)",
291 unstable("color", |o| {
294 "Configure coloring of output:
295 auto = colorize, if output goes to a tty (default);
296 always = always colorize output;
297 never = never colorize output",
300 unstable("error-format", |o| {
303 "How errors and other messages are produced",
306 unstable("disable-minification", |o| {
308 "disable-minification",
309 "Disable minification applied on JS files")
314 pub fn usage(argv0: &str) {
315 let mut options = getopts::Options::new();
316 for option in opts() {
317 (option.apply)(&mut options);
319 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
322 pub fn main_args(args: &[String]) -> isize {
323 let mut options = getopts::Options::new();
324 for option in opts() {
325 (option.apply)(&mut options);
327 let matches = match options.parse(&args[1..]) {
330 early_error(ErrorOutputType::default(), &err.to_string());
333 // Check for unstable options.
334 nightly_options::check_nightly_options(&matches, &opts());
336 if matches.opt_present("h") || matches.opt_present("help") {
339 } else if matches.opt_present("version") {
340 rustc_driver::version("rustdoc", &matches);
344 if matches.opt_strs("passes") == ["list"] {
345 println!("Available passes for running rustdoc:");
346 for &(name, _, description) in passes::PASSES {
347 println!("{:>20} - {}", name, description);
349 println!("\nDefault passes for rustdoc:");
350 for &name in passes::DEFAULT_PASSES {
351 println!("{:>20}", name);
356 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
357 Some("auto") => ColorConfig::Auto,
358 Some("always") => ColorConfig::Always,
359 Some("never") => ColorConfig::Never,
360 None => ColorConfig::Auto,
362 early_error(ErrorOutputType::default(),
363 &format!("argument for --color must be `auto`, `always` or `never` \
364 (instead was `{}`)", arg));
367 let error_format = match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
368 Some("human") => ErrorOutputType::HumanReadable(color),
369 Some("json") => ErrorOutputType::Json(false),
370 Some("pretty-json") => ErrorOutputType::Json(true),
371 Some("short") => ErrorOutputType::Short(color),
372 None => ErrorOutputType::HumanReadable(color),
374 early_error(ErrorOutputType::default(),
375 &format!("argument for --error-format must be `human`, `json` or \
376 `short` (instead was `{}`)", arg));
380 let diag = core::new_handler(error_format, None);
382 // check for deprecated options
383 check_deprecated_options(&matches, &diag);
385 let to_check = matches.opt_strs("theme-checker");
386 if !to_check.is_empty() {
387 let paths = theme::load_css_paths(include_bytes!("html/static/themes/light.css"));
390 println!("rustdoc: [theme-checker] Starting tests!");
391 for theme_file in to_check.iter() {
392 print!(" - Checking \"{}\"...", theme_file);
393 let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag);
394 if !differences.is_empty() || !success {
397 if !differences.is_empty() {
398 println!("{}", differences.join("\n"));
410 if matches.free.is_empty() {
411 diag.struct_err("missing file operand").emit();
414 if matches.free.len() > 1 {
415 diag.struct_err("too many file operands").emit();
418 let input = &matches.free[0];
420 let mut libs = SearchPaths::new();
421 for s in &matches.opt_strs("L") {
422 libs.add_path(s, error_format);
424 let externs = match parse_externs(&matches) {
427 diag.struct_err(&err.to_string()).emit();
432 let test_args = matches.opt_strs("test-args");
433 let test_args: Vec<String> = test_args.iter()
434 .flat_map(|s| s.split_whitespace())
435 .map(|s| s.to_string())
438 let should_test = matches.opt_present("test");
439 let markdown_input = Path::new(input).extension()
440 .map_or(false, |e| e == "md" || e == "markdown");
442 let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
443 let css_file_extension = matches.opt_str("e").map(|s| PathBuf::from(&s));
444 let cfgs = matches.opt_strs("cfg");
446 if let Some(ref p) = css_file_extension {
448 diag.struct_err("option --extend-css argument must be a file").emit();
453 let mut themes = Vec::new();
454 if matches.opt_present("themes") {
455 let paths = theme::load_css_paths(include_bytes!("html/static/themes/light.css"));
457 for (theme_file, theme_s) in matches.opt_strs("themes")
459 .map(|s| (PathBuf::from(&s), s.to_owned())) {
460 if !theme_file.is_file() {
461 diag.struct_err("option --themes arguments must all be files").emit();
464 let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
465 if !success || !ret.is_empty() {
466 diag.struct_err(&format!("invalid theme: \"{}\"", theme_s))
467 .help("check what's wrong with the --theme-checker option")
471 themes.push(theme_file);
475 let external_html = match ExternalHtml::load(
476 &matches.opt_strs("html-in-header"),
477 &matches.opt_strs("html-before-content"),
478 &matches.opt_strs("html-after-content"),
479 &matches.opt_strs("markdown-before-content"),
480 &matches.opt_strs("markdown-after-content"), &diag) {
484 let crate_name = matches.opt_str("crate-name");
485 let playground_url = matches.opt_str("playground-url");
486 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
487 let display_warnings = matches.opt_present("display-warnings");
488 let linker = matches.opt_str("linker").map(PathBuf::from);
489 let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
490 let resource_suffix = matches.opt_str("resource-suffix");
491 let enable_minification = !matches.opt_present("disable-minification");
493 let edition = matches.opt_str("edition").unwrap_or("2015".to_string());
494 let edition = match edition.parse() {
497 diag.struct_err("could not parse edition").emit();
502 let cg = build_codegen_options(&matches, ErrorOutputType::default());
504 match (should_test, markdown_input) {
506 return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot,
507 display_warnings, linker, edition, cg, &diag)
510 return test::run(Path::new(input), cfgs, libs, externs, test_args, crate_name,
511 maybe_sysroot, display_warnings, linker, edition, cg)
513 (false, true) => return markdown::render(Path::new(input),
514 output.unwrap_or(PathBuf::from("doc")),
515 &matches, &external_html,
516 !matches.opt_present("markdown-no-toc"), &diag),
520 let output_format = matches.opt_str("w");
522 let res = acquire_input(PathBuf::from(input), externs, edition, cg, &matches, error_format,
524 let Output { krate, passes, renderinfo } = out;
525 let diag = core::new_handler(error_format, None);
526 info!("going to format");
527 match output_format.as_ref().map(|s| &**s) {
528 Some("html") | None => {
529 html::render::run(krate, &external_html, playground_url,
530 output.unwrap_or(PathBuf::from("doc")),
531 resource_suffix.unwrap_or(String::new()),
532 passes.into_iter().collect(),
535 sort_modules_alphabetically,
538 .expect("failed to generate documentation");
542 diag.struct_err(&format!("unknown output format: {}", s)).emit();
547 res.unwrap_or_else(|s| {
548 diag.struct_err(&format!("input error: {}", s)).emit();
553 /// Looks inside the command line arguments to extract the relevant input format
554 /// and files and then generates the necessary rustdoc output for formatting.
555 fn acquire_input<R, F>(input: PathBuf,
559 matches: &getopts::Matches,
560 error_format: ErrorOutputType,
563 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
564 match matches.opt_str("r").as_ref().map(|s| &**s) {
565 Some("rust") => Ok(rust_input(input, externs, edition, cg, matches, error_format, f)),
566 Some(s) => Err(format!("unknown input format: {}", s)),
567 None => Ok(rust_input(input, externs, edition, cg, matches, error_format, f))
571 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
572 /// returns a map mapping crate names to their paths or else an
574 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
575 let mut externs = BTreeMap::new();
576 for arg in &matches.opt_strs("extern") {
577 let mut parts = arg.splitn(2, '=');
578 let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
579 let location = parts.next()
580 .ok_or("--extern value must be of the format `foo=bar`"
582 let name = name.to_string();
583 externs.entry(name).or_insert_with(BTreeSet::new).insert(location.to_string());
585 Ok(Externs::new(externs))
588 /// Interprets the input file as a rust source file, passing it through the
589 /// compiler all the way through the analysis passes. The rustdoc output is then
590 /// generated from the cleaned AST of the crate.
592 /// This form of input will run all of the plug/cleaning passes
593 fn rust_input<R, F>(cratefile: PathBuf,
597 matches: &getopts::Matches,
598 error_format: ErrorOutputType,
600 where R: 'static + Send,
601 F: 'static + Send + FnOnce(Output) -> R
603 let mut default_passes = !matches.opt_present("no-defaults");
604 let mut passes = matches.opt_strs("passes");
605 let mut plugins = matches.opt_strs("plugins");
607 // We hardcode in the passes here, as this is a new flag and we
608 // are generally deprecating passes.
609 if matches.opt_present("document-private-items") {
610 default_passes = false;
613 String::from("collapse-docs"),
614 String::from("unindent-comments"),
618 // First, parse the crate and extract all relevant information.
619 let mut paths = SearchPaths::new();
620 for s in &matches.opt_strs("L") {
621 paths.add_path(s, ErrorOutputType::default());
623 let cfgs = matches.opt_strs("cfg");
624 let triple = matches.opt_str("target").map(|target| {
625 if target.ends_with(".json") {
626 TargetTriple::TargetPath(PathBuf::from(target))
628 TargetTriple::TargetTriple(target)
631 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
632 let crate_name = matches.opt_str("crate-name");
633 let crate_version = matches.opt_str("crate-version");
634 let plugin_path = matches.opt_str("plugin-path");
636 info!("starting to run rustc");
637 let display_warnings = matches.opt_present("display-warnings");
639 let force_unstable_if_unmarked = matches.opt_strs("Z").iter().any(|x| {
640 *x == "force-unstable-if-unmarked"
643 let (tx, rx) = channel();
645 rustc_driver::monitor(move || syntax::with_globals(move || {
646 use rustc::session::config::Input;
648 let (mut krate, renderinfo) =
649 core::run_core(paths, cfgs, externs, Input::File(cratefile), triple, maybe_sysroot,
650 display_warnings, crate_name.clone(),
651 force_unstable_if_unmarked, edition, cg, error_format);
653 info!("finished with rustc");
655 if let Some(name) = crate_name {
659 krate.version = crate_version;
661 let diag = core::new_handler(error_format, None);
663 fn report_deprecated_attr(name: &str, diag: &errors::Handler) {
664 let mut msg = diag.struct_warn(&format!("the `#![doc({})]` attribute is \
665 considered deprecated", name));
666 msg.warn("please see https://github.com/rust-lang/rust/issues/44136");
668 if name == "no_default_passes" {
669 msg.help("you may want to use `#![doc(document_private_items)]`");
675 // Process all of the crate attributes, extracting plugin metadata along
676 // with the passes which we are supposed to run.
677 for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
678 let name = attr.name().map(|s| s.as_str());
679 let name = name.as_ref().map(|s| &s[..]);
681 if name == Some("no_default_passes") {
682 report_deprecated_attr("no_default_passes", &diag);
683 default_passes = false;
685 } else if let Some(value) = attr.value_str() {
686 let sink = match name {
688 report_deprecated_attr("passes = \"...\"", &diag);
692 report_deprecated_attr("plugins = \"...\"", &diag);
697 for p in value.as_str().split_whitespace() {
698 sink.push(p.to_string());
702 if attr.is_word() && name == Some("document_private_items") {
703 default_passes = false;
706 String::from("collapse-docs"),
707 String::from("unindent-comments"),
713 for name in passes::DEFAULT_PASSES.iter().rev() {
714 passes.insert(0, name.to_string());
718 // Load all plugins/passes into a PluginManager
719 let path = plugin_path.unwrap_or("/tmp/rustdoc/plugins".to_string());
720 let mut pm = plugins::PluginManager::new(PathBuf::from(path));
721 for pass in &passes {
722 let plugin = match passes::PASSES.iter()
723 .position(|&(p, ..)| {
726 Some(i) => passes::PASSES[i].1,
728 error!("unknown pass {}, skipping", *pass);
732 pm.add_plugin(plugin);
734 info!("loading plugins...");
735 for pname in plugins {
736 pm.load_plugin(pname);
740 info!("Executing passes/plugins");
741 let krate = pm.run_plugins(krate);
743 tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes })).unwrap();
748 /// Prints deprecation warnings for deprecated options
749 fn check_deprecated_options(matches: &getopts::Matches, diag: &errors::Handler) {
750 let deprecated_flags = [
759 for flag in deprecated_flags.into_iter() {
760 if matches.opt_present(flag) {
761 let mut err = diag.struct_warn(&format!("the '{}' flag is considered deprecated",
763 err.warn("please see https://github.com/rust-lang/rust/issues/44136");
765 if *flag == "no-defaults" {
766 err.help("you may want to use --document-private-items");