1 // Copyright 2018 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 use std::collections::{BTreeMap, BTreeSet};
13 use std::path::PathBuf;
16 use errors::emitter::ColorConfig;
18 use rustc::lint::Level;
19 use rustc::session::early_error;
20 use rustc::session::config::{CodegenOptions, DebuggingOptions, ErrorOutputType, Externs};
21 use rustc::session::config::{nightly_options, build_codegen_options, build_debugging_options,
22 get_cmd_lint_options};
23 use rustc::session::search_paths::SearchPath;
25 use rustc_target::spec::TargetTriple;
26 use syntax::edition::Edition;
28 use core::new_handler;
29 use externalfiles::ExternalHtml;
31 use html::markdown::IdMap;
32 use html::static_files;
34 use passes::{self, DefaultPassOption};
37 /// Configuration options for rustdoc.
40 // Basic options / Options passed directly to rustc
42 /// The crate root or Markdown file to load.
44 /// The name of the crate being documented.
45 pub crate_name: Option<String>,
46 /// How to format errors and warnings.
47 pub error_format: ErrorOutputType,
48 /// Library search paths to hand to the compiler.
49 pub libs: Vec<SearchPath>,
50 /// The list of external crates to link against.
52 /// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`.
53 pub cfgs: Vec<String>,
54 /// Codegen options to hand to the compiler.
55 pub codegen_options: CodegenOptions,
56 /// Debugging (`-Z`) options to pass to the compiler.
57 pub debugging_options: DebuggingOptions,
58 /// The target used to compile the crate against.
59 pub target: Option<TargetTriple>,
60 /// Edition used when reading the crate. Defaults to "2015". Also used by default when
61 /// compiling doctests from the crate.
63 /// The path to the sysroot. Used during the compilation process.
64 pub maybe_sysroot: Option<PathBuf>,
65 /// Linker to use when building doctests.
66 pub linker: Option<PathBuf>,
67 /// Lint information passed over the command-line.
68 pub lint_opts: Vec<(String, Level)>,
69 /// Whether to ask rustc to describe the lints it knows. Practically speaking, this will not be
70 /// used, since we abort if we have no input file, but it's included for completeness.
71 pub describe_lints: bool,
72 /// What level to cap lints at.
73 pub lint_cap: Option<Level>,
75 // Options specific to running doctests
77 /// Whether we should run doctests instead of generating docs.
78 pub should_test: bool,
79 /// List of arguments to pass to the test harness, if running tests.
80 pub test_args: Vec<String>,
82 // Options that affect the documentation process
84 /// The selected default set of passes to use.
86 /// Be aware: This option can come both from the CLI and from crate attributes!
87 pub default_passes: DefaultPassOption,
88 /// Any passes manually selected by the user.
90 /// Be aware: This option can come both from the CLI and from crate attributes!
91 pub manual_passes: Vec<String>,
92 /// Whether to display warnings during doc generation or while gathering doctests. By default,
93 /// all non-rustdoc-specific lints are allowed when generating docs.
94 pub display_warnings: bool,
96 // Options that alter generated documentation pages
98 /// Crate version to note on the sidebar of generated docs.
99 pub crate_version: Option<String>,
100 /// Collected options specific to outputting final pages.
101 pub render_options: RenderOptions,
104 impl fmt::Debug for Options {
105 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
106 struct FmtExterns<'a>(&'a Externs);
108 impl<'a> fmt::Debug for FmtExterns<'a> {
109 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
111 .entries(self.0.iter())
116 f.debug_struct("Options")
117 .field("input", &self.input)
118 .field("crate_name", &self.crate_name)
119 .field("error_format", &self.error_format)
120 .field("libs", &self.libs)
121 .field("externs", &FmtExterns(&self.externs))
122 .field("cfgs", &self.cfgs)
123 .field("codegen_options", &"...")
124 .field("debugging_options", &"...")
125 .field("target", &self.target)
126 .field("edition", &self.edition)
127 .field("maybe_sysroot", &self.maybe_sysroot)
128 .field("linker", &self.linker)
129 .field("lint_opts", &self.lint_opts)
130 .field("describe_lints", &self.describe_lints)
131 .field("lint_cap", &self.lint_cap)
132 .field("should_test", &self.should_test)
133 .field("test_args", &self.test_args)
134 .field("default_passes", &self.default_passes)
135 .field("manual_passes", &self.manual_passes)
136 .field("display_warnings", &self.display_warnings)
137 .field("crate_version", &self.crate_version)
138 .field("render_options", &self.render_options)
143 /// Configuration options for the HTML page-creation process.
144 #[derive(Clone, Debug)]
145 pub struct RenderOptions {
146 /// Output directory to generate docs into. Defaults to `doc`.
148 /// External files to insert into generated pages.
149 pub external_html: ExternalHtml,
150 /// A pre-populated `IdMap` with the default headings and any headings added by Markdown files
151 /// processed by `external_html`.
153 /// If present, playground URL to use in the "Run" button added to code samples.
155 /// Be aware: This option can come both from the CLI and from crate attributes!
156 pub playground_url: Option<String>,
157 /// Whether to sort modules alphabetically on a module page instead of using declaration order.
158 /// `true` by default.
160 /// FIXME(misdreavus): the flag name is `--sort-modules-by-appearance` but the meaning is
161 /// inverted once read
162 pub sort_modules_alphabetically: bool,
163 /// List of themes to extend the docs with. Original argument name is included to assist in
164 /// displaying errors if it fails a theme check.
165 pub themes: Vec<PathBuf>,
166 /// If present, CSS file that contains rules to add to the default CSS.
167 pub extension_css: Option<PathBuf>,
168 /// A map of crate names to the URL to use instead of querying the crate's `html_root_url`.
169 pub extern_html_root_urls: BTreeMap<String, String>,
170 /// If present, suffix added to CSS/JavaScript files when referencing them in generated pages.
171 pub resource_suffix: String,
172 /// Whether to run the static CSS/JavaScript through a minifier when outputting them. `true` by
175 /// FIXME(misdreavus): the flag name is `--disable-minification` but the meaning is inverted
177 pub enable_minification: bool,
178 /// Whether to create an index page in the root of the output directory. If this is true but
179 /// `enable_index_page` is None, generate a static listing of crates instead.
180 pub enable_index_page: bool,
181 /// A file to use as the index page at the root of the output directory. Overrides
182 /// `enable_index_page` to be true if set.
183 pub index_page: Option<PathBuf>,
184 /// An optional path to use as the location of static files. If not set, uses combinations of
185 /// `../` to reach the documentation root.
186 pub static_root_path: Option<String>,
188 // Options specific to reading standalone Markdown files
190 /// Whether to generate a table of contents on the output file when reading a standalone
192 pub markdown_no_toc: bool,
193 /// Additional CSS files to link in pages generated from standalone Markdown files.
194 pub markdown_css: Vec<String>,
195 /// If present, playground URL to use in the "Run" button added to code samples generated from
196 /// standalone Markdown files. If not present, `playground_url` is used.
197 pub markdown_playground_url: Option<String>,
198 /// If false, the `select` element to have search filtering by crates on rendered docs
199 /// won't be generated.
200 pub generate_search_filter: bool,
204 /// Parses the given command-line for options. If an error message or other early-return has
205 /// been printed, returns `Err` with the exit code.
206 pub fn from_matches(matches: &getopts::Matches) -> Result<Options, isize> {
207 // Check for unstable options.
208 nightly_options::check_nightly_options(&matches, &opts());
210 if matches.opt_present("h") || matches.opt_present("help") {
213 } else if matches.opt_present("version") {
214 rustc_driver::version("rustdoc", &matches);
218 if matches.opt_strs("passes") == ["list"] {
219 println!("Available passes for running rustdoc:");
220 for pass in passes::PASSES {
221 println!("{:>20} - {}", pass.name(), pass.description());
223 println!("\nDefault passes for rustdoc:");
224 for &name in passes::DEFAULT_PASSES {
225 println!("{:>20}", name);
227 println!("\nPasses run with `--document-private-items`:");
228 for &name in passes::DEFAULT_PRIVATE_PASSES {
229 println!("{:>20}", name);
234 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
235 Some("auto") => ColorConfig::Auto,
236 Some("always") => ColorConfig::Always,
237 Some("never") => ColorConfig::Never,
238 None => ColorConfig::Auto,
240 early_error(ErrorOutputType::default(),
241 &format!("argument for --color must be `auto`, `always` or `never` \
242 (instead was `{}`)", arg));
245 let error_format = match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
246 Some("human") => ErrorOutputType::HumanReadable(color),
247 Some("json") => ErrorOutputType::Json(false),
248 Some("pretty-json") => ErrorOutputType::Json(true),
249 Some("short") => ErrorOutputType::Short(color),
250 None => ErrorOutputType::HumanReadable(color),
252 early_error(ErrorOutputType::default(),
253 &format!("argument for --error-format must be `human`, `json` or \
254 `short` (instead was `{}`)", arg));
258 let codegen_options = build_codegen_options(matches, error_format);
259 let debugging_options = build_debugging_options(matches, error_format);
261 let diag = new_handler(error_format,
263 debugging_options.treat_err_as_bug,
264 debugging_options.ui_testing);
266 // check for deprecated options
267 check_deprecated_options(&matches, &diag);
269 let to_check = matches.opt_strs("theme-checker");
270 if !to_check.is_empty() {
271 let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
274 println!("rustdoc: [theme-checker] Starting tests!");
275 for theme_file in to_check.iter() {
276 print!(" - Checking \"{}\"...", theme_file);
277 let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag);
278 if !differences.is_empty() || !success {
281 if !differences.is_empty() {
282 println!("{}", differences.join("\n"));
294 if matches.free.is_empty() {
295 diag.struct_err("missing file operand").emit();
298 if matches.free.len() > 1 {
299 diag.struct_err("too many file operands").emit();
302 let input = PathBuf::from(&matches.free[0]);
304 let libs = matches.opt_strs("L").iter()
305 .map(|s| SearchPath::from_cli_opt(s, error_format))
307 let externs = match parse_externs(&matches) {
310 diag.struct_err(&err).emit();
314 let extern_html_root_urls = match parse_extern_html_roots(&matches) {
317 diag.struct_err(err).emit();
322 let test_args = matches.opt_strs("test-args");
323 let test_args: Vec<String> = test_args.iter()
324 .flat_map(|s| s.split_whitespace())
325 .map(|s| s.to_string())
328 let should_test = matches.opt_present("test");
330 let output = matches.opt_str("o")
331 .map(|s| PathBuf::from(&s))
332 .unwrap_or_else(|| PathBuf::from("doc"));
333 let mut cfgs = matches.opt_strs("cfg");
334 cfgs.push("rustdoc".to_string());
336 let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
338 if let Some(ref p) = extension_css {
340 diag.struct_err("option --extend-css argument must be a file").emit();
345 let mut themes = Vec::new();
346 if matches.opt_present("themes") {
347 let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
349 for (theme_file, theme_s) in matches.opt_strs("themes")
351 .map(|s| (PathBuf::from(&s), s.to_owned())) {
352 if !theme_file.is_file() {
353 diag.struct_err("option --themes arguments must all be files").emit();
356 let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
357 if !success || !ret.is_empty() {
358 diag.struct_err(&format!("invalid theme: \"{}\"", theme_s))
359 .help("check what's wrong with the --theme-checker option")
363 themes.push(theme_file);
367 let mut id_map = html::markdown::IdMap::new();
368 id_map.populate(html::render::initial_ids());
369 let external_html = match ExternalHtml::load(
370 &matches.opt_strs("html-in-header"),
371 &matches.opt_strs("html-before-content"),
372 &matches.opt_strs("html-after-content"),
373 &matches.opt_strs("markdown-before-content"),
374 &matches.opt_strs("markdown-after-content"), &diag, &mut id_map) {
376 None => return Err(3),
379 let edition = matches.opt_str("edition").unwrap_or("2015".to_string());
380 let edition = match edition.parse() {
383 diag.struct_err("could not parse edition").emit();
388 match matches.opt_str("r").as_ref().map(|s| &**s) {
389 Some("rust") | None => {}
391 diag.struct_err(&format!("unknown input format: {}", s)).emit();
396 match matches.opt_str("w").as_ref().map(|s| &**s) {
397 Some("html") | None => {}
399 diag.struct_err(&format!("unknown output format: {}", s)).emit();
404 let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
405 if let Some(ref index_page) = index_page {
406 if !index_page.is_file() {
407 diag.struct_err("option `--index-page` argument must be a file").emit();
412 let target = matches.opt_str("target").map(|target| {
413 if target.ends_with(".json") {
414 TargetTriple::TargetPath(PathBuf::from(target))
416 TargetTriple::TargetTriple(target)
420 let default_passes = if matches.opt_present("no-defaults") {
421 passes::DefaultPassOption::None
422 } else if matches.opt_present("document-private-items") {
423 passes::DefaultPassOption::Private
425 passes::DefaultPassOption::Default
427 let manual_passes = matches.opt_strs("passes");
429 let crate_name = matches.opt_str("crate-name");
430 let playground_url = matches.opt_str("playground-url");
431 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
432 let display_warnings = matches.opt_present("display-warnings");
433 let linker = matches.opt_str("linker").map(PathBuf::from);
434 let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
435 let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
436 let enable_minification = !matches.opt_present("disable-minification");
437 let markdown_no_toc = matches.opt_present("markdown-no-toc");
438 let markdown_css = matches.opt_strs("markdown-css");
439 let markdown_playground_url = matches.opt_str("markdown-playground-url");
440 let crate_version = matches.opt_str("crate-version");
441 let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
442 let static_root_path = matches.opt_str("static-root-path");
443 let generate_search_filter = !matches.opt_present("disable-per-crate-search");
445 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
469 render_options: RenderOptions {
474 sort_modules_alphabetically,
477 extern_html_root_urls,
485 markdown_playground_url,
486 generate_search_filter,
491 /// Returns whether the file given as `self.input` is a Markdown file.
492 pub fn markdown_input(&self) -> bool {
493 self.input.extension()
494 .map_or(false, |e| e == "md" || e == "markdown")
498 /// Prints deprecation warnings for deprecated options
499 fn check_deprecated_options(matches: &getopts::Matches, diag: &errors::Handler) {
500 let deprecated_flags = [
507 for flag in deprecated_flags.into_iter() {
508 if matches.opt_present(flag) {
509 let mut err = diag.struct_warn(&format!("the '{}' flag is considered deprecated",
511 err.warn("please see https://github.com/rust-lang/rust/issues/44136");
513 if *flag == "no-defaults" {
514 err.help("you may want to use --document-private-items");
521 let removed_flags = [
526 for &flag in removed_flags.iter() {
527 if matches.opt_present(flag) {
528 diag.struct_warn(&format!("the '{}' flag no longer functions", flag))
529 .warn("see CVE-2018-1000622")
535 /// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
536 /// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
537 /// describing the issue.
538 fn parse_extern_html_roots(
539 matches: &getopts::Matches,
540 ) -> Result<BTreeMap<String, String>, &'static str> {
541 let mut externs = BTreeMap::new();
542 for arg in &matches.opt_strs("extern-html-root-url") {
543 let mut parts = arg.splitn(2, '=');
544 let name = parts.next().ok_or("--extern-html-root-url must not be empty")?;
545 let url = parts.next().ok_or("--extern-html-root-url must be of the form name=url")?;
546 externs.insert(name.to_string(), url.to_string());
552 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
553 /// returns a map mapping crate names to their paths or else an
555 // FIXME(eddyb) This shouldn't be duplicated with `rustc::session`.
556 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
557 let mut externs: BTreeMap<_, BTreeSet<_>> = BTreeMap::new();
558 for arg in &matches.opt_strs("extern") {
559 let mut parts = arg.splitn(2, '=');
560 let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
561 let location = parts.next().map(|s| s.to_string());
562 if location.is_none() && !nightly_options::is_unstable_enabled(matches) {
563 return Err("the `-Z unstable-options` flag must also be passed to \
564 enable `--extern crate_name` without `=path`".to_string());
566 let name = name.to_string();
567 externs.entry(name).or_default().insert(location);
569 Ok(Externs::new(externs))