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;
71 use rustc::session::config::get_cmd_lint_options;
74 pub mod externalfiles;
98 use clean::AttributesExt;
102 renderinfo: html::render::RenderInfo,
107 let thread_stack_size: usize = if cfg!(target_os = "haiku") {
108 16_000_000 // 16MB on Haiku
110 32_000_000 // 32MB on other platforms
112 rustc_driver::set_sigpipe_handler();
114 let res = std::thread::Builder::new().stack_size(thread_stack_size).spawn(move || {
115 syntax::with_globals(move || {
116 get_args().map(|args| main_args(&args)).unwrap_or(1)
118 }).unwrap().join().unwrap_or(101);
119 process::exit(res as i32);
122 fn get_args() -> Option<Vec<String>> {
123 env::args_os().enumerate()
124 .map(|(i, arg)| arg.into_string().map_err(|arg| {
125 early_warn(ErrorOutputType::default(),
126 &format!("Argument {} is not valid Unicode: {:?}", i, arg));
131 fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
132 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
134 RustcOptGroup::stable(name, f)
137 fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
138 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
140 RustcOptGroup::unstable(name, f)
143 pub fn opts() -> Vec<RustcOptGroup> {
145 stable("h", |o| o.optflag("h", "help", "show this help message")),
146 stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
147 stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
149 o.optopt("r", "input-format", "the input type of the specified file",
153 o.optopt("w", "output-format", "the output type to write", "[html]")
155 stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
156 stable("crate-name", |o| {
157 o.optopt("", "crate-name", "specify the name of this crate", "NAME")
160 o.optmulti("L", "library-path", "directory to add to crate search path",
163 stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
164 stable("extern", |o| {
165 o.optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH")
167 stable("plugin-path", |o| {
168 o.optmulti("", "plugin-path", "removed", "DIR")
171 o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
173 stable("passes", |o| {
174 o.optmulti("", "passes",
175 "list of passes to also run, you might want \
176 to pass it multiple times; a value of `list` \
177 will print available passes",
180 stable("plugins", |o| {
181 o.optmulti("", "plugins", "removed",
184 stable("no-default", |o| {
185 o.optflag("", "no-defaults", "don't run the default passes")
187 stable("document-private-items", |o| {
188 o.optflag("", "document-private-items", "document private items")
190 stable("test", |o| o.optflag("", "test", "run code examples as tests")),
191 stable("test-args", |o| {
192 o.optmulti("", "test-args", "arguments to pass to the test runner",
195 stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
196 stable("markdown-css", |o| {
197 o.optmulti("", "markdown-css",
198 "CSS files to include via <link> in a rendered Markdown file",
201 stable("html-in-header", |o| {
202 o.optmulti("", "html-in-header",
203 "files to include inline in the <head> section of a rendered Markdown file \
204 or generated documentation",
207 stable("html-before-content", |o| {
208 o.optmulti("", "html-before-content",
209 "files to include inline between <body> and the content of a rendered \
210 Markdown file or generated documentation",
213 stable("html-after-content", |o| {
214 o.optmulti("", "html-after-content",
215 "files to include inline between the content and </body> of a rendered \
216 Markdown file or generated documentation",
219 unstable("markdown-before-content", |o| {
220 o.optmulti("", "markdown-before-content",
221 "files to include inline between <body> and the content of a rendered \
222 Markdown file or generated documentation",
225 unstable("markdown-after-content", |o| {
226 o.optmulti("", "markdown-after-content",
227 "files to include inline between the content and </body> of a rendered \
228 Markdown file or generated documentation",
231 stable("markdown-playground-url", |o| {
232 o.optopt("", "markdown-playground-url",
233 "URL to send code snippets to", "URL")
235 stable("markdown-no-toc", |o| {
236 o.optflag("", "markdown-no-toc", "don't include table of contents")
239 o.optopt("e", "extend-css",
240 "To add some CSS rules with a given file to generate doc with your \
241 own theme. However, your theme might break if the rustdoc's generated HTML \
242 changes, so be careful!", "PATH")
246 "internal and debugging options (only on nightly build)", "FLAG")
248 stable("sysroot", |o| {
249 o.optopt("", "sysroot", "Override the system root", "PATH")
251 unstable("playground-url", |o| {
252 o.optopt("", "playground-url",
253 "URL to send code snippets to, may be reset by --markdown-playground-url \
254 or `#![doc(html_playground_url=...)]`",
257 unstable("display-warnings", |o| {
258 o.optflag("", "display-warnings", "to print code warnings when testing doc")
260 unstable("crate-version", |o| {
261 o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
263 unstable("linker", |o| {
264 o.optopt("", "linker", "linker used for building executable test code", "PATH")
266 unstable("sort-modules-by-appearance", |o| {
267 o.optflag("", "sort-modules-by-appearance", "sort modules by where they appear in the \
268 program, rather than alphabetically")
270 unstable("themes", |o| {
271 o.optmulti("", "themes",
272 "additional themes which will be added to the generated docs",
275 unstable("theme-checker", |o| {
276 o.optmulti("", "theme-checker",
277 "check if given theme is valid",
280 unstable("resource-suffix", |o| {
283 "suffix to add to CSS and JavaScript files, e.g. \"light.css\" will become \
284 \"light-suffix.css\"",
287 unstable("edition", |o| {
288 o.optopt("", "edition",
289 "edition to use when compiling rust code (default: 2015)",
292 unstable("color", |o| {
295 "Configure coloring of output:
296 auto = colorize, if output goes to a tty (default);
297 always = always colorize output;
298 never = never colorize output",
301 unstable("error-format", |o| {
304 "How errors and other messages are produced",
307 unstable("disable-minification", |o| {
309 "disable-minification",
310 "Disable minification applied on JS files")
312 unstable("warn", |o| {
313 o.optmulti("W", "warn", "Set lint warnings", "OPT")
315 unstable("allow", |o| {
316 o.optmulti("A", "allow", "Set lint allowed", "OPT")
318 unstable("deny", |o| {
319 o.optmulti("D", "deny", "Set lint denied", "OPT")
321 unstable("forbid", |o| {
322 o.optmulti("F", "forbid", "Set lint forbidden", "OPT")
324 unstable("cap-lints", |o| {
328 "Set the most restrictive lint level. \
329 More restrictive lints are capped at this \
330 level. By default, it is at `forbid` level.",
337 pub fn usage(argv0: &str) {
338 let mut options = getopts::Options::new();
339 for option in opts() {
340 (option.apply)(&mut options);
342 println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
345 pub fn main_args(args: &[String]) -> isize {
346 let mut options = getopts::Options::new();
347 for option in opts() {
348 (option.apply)(&mut options);
350 let matches = match options.parse(&args[1..]) {
353 early_error(ErrorOutputType::default(), &err.to_string());
356 // Check for unstable options.
357 nightly_options::check_nightly_options(&matches, &opts());
359 if matches.opt_present("h") || matches.opt_present("help") {
362 } else if matches.opt_present("version") {
363 rustc_driver::version("rustdoc", &matches);
367 if matches.opt_strs("passes") == ["list"] {
368 println!("Available passes for running rustdoc:");
369 for &(name, _, description) in passes::PASSES {
370 println!("{:>20} - {}", name, description);
372 println!("\nDefault passes for rustdoc:");
373 for &name in passes::DEFAULT_PASSES {
374 println!("{:>20}", name);
379 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
380 Some("auto") => ColorConfig::Auto,
381 Some("always") => ColorConfig::Always,
382 Some("never") => ColorConfig::Never,
383 None => ColorConfig::Auto,
385 early_error(ErrorOutputType::default(),
386 &format!("argument for --color must be `auto`, `always` or `never` \
387 (instead was `{}`)", arg));
390 let error_format = match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
391 Some("human") => ErrorOutputType::HumanReadable(color),
392 Some("json") => ErrorOutputType::Json(false),
393 Some("pretty-json") => ErrorOutputType::Json(true),
394 Some("short") => ErrorOutputType::Short(color),
395 None => ErrorOutputType::HumanReadable(color),
397 early_error(ErrorOutputType::default(),
398 &format!("argument for --error-format must be `human`, `json` or \
399 `short` (instead was `{}`)", arg));
403 let diag = core::new_handler(error_format, None);
405 // check for deprecated options
406 check_deprecated_options(&matches, &diag);
408 let to_check = matches.opt_strs("theme-checker");
409 if !to_check.is_empty() {
410 let paths = theme::load_css_paths(include_bytes!("html/static/themes/light.css"));
413 println!("rustdoc: [theme-checker] Starting tests!");
414 for theme_file in to_check.iter() {
415 print!(" - Checking \"{}\"...", theme_file);
416 let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag);
417 if !differences.is_empty() || !success {
420 if !differences.is_empty() {
421 println!("{}", differences.join("\n"));
433 if matches.free.is_empty() {
434 diag.struct_err("missing file operand").emit();
437 if matches.free.len() > 1 {
438 diag.struct_err("too many file operands").emit();
441 let input = &matches.free[0];
443 let mut libs = SearchPaths::new();
444 for s in &matches.opt_strs("L") {
445 libs.add_path(s, error_format);
447 let externs = match parse_externs(&matches) {
450 diag.struct_err(&err.to_string()).emit();
455 let test_args = matches.opt_strs("test-args");
456 let test_args: Vec<String> = test_args.iter()
457 .flat_map(|s| s.split_whitespace())
458 .map(|s| s.to_string())
461 let should_test = matches.opt_present("test");
462 let markdown_input = Path::new(input).extension()
463 .map_or(false, |e| e == "md" || e == "markdown");
465 let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
466 let css_file_extension = matches.opt_str("e").map(|s| PathBuf::from(&s));
467 let cfgs = matches.opt_strs("cfg");
469 if let Some(ref p) = css_file_extension {
471 diag.struct_err("option --extend-css argument must be a file").emit();
476 let mut themes = Vec::new();
477 if matches.opt_present("themes") {
478 let paths = theme::load_css_paths(include_bytes!("html/static/themes/light.css"));
480 for (theme_file, theme_s) in matches.opt_strs("themes")
482 .map(|s| (PathBuf::from(&s), s.to_owned())) {
483 if !theme_file.is_file() {
484 diag.struct_err("option --themes arguments must all be files").emit();
487 let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
488 if !success || !ret.is_empty() {
489 diag.struct_err(&format!("invalid theme: \"{}\"", theme_s))
490 .help("check what's wrong with the --theme-checker option")
494 themes.push(theme_file);
498 let external_html = match ExternalHtml::load(
499 &matches.opt_strs("html-in-header"),
500 &matches.opt_strs("html-before-content"),
501 &matches.opt_strs("html-after-content"),
502 &matches.opt_strs("markdown-before-content"),
503 &matches.opt_strs("markdown-after-content"), &diag) {
507 let crate_name = matches.opt_str("crate-name");
508 let playground_url = matches.opt_str("playground-url");
509 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
510 let display_warnings = matches.opt_present("display-warnings");
511 let linker = matches.opt_str("linker").map(PathBuf::from);
512 let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
513 let resource_suffix = matches.opt_str("resource-suffix");
514 let enable_minification = !matches.opt_present("disable-minification");
516 let edition = matches.opt_str("edition").unwrap_or("2015".to_string());
517 let edition = match edition.parse() {
520 diag.struct_err("could not parse edition").emit();
525 let cg = build_codegen_options(&matches, ErrorOutputType::default());
527 match (should_test, markdown_input) {
529 return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot,
530 display_warnings, linker, edition, cg, &diag)
533 return test::run(Path::new(input), cfgs, libs, externs, test_args, crate_name,
534 maybe_sysroot, display_warnings, linker, edition, cg)
536 (false, true) => return markdown::render(Path::new(input),
537 output.unwrap_or(PathBuf::from("doc")),
538 &matches, &external_html,
539 !matches.opt_present("markdown-no-toc"), &diag),
543 let output_format = matches.opt_str("w");
545 let res = acquire_input(PathBuf::from(input), externs, edition, cg, &matches, error_format,
547 let Output { krate, passes, renderinfo } = out;
548 let diag = core::new_handler(error_format, None);
549 info!("going to format");
550 match output_format.as_ref().map(|s| &**s) {
551 Some("html") | None => {
552 html::render::run(krate, &external_html, playground_url,
553 output.unwrap_or(PathBuf::from("doc")),
554 resource_suffix.unwrap_or(String::new()),
555 passes.into_iter().collect(),
558 sort_modules_alphabetically,
561 .expect("failed to generate documentation");
565 diag.struct_err(&format!("unknown output format: {}", s)).emit();
570 res.unwrap_or_else(|s| {
571 diag.struct_err(&format!("input error: {}", s)).emit();
576 /// Looks inside the command line arguments to extract the relevant input format
577 /// and files and then generates the necessary rustdoc output for formatting.
578 fn acquire_input<R, F>(input: PathBuf,
582 matches: &getopts::Matches,
583 error_format: ErrorOutputType,
586 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
587 match matches.opt_str("r").as_ref().map(|s| &**s) {
588 Some("rust") => Ok(rust_input(input, externs, edition, cg, matches, error_format, f)),
589 Some(s) => Err(format!("unknown input format: {}", s)),
590 None => Ok(rust_input(input, externs, edition, cg, matches, error_format, f))
594 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
595 /// returns a map mapping crate names to their paths or else an
597 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
598 let mut externs = BTreeMap::new();
599 for arg in &matches.opt_strs("extern") {
600 let mut parts = arg.splitn(2, '=');
601 let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
602 let location = parts.next()
603 .ok_or("--extern value must be of the format `foo=bar`"
605 let name = name.to_string();
606 externs.entry(name).or_insert_with(BTreeSet::new).insert(location.to_string());
608 Ok(Externs::new(externs))
611 /// Interprets the input file as a rust source file, passing it through the
612 /// compiler all the way through the analysis passes. The rustdoc output is then
613 /// generated from the cleaned AST of the crate.
615 /// This form of input will run all of the plug/cleaning passes
616 fn rust_input<R, F>(cratefile: PathBuf,
620 matches: &getopts::Matches,
621 error_format: ErrorOutputType,
623 where R: 'static + Send,
624 F: 'static + Send + FnOnce(Output) -> R
626 let mut default_passes = !matches.opt_present("no-defaults");
627 let mut passes = matches.opt_strs("passes");
628 let mut plugins = matches.opt_strs("plugins");
630 // We hardcode in the passes here, as this is a new flag and we
631 // are generally deprecating passes.
632 if matches.opt_present("document-private-items") {
633 default_passes = false;
636 String::from("collapse-docs"),
637 String::from("unindent-comments"),
641 // First, parse the crate and extract all relevant information.
642 let mut paths = SearchPaths::new();
643 for s in &matches.opt_strs("L") {
644 paths.add_path(s, ErrorOutputType::default());
646 let cfgs = matches.opt_strs("cfg");
647 let triple = matches.opt_str("target").map(|target| {
648 if target.ends_with(".json") {
649 TargetTriple::TargetPath(PathBuf::from(target))
651 TargetTriple::TargetTriple(target)
654 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
655 let crate_name = matches.opt_str("crate-name");
656 let crate_version = matches.opt_str("crate-version");
657 let plugin_path = matches.opt_str("plugin-path");
659 info!("starting to run rustc");
660 let display_warnings = matches.opt_present("display-warnings");
662 let force_unstable_if_unmarked = matches.opt_strs("Z").iter().any(|x| {
663 *x == "force-unstable-if-unmarked"
666 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
668 let (tx, rx) = channel();
670 rustc_driver::monitor(move || syntax::with_globals(move || {
671 use rustc::session::config::Input;
673 let (mut krate, renderinfo) =
674 core::run_core(paths, cfgs, externs, Input::File(cratefile), triple, maybe_sysroot,
675 display_warnings, crate_name.clone(),
676 force_unstable_if_unmarked, edition, cg, error_format,
677 lint_opts, lint_cap, describe_lints);
679 info!("finished with rustc");
681 if let Some(name) = crate_name {
685 krate.version = crate_version;
687 let diag = core::new_handler(error_format, None);
689 fn report_deprecated_attr(name: &str, diag: &errors::Handler) {
690 let mut msg = diag.struct_warn(&format!("the `#![doc({})]` attribute is \
691 considered deprecated", name));
692 msg.warn("please see https://github.com/rust-lang/rust/issues/44136");
694 if name == "no_default_passes" {
695 msg.help("you may want to use `#![doc(document_private_items)]`");
701 // Process all of the crate attributes, extracting plugin metadata along
702 // with the passes which we are supposed to run.
703 for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
704 let name = attr.name().map(|s| s.as_str());
705 let name = name.as_ref().map(|s| &s[..]);
707 if name == Some("no_default_passes") {
708 report_deprecated_attr("no_default_passes", &diag);
709 default_passes = false;
711 } else if let Some(value) = attr.value_str() {
712 let sink = match name {
714 report_deprecated_attr("passes = \"...\"", &diag);
718 report_deprecated_attr("plugins = \"...\"", &diag);
723 for p in value.as_str().split_whitespace() {
724 sink.push(p.to_string());
728 if attr.is_word() && name == Some("document_private_items") {
729 default_passes = false;
732 String::from("collapse-docs"),
733 String::from("unindent-comments"),
739 for name in passes::DEFAULT_PASSES.iter().rev() {
740 passes.insert(0, name.to_string());
744 if !plugins.is_empty() {
745 eprintln!("WARNING: --plugins no longer functions; see CVE-2018-1000622");
748 if !plugin_path.is_none() {
749 eprintln!("WARNING: --plugin-path no longer functions; see CVE-2018-1000622");
752 // Load all plugins/passes into a PluginManager
753 let mut pm = plugins::PluginManager::new();
754 for pass in &passes {
755 let plugin = match passes::PASSES.iter()
756 .position(|&(p, ..)| {
759 Some(i) => passes::PASSES[i].1,
761 error!("unknown pass {}, skipping", *pass);
765 pm.add_plugin(plugin);
769 info!("Executing passes/plugins");
770 let krate = pm.run_plugins(krate);
772 tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes })).unwrap();
777 /// Prints deprecation warnings for deprecated options
778 fn check_deprecated_options(matches: &getopts::Matches, diag: &errors::Handler) {
779 let deprecated_flags = [
786 for flag in deprecated_flags.into_iter() {
787 if matches.opt_present(flag) {
788 let mut err = diag.struct_warn(&format!("the '{}' flag is considered deprecated",
790 err.warn("please see https://github.com/rust-lang/rust/issues/44136");
792 if *flag == "no-defaults" {
793 err.help("you may want to use --document-private-items");