1 use std::collections::BTreeMap;
4 use std::path::PathBuf;
8 use rustc::lint::Level;
10 use rustc::session::config::{
11 build_codegen_options, build_debugging_options, get_cmd_lint_options, host_triple,
14 use rustc::session::config::{parse_crate_types_from_list, parse_externs, CrateType};
15 use rustc::session::config::{CodegenOptions, DebuggingOptions, ErrorOutputType, Externs};
16 use rustc::session::search_paths::SearchPath;
18 use rustc_span::edition::{Edition, DEFAULT_EDITION};
19 use rustc_target::spec::TargetTriple;
21 use crate::core::new_handler;
22 use crate::externalfiles::ExternalHtml;
24 use crate::html::markdown::IdMap;
25 use crate::html::static_files;
27 use crate::passes::{self, DefaultPassOption};
30 /// Configuration options for rustdoc.
33 // Basic options / Options passed directly to rustc
34 /// The crate root or Markdown file to load.
36 /// The name of the crate being documented.
37 pub crate_name: Option<String>,
38 /// Whether or not this is a proc-macro crate
39 pub proc_macro_crate: bool,
40 /// How to format errors and warnings.
41 pub error_format: ErrorOutputType,
42 /// Library search paths to hand to the compiler.
43 pub libs: Vec<SearchPath>,
44 /// Library search paths strings to hand to the compiler.
45 pub lib_strs: Vec<String>,
46 /// The list of external crates to link against.
48 /// The list of external crates strings to link against.
49 pub extern_strs: Vec<String>,
50 /// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`.
51 pub cfgs: Vec<String>,
52 /// Codegen options to hand to the compiler.
53 pub codegen_options: CodegenOptions,
54 /// Codegen options strings to hand to the compiler.
55 pub codegen_options_strs: Vec<String>,
56 /// Debugging (`-Z`) options to pass to the compiler.
57 pub debugging_options: DebuggingOptions,
58 /// Debugging (`-Z`) options strings to pass to the compiler.
59 pub debugging_options_strs: Vec<String>,
60 /// The target used to compile the crate against.
61 pub target: TargetTriple,
62 /// Edition used when reading the crate. Defaults to "2015". Also used by default when
63 /// compiling doctests from the crate.
65 /// The path to the sysroot. Used during the compilation process.
66 pub maybe_sysroot: 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
76 /// Whether we should run doctests instead of generating docs.
77 pub should_test: bool,
78 /// List of arguments to pass to the test harness, if running tests.
79 pub test_args: Vec<String>,
80 /// Optional path to persist the doctest executables to, defaults to a
81 /// temporary directory if not set.
82 pub persist_doctests: Option<PathBuf>,
83 /// Runtool to run doctests with
84 pub runtool: Option<String>,
85 /// Arguments to pass to the runtool
86 pub runtool_args: Vec<String>,
87 /// Whether to allow ignoring doctests on a per-target basis
88 /// For example, using ignore-foo to ignore running the doctest on any target that
89 /// contains "foo" as a substring
90 pub enable_per_target_ignores: bool,
92 /// The path to a rustc-like binary to build tests with. If not set, we
93 /// default to loading from $sysroot/bin/rustc.
94 pub test_builder: Option<PathBuf>,
96 // Options that affect the documentation process
97 /// The selected default set of passes to use.
99 /// Be aware: This option can come both from the CLI and from crate attributes!
100 pub default_passes: DefaultPassOption,
101 /// Any passes manually selected by the user.
103 /// Be aware: This option can come both from the CLI and from crate attributes!
104 pub manual_passes: Vec<String>,
105 /// Whether to display warnings during doc generation or while gathering doctests. By default,
106 /// all non-rustdoc-specific lints are allowed when generating docs.
107 pub display_warnings: bool,
108 /// Whether to run the `calculate-doc-coverage` pass, which counts the number of public items
109 /// with and without documentation.
110 pub show_coverage: bool,
112 // Options that alter generated documentation pages
113 /// Crate version to note on the sidebar of generated docs.
114 pub crate_version: Option<String>,
115 /// Collected options specific to outputting final pages.
116 pub render_options: RenderOptions,
119 impl fmt::Debug for Options {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 struct FmtExterns<'a>(&'a Externs);
123 impl<'a> fmt::Debug for FmtExterns<'a> {
124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 f.debug_map().entries(self.0.iter()).finish()
129 f.debug_struct("Options")
130 .field("input", &self.input)
131 .field("crate_name", &self.crate_name)
132 .field("proc_macro_crate", &self.proc_macro_crate)
133 .field("error_format", &self.error_format)
134 .field("libs", &self.libs)
135 .field("externs", &FmtExterns(&self.externs))
136 .field("cfgs", &self.cfgs)
137 .field("codegen_options", &"...")
138 .field("debugging_options", &"...")
139 .field("target", &self.target)
140 .field("edition", &self.edition)
141 .field("maybe_sysroot", &self.maybe_sysroot)
142 .field("lint_opts", &self.lint_opts)
143 .field("describe_lints", &self.describe_lints)
144 .field("lint_cap", &self.lint_cap)
145 .field("should_test", &self.should_test)
146 .field("test_args", &self.test_args)
147 .field("persist_doctests", &self.persist_doctests)
148 .field("default_passes", &self.default_passes)
149 .field("manual_passes", &self.manual_passes)
150 .field("display_warnings", &self.display_warnings)
151 .field("show_coverage", &self.show_coverage)
152 .field("crate_version", &self.crate_version)
153 .field("render_options", &self.render_options)
154 .field("runtool", &self.runtool)
155 .field("runtool_args", &self.runtool_args)
156 .field("enable-per-target-ignores", &self.enable_per_target_ignores)
161 /// Configuration options for the HTML page-creation process.
162 #[derive(Clone, Debug)]
163 pub struct RenderOptions {
164 /// Output directory to generate docs into. Defaults to `doc`.
166 /// External files to insert into generated pages.
167 pub external_html: ExternalHtml,
168 /// A pre-populated `IdMap` with the default headings and any headings added by Markdown files
169 /// processed by `external_html`.
171 /// If present, playground URL to use in the "Run" button added to code samples.
173 /// Be aware: This option can come both from the CLI and from crate attributes!
174 pub playground_url: Option<String>,
175 /// Whether to sort modules alphabetically on a module page instead of using declaration order.
176 /// `true` by default.
178 // FIXME(misdreavus): the flag name is `--sort-modules-by-appearance` but the meaning is
179 // inverted once read.
180 pub sort_modules_alphabetically: bool,
181 /// List of themes to extend the docs with. Original argument name is included to assist in
182 /// displaying errors if it fails a theme check.
183 pub themes: Vec<PathBuf>,
184 /// If present, CSS file that contains rules to add to the default CSS.
185 pub extension_css: Option<PathBuf>,
186 /// A map of crate names to the URL to use instead of querying the crate's `html_root_url`.
187 pub extern_html_root_urls: BTreeMap<String, String>,
188 /// If present, suffix added to CSS/JavaScript files when referencing them in generated pages.
189 pub resource_suffix: String,
190 /// Whether to run the static CSS/JavaScript through a minifier when outputting them. `true` by
193 // FIXME(misdreavus): the flag name is `--disable-minification` but the meaning is inverted
195 pub enable_minification: bool,
196 /// Whether to create an index page in the root of the output directory. If this is true but
197 /// `enable_index_page` is None, generate a static listing of crates instead.
198 pub enable_index_page: bool,
199 /// A file to use as the index page at the root of the output directory. Overrides
200 /// `enable_index_page` to be true if set.
201 pub index_page: Option<PathBuf>,
202 /// An optional path to use as the location of static files. If not set, uses combinations of
203 /// `../` to reach the documentation root.
204 pub static_root_path: Option<String>,
206 // Options specific to reading standalone Markdown files
207 /// Whether to generate a table of contents on the output file when reading a standalone
209 pub markdown_no_toc: bool,
210 /// Additional CSS files to link in pages generated from standalone Markdown files.
211 pub markdown_css: Vec<String>,
212 /// If present, playground URL to use in the "Run" button added to code samples generated from
213 /// standalone Markdown files. If not present, `playground_url` is used.
214 pub markdown_playground_url: Option<String>,
215 /// If false, the `select` element to have search filtering by crates on rendered docs
216 /// won't be generated.
217 pub generate_search_filter: bool,
218 /// Option (disabled by default) to generate files used by RLS and some other tools.
219 pub generate_redirect_pages: bool,
223 /// Parses the given command-line for options. If an error message or other early-return has
224 /// been printed, returns `Err` with the exit code.
225 pub fn from_matches(matches: &getopts::Matches) -> Result<Options, i32> {
226 // Check for unstable options.
227 nightly_options::check_nightly_options(&matches, &opts());
229 if matches.opt_present("h") || matches.opt_present("help") {
230 crate::usage("rustdoc");
232 } else if matches.opt_present("version") {
233 rustc_driver::version("rustdoc", &matches);
237 if matches.opt_strs("passes") == ["list"] {
238 println!("Available passes for running rustdoc:");
239 for pass in passes::PASSES {
240 println!("{:>20} - {}", pass.name, pass.description);
242 println!("\nDefault passes for rustdoc:");
243 for pass in passes::DEFAULT_PASSES {
244 println!("{:>20}", pass.name);
246 println!("\nPasses run with `--document-private-items`:");
247 for pass in passes::DEFAULT_PRIVATE_PASSES {
248 println!("{:>20}", pass.name);
251 if nightly_options::is_nightly_build() {
252 println!("\nPasses run with `--show-coverage`:");
253 for pass in passes::DEFAULT_COVERAGE_PASSES {
254 println!("{:>20}", pass.name);
256 println!("\nPasses run with `--show-coverage --document-private-items`:");
257 for pass in passes::PRIVATE_COVERAGE_PASSES {
258 println!("{:>20}", pass.name);
265 let color = session::config::parse_color(&matches);
266 let (json_rendered, _artifacts) = session::config::parse_json(&matches);
267 let error_format = session::config::parse_error_format(&matches, color, json_rendered);
269 let codegen_options = build_codegen_options(matches, error_format);
270 let debugging_options = build_debugging_options(matches, error_format);
272 let diag = new_handler(
275 debugging_options.treat_err_as_bug,
276 debugging_options.ui_testing(),
279 // check for deprecated options
280 check_deprecated_options(&matches, &diag);
282 let to_check = matches.opt_strs("check-theme");
283 if !to_check.is_empty() {
284 let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
287 println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
288 for theme_file in to_check.iter() {
289 print!(" - Checking \"{}\"...", theme_file);
290 let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag);
291 if !differences.is_empty() || !success {
294 if !differences.is_empty() {
295 println!("{}", differences.join("\n"));
307 if matches.free.is_empty() {
308 diag.struct_err("missing file operand").emit();
311 if matches.free.len() > 1 {
312 diag.struct_err("too many file operands").emit();
315 let input = PathBuf::from(&matches.free[0]);
320 .map(|s| SearchPath::from_cli_opt(s, error_format))
322 let externs = parse_externs(&matches, &debugging_options, error_format);
323 let extern_html_root_urls = match parse_extern_html_roots(&matches) {
326 diag.struct_err(err).emit();
331 let test_args = matches.opt_strs("test-args");
332 let test_args: Vec<String> =
333 test_args.iter().flat_map(|s| s.split_whitespace()).map(|s| s.to_string()).collect();
335 let should_test = matches.opt_present("test");
338 matches.opt_str("o").map(|s| PathBuf::from(&s)).unwrap_or_else(|| PathBuf::from("doc"));
339 let cfgs = matches.opt_strs("cfg");
341 let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
343 if let Some(ref p) = extension_css {
345 diag.struct_err("option --extend-css argument must be a file").emit();
350 let mut themes = Vec::new();
351 if matches.opt_present("theme") {
352 let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
354 for (theme_file, theme_s) in
355 matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
357 if !theme_file.is_file() {
358 diag.struct_err(&format!("invalid argument: \"{}\"", theme_s))
359 .help("arguments to --theme must be files")
363 if theme_file.extension() != Some(OsStr::new("css")) {
364 diag.struct_err(&format!("invalid argument: \"{}\"", theme_s)).emit();
367 let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
369 diag.struct_err(&format!("error loading theme file: \"{}\"", theme_s)).emit();
371 } else if !ret.is_empty() {
372 diag.struct_warn(&format!(
373 "theme file \"{}\" is missing CSS rules from the \
377 .warn("the theme may appear incorrect when loaded")
379 "to see what rules are missing, call `rustdoc \
380 --check-theme \"{}\"`",
385 themes.push(theme_file);
389 let edition = if let Some(e) = matches.opt_str("edition") {
393 diag.struct_err("could not parse edition").emit();
401 let mut id_map = html::markdown::IdMap::new();
402 id_map.populate(html::render::initial_ids());
403 let external_html = match ExternalHtml::load(
404 &matches.opt_strs("html-in-header"),
405 &matches.opt_strs("html-before-content"),
406 &matches.opt_strs("html-after-content"),
407 &matches.opt_strs("markdown-before-content"),
408 &matches.opt_strs("markdown-after-content"),
415 None => return Err(3),
418 match matches.opt_str("r").as_ref().map(|s| &**s) {
419 Some("rust") | None => {}
421 diag.struct_err(&format!("unknown input format: {}", s)).emit();
426 match matches.opt_str("w").as_ref().map(|s| &**s) {
427 Some("html") | None => {}
429 diag.struct_err(&format!("unknown output format: {}", s)).emit();
434 let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
435 if let Some(ref index_page) = index_page {
436 if !index_page.is_file() {
437 diag.struct_err("option `--index-page` argument must be a file").emit();
443 matches.opt_str("target").map_or(TargetTriple::from_triple(host_triple()), |target| {
444 if target.ends_with(".json") {
445 TargetTriple::TargetPath(PathBuf::from(target))
447 TargetTriple::TargetTriple(target)
451 let show_coverage = matches.opt_present("show-coverage");
452 let document_private = matches.opt_present("document-private-items");
454 let default_passes = if matches.opt_present("no-defaults") {
455 passes::DefaultPassOption::None
456 } else if show_coverage && document_private {
457 passes::DefaultPassOption::PrivateCoverage
458 } else if show_coverage {
459 passes::DefaultPassOption::Coverage
460 } else if document_private {
461 passes::DefaultPassOption::Private
463 passes::DefaultPassOption::Default
465 let manual_passes = matches.opt_strs("passes");
467 let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
470 diag.struct_err(&format!("unknown crate type: {}", e)).emit();
475 let crate_name = matches.opt_str("crate-name");
476 let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
477 let playground_url = matches.opt_str("playground-url");
478 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
479 let display_warnings = matches.opt_present("display-warnings");
480 let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
481 let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
482 let enable_minification = !matches.opt_present("disable-minification");
483 let markdown_no_toc = matches.opt_present("markdown-no-toc");
484 let markdown_css = matches.opt_strs("markdown-css");
485 let markdown_playground_url = matches.opt_str("markdown-playground-url");
486 let crate_version = matches.opt_str("crate-version");
487 let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
488 let static_root_path = matches.opt_str("static-root-path");
489 let generate_search_filter = !matches.opt_present("disable-per-crate-search");
490 let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
491 let generate_redirect_pages = matches.opt_present("generate-redirect-pages");
492 let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
493 let codegen_options_strs = matches.opt_strs("C");
494 let debugging_options_strs = matches.opt_strs("Z");
495 let lib_strs = matches.opt_strs("L");
496 let extern_strs = matches.opt_strs("extern");
497 let runtool = matches.opt_str("runtool");
498 let runtool_args = matches.opt_strs("runtool-arg");
499 let enable_per_target_ignores = matches.opt_present("enable-per-target-ignores");
501 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
514 codegen_options_strs,
516 debugging_options_strs,
533 enable_per_target_ignores,
535 render_options: RenderOptions {
540 sort_modules_alphabetically,
543 extern_html_root_urls,
551 markdown_playground_url,
552 generate_search_filter,
553 generate_redirect_pages,
558 /// Returns `true` if the file given as `self.input` is a Markdown file.
559 pub fn markdown_input(&self) -> bool {
560 self.input.extension().map_or(false, |e| e == "md" || e == "markdown")
564 /// Prints deprecation warnings for deprecated options
565 fn check_deprecated_options(matches: &getopts::Matches, diag: &errors::Handler) {
566 let deprecated_flags = ["input-format", "output-format", "no-defaults", "passes"];
568 for flag in deprecated_flags.iter() {
569 if matches.opt_present(flag) {
571 diag.struct_warn(&format!("the '{}' flag is considered deprecated", flag));
572 err.warn("please see https://github.com/rust-lang/rust/issues/44136");
574 if *flag == "no-defaults" {
575 err.help("you may want to use --document-private-items");
582 let removed_flags = ["plugins", "plugin-path"];
584 for &flag in removed_flags.iter() {
585 if matches.opt_present(flag) {
586 diag.struct_warn(&format!("the '{}' flag no longer functions", flag))
587 .warn("see CVE-2018-1000622")
593 /// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
594 /// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
595 /// describing the issue.
596 fn parse_extern_html_roots(
597 matches: &getopts::Matches,
598 ) -> Result<BTreeMap<String, String>, &'static str> {
599 let mut externs = BTreeMap::new();
600 for arg in &matches.opt_strs("extern-html-root-url") {
601 let mut parts = arg.splitn(2, '=');
602 let name = parts.next().ok_or("--extern-html-root-url must not be empty")?;
603 let url = parts.next().ok_or("--extern-html-root-url must be of the form name=url")?;
604 externs.insert(name.to_string(), url.to_string());