1 use std::collections::BTreeMap;
3 use std::path::PathBuf;
7 use rustc::lint::Level;
9 use rustc::session::config::{CodegenOptions, DebuggingOptions, ErrorOutputType, Externs};
10 use rustc::session::config::{nightly_options, build_codegen_options, build_debugging_options,
11 get_cmd_lint_options, ExternEntry};
12 use rustc::session::search_paths::SearchPath;
14 use rustc_target::spec::TargetTriple;
15 use syntax::edition::{Edition, DEFAULT_EDITION};
17 use crate::core::new_handler;
18 use crate::externalfiles::ExternalHtml;
20 use crate::html::{static_files};
21 use crate::html::markdown::{IdMap};
23 use crate::passes::{self, DefaultPassOption};
26 /// Configuration options for rustdoc.
29 // Basic options / Options passed directly to rustc
31 /// The crate root or Markdown file to load.
33 /// The name of the crate being documented.
34 pub crate_name: Option<String>,
35 /// How to format errors and warnings.
36 pub error_format: ErrorOutputType,
37 /// Library search paths to hand to the compiler.
38 pub libs: Vec<SearchPath>,
39 /// The list of external crates to link against.
41 /// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`.
42 pub cfgs: Vec<String>,
43 /// Codegen options to hand to the compiler.
44 pub codegen_options: CodegenOptions,
45 /// Debugging (`-Z`) options to pass to the compiler.
46 pub debugging_options: DebuggingOptions,
47 /// The target used to compile the crate against.
48 pub target: Option<TargetTriple>,
49 /// Edition used when reading the crate. Defaults to "2015". Also used by default when
50 /// compiling doctests from the crate.
52 /// The path to the sysroot. Used during the compilation process.
53 pub maybe_sysroot: Option<PathBuf>,
54 /// Linker to use when building doctests.
55 pub linker: Option<PathBuf>,
56 /// Lint information passed over the command-line.
57 pub lint_opts: Vec<(String, Level)>,
58 /// Whether to ask rustc to describe the lints it knows. Practically speaking, this will not be
59 /// used, since we abort if we have no input file, but it's included for completeness.
60 pub describe_lints: bool,
61 /// What level to cap lints at.
62 pub lint_cap: Option<Level>,
64 // Options specific to running doctests
66 /// Whether we should run doctests instead of generating docs.
67 pub should_test: bool,
68 /// List of arguments to pass to the test harness, if running tests.
69 pub test_args: Vec<String>,
70 /// Optional path to persist the doctest executables to, defaults to a
71 /// temporary directory if not set.
72 pub persist_doctests: Option<PathBuf>,
74 // Options that affect the documentation process
76 /// The selected default set of passes to use.
78 /// Be aware: This option can come both from the CLI and from crate attributes!
79 pub default_passes: DefaultPassOption,
80 /// Any passes manually selected by the user.
82 /// Be aware: This option can come both from the CLI and from crate attributes!
83 pub manual_passes: Vec<String>,
84 /// Whether to display warnings during doc generation or while gathering doctests. By default,
85 /// all non-rustdoc-specific lints are allowed when generating docs.
86 pub display_warnings: bool,
87 /// Whether to run the `calculate-doc-coverage` pass, which counts the number of public items
88 /// with and without documentation.
89 pub show_coverage: bool,
91 // Options that alter generated documentation pages
93 /// Crate version to note on the sidebar of generated docs.
94 pub crate_version: Option<String>,
95 /// Collected options specific to outputting final pages.
96 pub render_options: RenderOptions,
99 impl fmt::Debug for Options {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 struct FmtExterns<'a>(&'a Externs);
103 impl<'a> fmt::Debug for FmtExterns<'a> {
104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 .entries(self.0.iter())
111 f.debug_struct("Options")
112 .field("input", &self.input)
113 .field("crate_name", &self.crate_name)
114 .field("error_format", &self.error_format)
115 .field("libs", &self.libs)
116 .field("externs", &FmtExterns(&self.externs))
117 .field("cfgs", &self.cfgs)
118 .field("codegen_options", &"...")
119 .field("debugging_options", &"...")
120 .field("target", &self.target)
121 .field("edition", &self.edition)
122 .field("maybe_sysroot", &self.maybe_sysroot)
123 .field("linker", &self.linker)
124 .field("lint_opts", &self.lint_opts)
125 .field("describe_lints", &self.describe_lints)
126 .field("lint_cap", &self.lint_cap)
127 .field("should_test", &self.should_test)
128 .field("test_args", &self.test_args)
129 .field("persist_doctests", &self.persist_doctests)
130 .field("default_passes", &self.default_passes)
131 .field("manual_passes", &self.manual_passes)
132 .field("display_warnings", &self.display_warnings)
133 .field("show_coverage", &self.show_coverage)
134 .field("crate_version", &self.crate_version)
135 .field("render_options", &self.render_options)
140 /// Configuration options for the HTML page-creation process.
141 #[derive(Clone, Debug)]
142 pub struct RenderOptions {
143 /// Output directory to generate docs into. Defaults to `doc`.
145 /// External files to insert into generated pages.
146 pub external_html: ExternalHtml,
147 /// A pre-populated `IdMap` with the default headings and any headings added by Markdown files
148 /// processed by `external_html`.
150 /// If present, playground URL to use in the "Run" button added to code samples.
152 /// Be aware: This option can come both from the CLI and from crate attributes!
153 pub playground_url: Option<String>,
154 /// Whether to sort modules alphabetically on a module page instead of using declaration order.
155 /// `true` by default.
157 // FIXME(misdreavus): the flag name is `--sort-modules-by-appearance` but the meaning is
158 // inverted once read.
159 pub sort_modules_alphabetically: bool,
160 /// List of themes to extend the docs with. Original argument name is included to assist in
161 /// displaying errors if it fails a theme check.
162 pub themes: Vec<PathBuf>,
163 /// If present, CSS file that contains rules to add to the default CSS.
164 pub extension_css: Option<PathBuf>,
165 /// A map of crate names to the URL to use instead of querying the crate's `html_root_url`.
166 pub extern_html_root_urls: BTreeMap<String, String>,
167 /// If present, suffix added to CSS/JavaScript files when referencing them in generated pages.
168 pub resource_suffix: String,
169 /// Whether to run the static CSS/JavaScript through a minifier when outputting them. `true` by
172 // FIXME(misdreavus): the flag name is `--disable-minification` but the meaning is inverted
174 pub enable_minification: bool,
175 /// Whether to create an index page in the root of the output directory. If this is true but
176 /// `enable_index_page` is None, generate a static listing of crates instead.
177 pub enable_index_page: bool,
178 /// A file to use as the index page at the root of the output directory. Overrides
179 /// `enable_index_page` to be true if set.
180 pub index_page: Option<PathBuf>,
181 /// An optional path to use as the location of static files. If not set, uses combinations of
182 /// `../` to reach the documentation root.
183 pub static_root_path: Option<String>,
185 // Options specific to reading standalone Markdown files
187 /// Whether to generate a table of contents on the output file when reading a standalone
189 pub markdown_no_toc: bool,
190 /// Additional CSS files to link in pages generated from standalone Markdown files.
191 pub markdown_css: Vec<String>,
192 /// If present, playground URL to use in the "Run" button added to code samples generated from
193 /// standalone Markdown files. If not present, `playground_url` is used.
194 pub markdown_playground_url: Option<String>,
195 /// If false, the `select` element to have search filtering by crates on rendered docs
196 /// won't be generated.
197 pub generate_search_filter: bool,
198 /// Option (disabled by default) to generate files used by RLS and some other tools.
199 pub generate_redirect_pages: bool,
203 /// Parses the given command-line for options. If an error message or other early-return has
204 /// been printed, returns `Err` with the exit code.
205 pub fn from_matches(matches: &getopts::Matches) -> Result<Options, i32> {
206 // Check for unstable options.
207 nightly_options::check_nightly_options(&matches, &opts());
209 if matches.opt_present("h") || matches.opt_present("help") {
210 crate::usage("rustdoc");
212 } else if matches.opt_present("version") {
213 rustc_driver::version("rustdoc", &matches);
217 if matches.opt_strs("passes") == ["list"] {
218 println!("Available passes for running rustdoc:");
219 for pass in passes::PASSES {
220 println!("{:>20} - {}", pass.name, pass.description);
222 println!("\nDefault passes for rustdoc:");
223 for pass in passes::DEFAULT_PASSES {
224 println!("{:>20}", pass.name);
226 println!("\nPasses run with `--document-private-items`:");
227 for pass in passes::DEFAULT_PRIVATE_PASSES {
228 println!("{:>20}", pass.name);
231 if nightly_options::is_nightly_build() {
232 println!("\nPasses run with `--show-coverage`:");
233 for pass in passes::DEFAULT_COVERAGE_PASSES {
234 println!("{:>20}", pass.name);
236 println!("\nPasses run with `--show-coverage --document-private-items`:");
237 for pass in passes::PRIVATE_COVERAGE_PASSES {
238 println!("{:>20}", pass.name);
245 let color = session::config::parse_color(&matches);
246 let (json_rendered, _artifacts) = session::config::parse_json(&matches);
247 let error_format = session::config::parse_error_format(&matches, color, json_rendered);
249 let codegen_options = build_codegen_options(matches, error_format);
250 let debugging_options = build_debugging_options(matches, error_format);
252 let diag = new_handler(error_format,
254 debugging_options.treat_err_as_bug,
255 debugging_options.ui_testing);
257 // check for deprecated options
258 check_deprecated_options(&matches, &diag);
260 let to_check = matches.opt_strs("theme-checker");
261 if !to_check.is_empty() {
262 let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
265 println!("rustdoc: [theme-checker] Starting tests!");
266 for theme_file in to_check.iter() {
267 print!(" - Checking \"{}\"...", theme_file);
268 let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag);
269 if !differences.is_empty() || !success {
272 if !differences.is_empty() {
273 println!("{}", differences.join("\n"));
285 if matches.free.is_empty() {
286 diag.struct_err("missing file operand").emit();
289 if matches.free.len() > 1 {
290 diag.struct_err("too many file operands").emit();
293 let input = PathBuf::from(&matches.free[0]);
295 let libs = matches.opt_strs("L").iter()
296 .map(|s| SearchPath::from_cli_opt(s, error_format))
298 let externs = match parse_externs(&matches) {
301 diag.struct_err(&err).emit();
305 let extern_html_root_urls = match parse_extern_html_roots(&matches) {
308 diag.struct_err(err).emit();
313 let test_args = matches.opt_strs("test-args");
314 let test_args: Vec<String> = test_args.iter()
315 .flat_map(|s| s.split_whitespace())
316 .map(|s| s.to_string())
319 let should_test = matches.opt_present("test");
321 let output = matches.opt_str("o")
322 .map(|s| PathBuf::from(&s))
323 .unwrap_or_else(|| PathBuf::from("doc"));
324 let mut cfgs = matches.opt_strs("cfg");
325 cfgs.push("rustdoc".to_string());
327 cfgs.push("doctest".to_string());
330 let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
332 if let Some(ref p) = extension_css {
334 diag.struct_err("option --extend-css argument must be a file").emit();
339 let mut themes = Vec::new();
340 if matches.opt_present("themes") {
341 let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
343 for (theme_file, theme_s) in matches.opt_strs("themes")
345 .map(|s| (PathBuf::from(&s), s.to_owned())) {
346 if !theme_file.is_file() {
347 diag.struct_err("option --themes arguments must all be files").emit();
350 let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
351 if !success || !ret.is_empty() {
352 diag.struct_err(&format!("invalid theme: \"{}\"", theme_s))
353 .help("check what's wrong with the --theme-checker option")
357 themes.push(theme_file);
361 let edition = if let Some(e) = matches.opt_str("edition") {
365 diag.struct_err("could not parse edition").emit();
373 let mut id_map = html::markdown::IdMap::new();
374 id_map.populate(html::render::initial_ids());
375 let external_html = match ExternalHtml::load(
376 &matches.opt_strs("html-in-header"),
377 &matches.opt_strs("html-before-content"),
378 &matches.opt_strs("html-after-content"),
379 &matches.opt_strs("markdown-before-content"),
380 &matches.opt_strs("markdown-after-content"),
381 &diag, &mut id_map, edition, &None) {
383 None => return Err(3),
386 match matches.opt_str("r").as_ref().map(|s| &**s) {
387 Some("rust") | None => {}
389 diag.struct_err(&format!("unknown input format: {}", s)).emit();
394 match matches.opt_str("w").as_ref().map(|s| &**s) {
395 Some("html") | None => {}
397 diag.struct_err(&format!("unknown output format: {}", s)).emit();
402 let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
403 if let Some(ref index_page) = index_page {
404 if !index_page.is_file() {
405 diag.struct_err("option `--index-page` argument must be a file").emit();
410 let target = matches.opt_str("target").map(|target| {
411 if target.ends_with(".json") {
412 TargetTriple::TargetPath(PathBuf::from(target))
414 TargetTriple::TargetTriple(target)
418 let show_coverage = matches.opt_present("show-coverage");
419 let document_private = matches.opt_present("document-private-items");
421 let default_passes = if matches.opt_present("no-defaults") {
422 passes::DefaultPassOption::None
423 } else if show_coverage && document_private {
424 passes::DefaultPassOption::PrivateCoverage
425 } else if show_coverage {
426 passes::DefaultPassOption::Coverage
427 } else if document_private {
428 passes::DefaultPassOption::Private
430 passes::DefaultPassOption::Default
432 let manual_passes = matches.opt_strs("passes");
434 let crate_name = matches.opt_str("crate-name");
435 let playground_url = matches.opt_str("playground-url");
436 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
437 let display_warnings = matches.opt_present("display-warnings");
438 let linker = matches.opt_str("linker").map(PathBuf::from);
439 let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
440 let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
441 let enable_minification = !matches.opt_present("disable-minification");
442 let markdown_no_toc = matches.opt_present("markdown-no-toc");
443 let markdown_css = matches.opt_strs("markdown-css");
444 let markdown_playground_url = matches.opt_str("markdown-playground-url");
445 let crate_version = matches.opt_str("crate-version");
446 let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
447 let static_root_path = matches.opt_str("static-root-path");
448 let generate_search_filter = !matches.opt_present("disable-per-crate-search");
449 let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
450 let generate_redirect_pages = matches.opt_present("generate-redirect-pages");
452 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
478 render_options: RenderOptions {
483 sort_modules_alphabetically,
486 extern_html_root_urls,
494 markdown_playground_url,
495 generate_search_filter,
496 generate_redirect_pages,
501 /// Returns `true` if the file given as `self.input` is a Markdown file.
502 pub fn markdown_input(&self) -> bool {
503 self.input.extension()
504 .map_or(false, |e| e == "md" || e == "markdown")
508 /// Prints deprecation warnings for deprecated options
509 fn check_deprecated_options(matches: &getopts::Matches, diag: &errors::Handler) {
510 let deprecated_flags = [
517 for flag in deprecated_flags.iter() {
518 if matches.opt_present(flag) {
519 let mut err = diag.struct_warn(&format!("the '{}' flag is considered deprecated",
521 err.warn("please see https://github.com/rust-lang/rust/issues/44136");
523 if *flag == "no-defaults" {
524 err.help("you may want to use --document-private-items");
531 let removed_flags = [
536 for &flag in removed_flags.iter() {
537 if matches.opt_present(flag) {
538 diag.struct_warn(&format!("the '{}' flag no longer functions", flag))
539 .warn("see CVE-2018-1000622")
545 /// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
546 /// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
547 /// describing the issue.
548 fn parse_extern_html_roots(
549 matches: &getopts::Matches,
550 ) -> Result<BTreeMap<String, String>, &'static str> {
551 let mut externs = BTreeMap::new();
552 for arg in &matches.opt_strs("extern-html-root-url") {
553 let mut parts = arg.splitn(2, '=');
554 let name = parts.next().ok_or("--extern-html-root-url must not be empty")?;
555 let url = parts.next().ok_or("--extern-html-root-url must be of the form name=url")?;
556 externs.insert(name.to_string(), url.to_string());
562 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
563 /// returns a map mapping crate names to their paths or else an
565 // FIXME(eddyb) This shouldn't be duplicated with `rustc::session`.
566 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
567 let mut externs: BTreeMap<_, ExternEntry> = BTreeMap::new();
568 for arg in &matches.opt_strs("extern") {
569 let mut parts = arg.splitn(2, '=');
570 let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
571 let location = parts.next().map(|s| s.to_string());
572 if location.is_none() && !nightly_options::is_unstable_enabled(matches) {
573 return Err("the `-Z unstable-options` flag must also be passed to \
574 enable `--extern crate_name` without `=path`".to_string());
576 let name = name.to_string();
577 // For Rustdoc purposes, we can treat all externs as public
580 .locations.insert(location.clone());
582 Ok(Externs::new(externs))