1 use std::collections::BTreeMap;
2 use std::convert::TryFrom;
5 use std::path::PathBuf;
7 use rustc_session::config::{self, parse_crate_types_from_list, parse_externs, CrateType};
8 use rustc_session::config::{
9 build_codegen_options, build_debugging_options, get_cmd_lint_options, host_triple,
12 use rustc_session::config::{CodegenOptions, DebuggingOptions, ErrorOutputType, Externs};
13 use rustc_session::getopts;
14 use rustc_session::lint::Level;
15 use rustc_session::search_paths::SearchPath;
16 use rustc_span::edition::{Edition, DEFAULT_EDITION};
17 use rustc_target::spec::TargetTriple;
19 use crate::core::new_handler;
20 use crate::externalfiles::ExternalHtml;
22 use crate::html::markdown::IdMap;
23 use crate::html::render::StylePath;
24 use crate::html::static_files;
26 use crate::passes::{self, Condition, DefaultPassOption};
29 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
30 pub enum OutputFormat {
36 pub fn is_json(&self) -> bool {
38 OutputFormat::Json => true,
44 impl TryFrom<&str> for OutputFormat {
47 fn try_from(value: &str) -> Result<Self, Self::Error> {
49 "json" => Ok(OutputFormat::Json),
50 "html" => Ok(OutputFormat::Html),
51 _ => Err(format!("unknown output format `{}`", value)),
56 /// Configuration options for rustdoc.
59 // Basic options / Options passed directly to rustc
60 /// The crate root or Markdown file to load.
62 /// The name of the crate being documented.
63 pub crate_name: Option<String>,
64 /// Whether or not this is a proc-macro crate
65 pub proc_macro_crate: bool,
66 /// How to format errors and warnings.
67 pub error_format: ErrorOutputType,
68 /// Library search paths to hand to the compiler.
69 pub libs: Vec<SearchPath>,
70 /// Library search paths strings to hand to the compiler.
71 pub lib_strs: Vec<String>,
72 /// The list of external crates to link against.
74 /// The list of external crates strings to link against.
75 pub extern_strs: Vec<String>,
76 /// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`.
77 pub cfgs: Vec<String>,
78 /// Codegen options to hand to the compiler.
79 pub codegen_options: CodegenOptions,
80 /// Codegen options strings to hand to the compiler.
81 pub codegen_options_strs: Vec<String>,
82 /// Debugging (`-Z`) options to pass to the compiler.
83 pub debugging_options: DebuggingOptions,
84 /// Debugging (`-Z`) options strings to pass to the compiler.
85 pub debugging_options_strs: Vec<String>,
86 /// The target used to compile the crate against.
87 pub target: TargetTriple,
88 /// Edition used when reading the crate. Defaults to "2015". Also used by default when
89 /// compiling doctests from the crate.
91 /// The path to the sysroot. Used during the compilation process.
92 pub maybe_sysroot: Option<PathBuf>,
93 /// Lint information passed over the command-line.
94 pub lint_opts: Vec<(String, Level)>,
95 /// Whether to ask rustc to describe the lints it knows. Practically speaking, this will not be
96 /// used, since we abort if we have no input file, but it's included for completeness.
97 pub describe_lints: bool,
98 /// What level to cap lints at.
99 pub lint_cap: Option<Level>,
101 // Options specific to running doctests
102 /// Whether we should run doctests instead of generating docs.
103 pub should_test: bool,
104 /// List of arguments to pass to the test harness, if running tests.
105 pub test_args: Vec<String>,
106 /// Optional path to persist the doctest executables to, defaults to a
107 /// temporary directory if not set.
108 pub persist_doctests: Option<PathBuf>,
109 /// Runtool to run doctests with
110 pub runtool: Option<String>,
111 /// Arguments to pass to the runtool
112 pub runtool_args: Vec<String>,
113 /// Whether to allow ignoring doctests on a per-target basis
114 /// For example, using ignore-foo to ignore running the doctest on any target that
115 /// contains "foo" as a substring
116 pub enable_per_target_ignores: bool,
118 /// The path to a rustc-like binary to build tests with. If not set, we
119 /// default to loading from $sysroot/bin/rustc.
120 pub test_builder: Option<PathBuf>,
122 // Options that affect the documentation process
123 /// The selected default set of passes to use.
125 /// Be aware: This option can come both from the CLI and from crate attributes!
126 pub default_passes: DefaultPassOption,
127 /// Any passes manually selected by the user.
129 /// Be aware: This option can come both from the CLI and from crate attributes!
130 pub manual_passes: Vec<String>,
131 /// Whether to display warnings during doc generation or while gathering doctests. By default,
132 /// all non-rustdoc-specific lints are allowed when generating docs.
133 pub display_warnings: bool,
134 /// Whether to run the `calculate-doc-coverage` pass, which counts the number of public items
135 /// with and without documentation.
136 pub show_coverage: bool,
138 // Options that alter generated documentation pages
139 /// Crate version to note on the sidebar of generated docs.
140 pub crate_version: Option<String>,
141 /// Collected options specific to outputting final pages.
142 pub render_options: RenderOptions,
143 /// Output format rendering (used only for "show-coverage" option for the moment)
144 pub output_format: Option<OutputFormat>,
147 impl fmt::Debug for Options {
148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149 struct FmtExterns<'a>(&'a Externs);
151 impl<'a> fmt::Debug for FmtExterns<'a> {
152 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153 f.debug_map().entries(self.0.iter()).finish()
157 f.debug_struct("Options")
158 .field("input", &self.input)
159 .field("crate_name", &self.crate_name)
160 .field("proc_macro_crate", &self.proc_macro_crate)
161 .field("error_format", &self.error_format)
162 .field("libs", &self.libs)
163 .field("externs", &FmtExterns(&self.externs))
164 .field("cfgs", &self.cfgs)
165 .field("codegen_options", &"...")
166 .field("debugging_options", &"...")
167 .field("target", &self.target)
168 .field("edition", &self.edition)
169 .field("maybe_sysroot", &self.maybe_sysroot)
170 .field("lint_opts", &self.lint_opts)
171 .field("describe_lints", &self.describe_lints)
172 .field("lint_cap", &self.lint_cap)
173 .field("should_test", &self.should_test)
174 .field("test_args", &self.test_args)
175 .field("persist_doctests", &self.persist_doctests)
176 .field("default_passes", &self.default_passes)
177 .field("manual_passes", &self.manual_passes)
178 .field("display_warnings", &self.display_warnings)
179 .field("show_coverage", &self.show_coverage)
180 .field("crate_version", &self.crate_version)
181 .field("render_options", &self.render_options)
182 .field("runtool", &self.runtool)
183 .field("runtool_args", &self.runtool_args)
184 .field("enable-per-target-ignores", &self.enable_per_target_ignores)
189 /// Configuration options for the HTML page-creation process.
190 #[derive(Clone, Debug)]
191 pub struct RenderOptions {
192 /// Output directory to generate docs into. Defaults to `doc`.
194 /// External files to insert into generated pages.
195 pub external_html: ExternalHtml,
196 /// A pre-populated `IdMap` with the default headings and any headings added by Markdown files
197 /// processed by `external_html`.
199 /// If present, playground URL to use in the "Run" button added to code samples.
201 /// Be aware: This option can come both from the CLI and from crate attributes!
202 pub playground_url: Option<String>,
203 /// Whether to sort modules alphabetically on a module page instead of using declaration order.
204 /// `true` by default.
206 // FIXME(misdreavus): the flag name is `--sort-modules-by-appearance` but the meaning is
207 // inverted once read.
208 pub sort_modules_alphabetically: bool,
209 /// List of themes to extend the docs with. Original argument name is included to assist in
210 /// displaying errors if it fails a theme check.
211 pub themes: Vec<StylePath>,
212 /// If present, CSS file that contains rules to add to the default CSS.
213 pub extension_css: Option<PathBuf>,
214 /// A map of crate names to the URL to use instead of querying the crate's `html_root_url`.
215 pub extern_html_root_urls: BTreeMap<String, String>,
216 /// If present, suffix added to CSS/JavaScript files when referencing them in generated pages.
217 pub resource_suffix: String,
218 /// Whether to run the static CSS/JavaScript through a minifier when outputting them. `true` by
221 // FIXME(misdreavus): the flag name is `--disable-minification` but the meaning is inverted
223 pub enable_minification: bool,
224 /// Whether to create an index page in the root of the output directory. If this is true but
225 /// `enable_index_page` is None, generate a static listing of crates instead.
226 pub enable_index_page: bool,
227 /// A file to use as the index page at the root of the output directory. Overrides
228 /// `enable_index_page` to be true if set.
229 pub index_page: Option<PathBuf>,
230 /// An optional path to use as the location of static files. If not set, uses combinations of
231 /// `../` to reach the documentation root.
232 pub static_root_path: Option<String>,
234 // Options specific to reading standalone Markdown files
235 /// Whether to generate a table of contents on the output file when reading a standalone
237 pub markdown_no_toc: bool,
238 /// Additional CSS files to link in pages generated from standalone Markdown files.
239 pub markdown_css: Vec<String>,
240 /// If present, playground URL to use in the "Run" button added to code samples generated from
241 /// standalone Markdown files. If not present, `playground_url` is used.
242 pub markdown_playground_url: Option<String>,
243 /// If false, the `select` element to have search filtering by crates on rendered docs
244 /// won't be generated.
245 pub generate_search_filter: bool,
246 /// Document items that have lower than `pub` visibility.
247 pub document_private: bool,
248 /// Document items that have `doc(hidden)`.
249 pub document_hidden: bool,
253 /// Parses the given command-line for options. If an error message or other early-return has
254 /// been printed, returns `Err` with the exit code.
255 pub fn from_matches(matches: &getopts::Matches) -> Result<Options, i32> {
256 // Check for unstable options.
257 nightly_options::check_nightly_options(&matches, &opts());
259 if matches.opt_present("h") || matches.opt_present("help") {
260 crate::usage("rustdoc");
262 } else if matches.opt_present("version") {
263 rustc_driver::version("rustdoc", &matches);
267 if matches.opt_strs("passes") == ["list"] {
268 println!("Available passes for running rustdoc:");
269 for pass in passes::PASSES {
270 println!("{:>20} - {}", pass.name, pass.description);
272 println!("\nDefault passes for rustdoc:");
273 for p in passes::DEFAULT_PASSES {
274 print!("{:>20}", p.pass.name);
275 println_condition(p.condition);
278 if nightly_options::is_nightly_build() {
279 println!("\nPasses run with `--show-coverage`:");
280 for p in passes::COVERAGE_PASSES {
281 print!("{:>20}", p.pass.name);
282 println_condition(p.condition);
286 fn println_condition(condition: Condition) {
289 Always => println!(),
290 WhenDocumentPrivate => println!(" (when --document-private-items)"),
291 WhenNotDocumentPrivate => println!(" (when not --document-private-items)"),
292 WhenNotDocumentHidden => println!(" (when not --document-hidden-items)"),
299 let color = config::parse_color(&matches);
300 let (json_rendered, _artifacts) = config::parse_json(&matches);
301 let error_format = config::parse_error_format(&matches, color, json_rendered);
303 let codegen_options = build_codegen_options(matches, error_format);
304 let debugging_options = build_debugging_options(matches, error_format);
306 let diag = new_handler(error_format, None, &debugging_options);
308 // check for deprecated options
309 check_deprecated_options(&matches, &diag);
311 let to_check = matches.opt_strs("check-theme");
312 if !to_check.is_empty() {
313 let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
316 println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
317 for theme_file in to_check.iter() {
318 print!(" - Checking \"{}\"...", theme_file);
319 let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag);
320 if !differences.is_empty() || !success {
323 if !differences.is_empty() {
324 println!("{}", differences.join("\n"));
336 if matches.free.is_empty() {
337 diag.struct_err("missing file operand").emit();
340 if matches.free.len() > 1 {
341 diag.struct_err("too many file operands").emit();
344 let input = PathBuf::from(&matches.free[0]);
349 .map(|s| SearchPath::from_cli_opt(s, error_format))
351 let externs = parse_externs(&matches, &debugging_options, error_format);
352 let extern_html_root_urls = match parse_extern_html_roots(&matches) {
355 diag.struct_err(err).emit();
360 let test_args = matches.opt_strs("test-args");
361 let test_args: Vec<String> =
362 test_args.iter().flat_map(|s| s.split_whitespace()).map(|s| s.to_string()).collect();
364 let should_test = matches.opt_present("test");
367 matches.opt_str("o").map(|s| PathBuf::from(&s)).unwrap_or_else(|| PathBuf::from("doc"));
368 let cfgs = matches.opt_strs("cfg");
370 let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
372 if let Some(ref p) = extension_css {
374 diag.struct_err("option --extend-css argument must be a file").emit();
379 let mut themes = Vec::new();
380 if matches.opt_present("theme") {
381 let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
383 for (theme_file, theme_s) in
384 matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
386 if !theme_file.is_file() {
387 diag.struct_err(&format!("invalid argument: \"{}\"", theme_s))
388 .help("arguments to --theme must be files")
392 if theme_file.extension() != Some(OsStr::new("css")) {
393 diag.struct_err(&format!("invalid argument: \"{}\"", theme_s)).emit();
396 let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
398 diag.struct_err(&format!("error loading theme file: \"{}\"", theme_s)).emit();
400 } else if !ret.is_empty() {
401 diag.struct_warn(&format!(
402 "theme file \"{}\" is missing CSS rules from the \
406 .warn("the theme may appear incorrect when loaded")
408 "to see what rules are missing, call `rustdoc \
409 --check-theme \"{}\"`",
414 themes.push(StylePath { path: theme_file, disabled: true });
418 let edition = if let Some(e) = matches.opt_str("edition") {
422 diag.struct_err("could not parse edition").emit();
430 let mut id_map = html::markdown::IdMap::new();
431 id_map.populate(html::render::initial_ids());
432 let external_html = match ExternalHtml::load(
433 &matches.opt_strs("html-in-header"),
434 &matches.opt_strs("html-before-content"),
435 &matches.opt_strs("html-after-content"),
436 &matches.opt_strs("markdown-before-content"),
437 &matches.opt_strs("markdown-after-content"),
444 None => return Err(3),
447 match matches.opt_str("r").as_deref() {
448 Some("rust") | None => {}
450 diag.struct_err(&format!("unknown input format: {}", s)).emit();
455 let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
456 if let Some(ref index_page) = index_page {
457 if !index_page.is_file() {
458 diag.struct_err("option `--index-page` argument must be a file").emit();
464 matches.opt_str("target").map_or(TargetTriple::from_triple(host_triple()), |target| {
465 if target.ends_with(".json") {
466 TargetTriple::TargetPath(PathBuf::from(target))
468 TargetTriple::TargetTriple(target)
472 let show_coverage = matches.opt_present("show-coverage");
474 let default_passes = if matches.opt_present("no-defaults") {
475 passes::DefaultPassOption::None
476 } else if show_coverage {
477 passes::DefaultPassOption::Coverage
479 passes::DefaultPassOption::Default
481 let manual_passes = matches.opt_strs("passes");
483 let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
486 diag.struct_err(&format!("unknown crate type: {}", e)).emit();
491 let output_format = match matches.opt_str("output-format") {
492 Some(s) => match OutputFormat::try_from(s.as_str()) {
494 if o.is_json() && !show_coverage {
495 diag.struct_err("json output format isn't supported for doc generation")
498 } else if !o.is_json() && show_coverage {
500 "html output format isn't supported for the --show-coverage option",
508 diag.struct_err(&e).emit();
514 let crate_name = matches.opt_str("crate-name");
515 let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
516 let playground_url = matches.opt_str("playground-url");
517 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
518 let display_warnings = matches.opt_present("display-warnings");
519 let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
520 let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
521 let enable_minification = !matches.opt_present("disable-minification");
522 let markdown_no_toc = matches.opt_present("markdown-no-toc");
523 let markdown_css = matches.opt_strs("markdown-css");
524 let markdown_playground_url = matches.opt_str("markdown-playground-url");
525 let crate_version = matches.opt_str("crate-version");
526 let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
527 let static_root_path = matches.opt_str("static-root-path");
528 let generate_search_filter = !matches.opt_present("disable-per-crate-search");
529 let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
530 let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
531 let codegen_options_strs = matches.opt_strs("C");
532 let debugging_options_strs = matches.opt_strs("Z");
533 let lib_strs = matches.opt_strs("L");
534 let extern_strs = matches.opt_strs("extern");
535 let runtool = matches.opt_str("runtool");
536 let runtool_args = matches.opt_strs("runtool-arg");
537 let enable_per_target_ignores = matches.opt_present("enable-per-target-ignores");
538 let document_private = matches.opt_present("document-private-items");
539 let document_hidden = matches.opt_present("document-hidden-items");
541 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
554 codegen_options_strs,
556 debugging_options_strs,
573 enable_per_target_ignores,
575 render_options: RenderOptions {
580 sort_modules_alphabetically,
583 extern_html_root_urls,
591 markdown_playground_url,
592 generate_search_filter,
600 /// Returns `true` if the file given as `self.input` is a Markdown file.
601 pub fn markdown_input(&self) -> bool {
602 self.input.extension().map_or(false, |e| e == "md" || e == "markdown")
606 /// Prints deprecation warnings for deprecated options
607 fn check_deprecated_options(matches: &getopts::Matches, diag: &rustc_errors::Handler) {
608 let deprecated_flags = ["input-format", "output-format", "no-defaults", "passes"];
610 for flag in deprecated_flags.iter() {
611 if matches.opt_present(flag) {
612 if *flag == "output-format" && matches.opt_present("show-coverage") {
616 diag.struct_warn(&format!("the '{}' flag is considered deprecated", flag));
618 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
619 for more information",
622 if *flag == "no-defaults" {
623 err.help("you may want to use --document-private-items");
630 let removed_flags = ["plugins", "plugin-path"];
632 for &flag in removed_flags.iter() {
633 if matches.opt_present(flag) {
634 diag.struct_warn(&format!("the '{}' flag no longer functions", flag))
635 .warn("see CVE-2018-1000622")
641 /// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
642 /// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
643 /// describing the issue.
644 fn parse_extern_html_roots(
645 matches: &getopts::Matches,
646 ) -> Result<BTreeMap<String, String>, &'static str> {
647 let mut externs = BTreeMap::new();
648 for arg in &matches.opt_strs("extern-html-root-url") {
649 let mut parts = arg.splitn(2, '=');
650 let name = parts.next().ok_or("--extern-html-root-url must not be empty")?;
651 let url = parts.next().ok_or("--extern-html-root-url must be of the form name=url")?;
652 externs.insert(name.to_string(), url.to_string());