1 use std::collections::BTreeMap;
2 use std::convert::TryFrom;
5 use std::path::PathBuf;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_session::config::{self, parse_crate_types_from_list, parse_externs, CrateType};
10 use rustc_session::config::{
11 build_codegen_options, build_debugging_options, get_cmd_lint_options, host_triple,
14 use rustc_session::config::{CodegenOptions, DebuggingOptions, ErrorOutputType, Externs};
15 use rustc_session::getopts;
16 use rustc_session::lint::Level;
17 use rustc_session::search_paths::SearchPath;
18 use rustc_span::edition::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::render::StylePath;
26 use crate::html::static_files;
28 use crate::passes::{self, Condition, DefaultPassOption};
31 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
32 crate enum OutputFormat {
37 impl Default for OutputFormat {
38 fn default() -> OutputFormat {
44 crate fn is_json(&self) -> bool {
45 matches!(self, OutputFormat::Json)
49 impl TryFrom<&str> for OutputFormat {
52 fn try_from(value: &str) -> Result<Self, Self::Error> {
54 "json" => Ok(OutputFormat::Json),
55 "html" => Ok(OutputFormat::Html),
56 _ => Err(format!("unknown output format `{}`", value)),
61 /// Configuration options for rustdoc.
63 crate struct Options {
64 // Basic options / Options passed directly to rustc
65 /// The crate root or Markdown file to load.
67 /// The name of the crate being documented.
68 crate crate_name: Option<String>,
69 /// Whether or not this is a proc-macro crate
70 crate proc_macro_crate: bool,
71 /// How to format errors and warnings.
72 crate error_format: ErrorOutputType,
73 /// Library search paths to hand to the compiler.
74 crate libs: Vec<SearchPath>,
75 /// Library search paths strings to hand to the compiler.
76 crate lib_strs: Vec<String>,
77 /// The list of external crates to link against.
78 crate externs: Externs,
79 /// The list of external crates strings to link against.
80 crate extern_strs: Vec<String>,
81 /// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`.
82 crate cfgs: Vec<String>,
83 /// Codegen options to hand to the compiler.
84 crate codegen_options: CodegenOptions,
85 /// Codegen options strings to hand to the compiler.
86 crate codegen_options_strs: Vec<String>,
87 /// Debugging (`-Z`) options to pass to the compiler.
88 crate debugging_opts: DebuggingOptions,
89 /// Debugging (`-Z`) options strings to pass to the compiler.
90 crate debugging_opts_strs: Vec<String>,
91 /// The target used to compile the crate against.
92 crate target: TargetTriple,
93 /// Edition used when reading the crate. Defaults to "2015". Also used by default when
94 /// compiling doctests from the crate.
95 crate edition: Edition,
96 /// The path to the sysroot. Used during the compilation process.
97 crate maybe_sysroot: Option<PathBuf>,
98 /// Lint information passed over the command-line.
99 crate lint_opts: Vec<(String, Level)>,
100 /// Whether to ask rustc to describe the lints it knows. Practically speaking, this will not be
101 /// used, since we abort if we have no input file, but it's included for completeness.
102 crate describe_lints: bool,
103 /// What level to cap lints at.
104 crate lint_cap: Option<Level>,
106 // Options specific to running doctests
107 /// Whether we should run doctests instead of generating docs.
108 crate should_test: bool,
109 /// List of arguments to pass to the test harness, if running tests.
110 crate test_args: Vec<String>,
111 /// The working directory in which to run tests.
112 crate test_run_directory: Option<PathBuf>,
113 /// Optional path to persist the doctest executables to, defaults to a
114 /// temporary directory if not set.
115 crate persist_doctests: Option<PathBuf>,
116 /// Runtool to run doctests with
117 crate runtool: Option<String>,
118 /// Arguments to pass to the runtool
119 crate runtool_args: Vec<String>,
120 /// Whether to allow ignoring doctests on a per-target basis
121 /// For example, using ignore-foo to ignore running the doctest on any target that
122 /// contains "foo" as a substring
123 crate enable_per_target_ignores: bool,
125 /// The path to a rustc-like binary to build tests with. If not set, we
126 /// default to loading from `$sysroot/bin/rustc`.
127 crate test_builder: Option<PathBuf>,
129 // Options that affect the documentation process
130 /// The selected default set of passes to use.
132 /// Be aware: This option can come both from the CLI and from crate attributes!
133 crate default_passes: DefaultPassOption,
134 /// Any passes manually selected by the user.
136 /// Be aware: This option can come both from the CLI and from crate attributes!
137 crate manual_passes: Vec<String>,
138 /// Whether to display warnings during doc generation or while gathering doctests. By default,
139 /// all non-rustdoc-specific lints are allowed when generating docs.
140 crate display_warnings: bool,
141 /// Whether to run the `calculate-doc-coverage` pass, which counts the number of public items
142 /// with and without documentation.
143 crate show_coverage: bool,
145 // Options that alter generated documentation pages
146 /// Crate version to note on the sidebar of generated docs.
147 crate crate_version: Option<String>,
148 /// Collected options specific to outputting final pages.
149 crate render_options: RenderOptions,
150 /// The format that we output when rendering.
152 /// Currently used only for the `--show-coverage` option.
153 crate output_format: OutputFormat,
154 /// If this option is set to `true`, rustdoc will only run checks and not generate
156 crate run_check: bool,
159 impl fmt::Debug for Options {
160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161 struct FmtExterns<'a>(&'a Externs);
163 impl<'a> fmt::Debug for FmtExterns<'a> {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 f.debug_map().entries(self.0.iter()).finish()
169 f.debug_struct("Options")
170 .field("input", &self.input)
171 .field("crate_name", &self.crate_name)
172 .field("proc_macro_crate", &self.proc_macro_crate)
173 .field("error_format", &self.error_format)
174 .field("libs", &self.libs)
175 .field("externs", &FmtExterns(&self.externs))
176 .field("cfgs", &self.cfgs)
177 .field("codegen_options", &"...")
178 .field("debugging_options", &"...")
179 .field("target", &self.target)
180 .field("edition", &self.edition)
181 .field("maybe_sysroot", &self.maybe_sysroot)
182 .field("lint_opts", &self.lint_opts)
183 .field("describe_lints", &self.describe_lints)
184 .field("lint_cap", &self.lint_cap)
185 .field("should_test", &self.should_test)
186 .field("test_args", &self.test_args)
187 .field("test_run_directory", &self.test_run_directory)
188 .field("persist_doctests", &self.persist_doctests)
189 .field("default_passes", &self.default_passes)
190 .field("manual_passes", &self.manual_passes)
191 .field("display_warnings", &self.display_warnings)
192 .field("show_coverage", &self.show_coverage)
193 .field("crate_version", &self.crate_version)
194 .field("render_options", &self.render_options)
195 .field("runtool", &self.runtool)
196 .field("runtool_args", &self.runtool_args)
197 .field("enable-per-target-ignores", &self.enable_per_target_ignores)
198 .field("run_check", &self.run_check)
203 /// Configuration options for the HTML page-creation process.
204 #[derive(Clone, Debug)]
205 crate struct RenderOptions {
206 /// Output directory to generate docs into. Defaults to `doc`.
207 crate output: PathBuf,
208 /// External files to insert into generated pages.
209 crate external_html: ExternalHtml,
210 /// A pre-populated `IdMap` with the default headings and any headings added by Markdown files
211 /// processed by `external_html`.
213 /// If present, playground URL to use in the "Run" button added to code samples.
215 /// Be aware: This option can come both from the CLI and from crate attributes!
216 crate playground_url: Option<String>,
217 /// Whether to sort modules alphabetically on a module page instead of using declaration order.
218 /// `true` by default.
220 // FIXME(misdreavus): the flag name is `--sort-modules-by-appearance` but the meaning is
221 // inverted once read.
222 crate sort_modules_alphabetically: bool,
223 /// List of themes to extend the docs with. Original argument name is included to assist in
224 /// displaying errors if it fails a theme check.
225 crate themes: Vec<StylePath>,
226 /// If present, CSS file that contains rules to add to the default CSS.
227 crate extension_css: Option<PathBuf>,
228 /// A map of crate names to the URL to use instead of querying the crate's `html_root_url`.
229 crate extern_html_root_urls: BTreeMap<String, String>,
230 /// A map of the default settings (values are as for DOM storage API). Keys should lack the
231 /// `rustdoc-` prefix.
232 crate default_settings: FxHashMap<String, String>,
233 /// If present, suffix added to CSS/JavaScript files when referencing them in generated pages.
234 crate resource_suffix: String,
235 /// Whether to run the static CSS/JavaScript through a minifier when outputting them. `true` by
238 // FIXME(misdreavus): the flag name is `--disable-minification` but the meaning is inverted
240 crate enable_minification: bool,
241 /// Whether to create an index page in the root of the output directory. If this is true but
242 /// `enable_index_page` is None, generate a static listing of crates instead.
243 crate enable_index_page: bool,
244 /// A file to use as the index page at the root of the output directory. Overrides
245 /// `enable_index_page` to be true if set.
246 crate index_page: Option<PathBuf>,
247 /// An optional path to use as the location of static files. If not set, uses combinations of
248 /// `../` to reach the documentation root.
249 crate static_root_path: Option<String>,
251 // Options specific to reading standalone Markdown files
252 /// Whether to generate a table of contents on the output file when reading a standalone
254 crate markdown_no_toc: bool,
255 /// Additional CSS files to link in pages generated from standalone Markdown files.
256 crate markdown_css: Vec<String>,
257 /// If present, playground URL to use in the "Run" button added to code samples generated from
258 /// standalone Markdown files. If not present, `playground_url` is used.
259 crate markdown_playground_url: Option<String>,
260 /// If false, the `select` element to have search filtering by crates on rendered docs
261 /// won't be generated.
262 crate generate_search_filter: bool,
263 /// Document items that have lower than `pub` visibility.
264 crate document_private: bool,
265 /// Document items that have `doc(hidden)`.
266 crate document_hidden: bool,
267 /// If `true`, generate a JSON file in the crate folder instead of HTML redirection files.
268 crate generate_redirect_map: bool,
269 crate unstable_features: rustc_feature::UnstableFeatures,
270 crate emit: Vec<EmitType>,
273 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
274 crate enum EmitType {
280 impl FromStr for EmitType {
283 fn from_str(s: &str) -> Result<Self, Self::Err> {
286 "unversioned-shared-resources" => Ok(Unversioned),
287 "toolchain-shared-resources" => Ok(Toolchain),
288 "invocation-specific" => Ok(InvocationSpecific),
295 crate fn should_emit_crate(&self) -> bool {
296 self.emit.is_empty() || self.emit.contains(&EmitType::InvocationSpecific)
301 /// Parses the given command-line for options. If an error message or other early-return has
302 /// been printed, returns `Err` with the exit code.
303 crate fn from_matches(matches: &getopts::Matches) -> Result<Options, i32> {
304 // Check for unstable options.
305 nightly_options::check_nightly_options(&matches, &opts());
307 if matches.opt_present("h") || matches.opt_present("help") {
308 crate::usage("rustdoc");
310 } else if matches.opt_present("version") {
311 rustc_driver::version("rustdoc", &matches);
315 if matches.opt_strs("passes") == ["list"] {
316 println!("Available passes for running rustdoc:");
317 for pass in passes::PASSES {
318 println!("{:>20} - {}", pass.name, pass.description);
320 println!("\nDefault passes for rustdoc:");
321 for p in passes::DEFAULT_PASSES {
322 print!("{:>20}", p.pass.name);
323 println_condition(p.condition);
326 if nightly_options::match_is_nightly_build(matches) {
327 println!("\nPasses run with `--show-coverage`:");
328 for p in passes::COVERAGE_PASSES {
329 print!("{:>20}", p.pass.name);
330 println_condition(p.condition);
334 fn println_condition(condition: Condition) {
337 Always => println!(),
338 WhenDocumentPrivate => println!(" (when --document-private-items)"),
339 WhenNotDocumentPrivate => println!(" (when not --document-private-items)"),
340 WhenNotDocumentHidden => println!(" (when not --document-hidden-items)"),
347 if matches.opt_strs("print").iter().any(|opt| opt == "unversioned-files") {
348 for file in crate::html::render::FILES_UNVERSIONED.keys() {
349 println!("{}", file);
354 let color = config::parse_color(&matches);
355 let (json_rendered, _artifacts) = config::parse_json(&matches);
356 let error_format = config::parse_error_format(&matches, color, json_rendered);
358 let codegen_options = build_codegen_options(matches, error_format);
359 let debugging_opts = build_debugging_options(matches, error_format);
361 let diag = new_handler(error_format, None, &debugging_opts);
363 // check for deprecated options
364 check_deprecated_options(&matches, &diag);
366 let mut emit = Vec::new();
367 for list in matches.opt_strs("emit") {
368 for kind in list.split(',') {
370 Ok(kind) => emit.push(kind),
372 diag.err(&format!("unrecognized emission type: {}", kind));
379 let to_check = matches.opt_strs("check-theme");
380 if !to_check.is_empty() {
381 let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
384 println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
385 for theme_file in to_check.iter() {
386 print!(" - Checking \"{}\"...", theme_file);
387 let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag);
388 if !differences.is_empty() || !success {
391 if !differences.is_empty() {
392 println!("{}", differences.join("\n"));
404 if matches.free.is_empty() {
405 diag.struct_err("missing file operand").emit();
408 if matches.free.len() > 1 {
409 diag.struct_err("too many file operands").emit();
412 let input = PathBuf::from(&matches.free[0]);
417 .map(|s| SearchPath::from_cli_opt(s, error_format))
419 let externs = parse_externs(&matches, &debugging_opts, error_format);
420 let extern_html_root_urls = match parse_extern_html_roots(&matches) {
423 diag.struct_err(err).emit();
428 let default_settings: Vec<Vec<(String, String)>> = vec![
430 .opt_str("default-theme")
434 ("use-system-theme".to_string(), "false".to_string()),
435 ("theme".to_string(), theme.to_string()),
441 .opt_strs("default-setting")
443 .map(|s| match s.split_once('=') {
444 None => (s.clone(), "true".to_string()),
445 Some((k, v)) => (k.to_string(), v.to_string()),
449 let default_settings = default_settings.into_iter().flatten().collect();
451 let test_args = matches.opt_strs("test-args");
452 let test_args: Vec<String> =
453 test_args.iter().flat_map(|s| s.split_whitespace()).map(|s| s.to_string()).collect();
455 let should_test = matches.opt_present("test");
458 matches.opt_str("o").map(|s| PathBuf::from(&s)).unwrap_or_else(|| PathBuf::from("doc"));
459 let cfgs = matches.opt_strs("cfg");
461 let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
463 if let Some(ref p) = extension_css {
465 diag.struct_err("option --extend-css argument must be a file").emit();
470 let mut themes = Vec::new();
471 if matches.opt_present("theme") {
472 let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
474 for (theme_file, theme_s) in
475 matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
477 if !theme_file.is_file() {
478 diag.struct_err(&format!("invalid argument: \"{}\"", theme_s))
479 .help("arguments to --theme must be files")
483 if theme_file.extension() != Some(OsStr::new("css")) {
484 diag.struct_err(&format!("invalid argument: \"{}\"", theme_s)).emit();
487 let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
489 diag.struct_err(&format!("error loading theme file: \"{}\"", theme_s)).emit();
491 } else if !ret.is_empty() {
492 diag.struct_warn(&format!(
493 "theme file \"{}\" is missing CSS rules from the default theme",
496 .warn("the theme may appear incorrect when loaded")
498 "to see what rules are missing, call `rustdoc --check-theme \"{}\"`",
503 themes.push(StylePath { path: theme_file, disabled: true });
507 let edition = config::parse_crate_edition(&matches);
509 let mut id_map = html::markdown::IdMap::new();
510 id_map.populate(&html::render::INITIAL_IDS);
511 let external_html = match ExternalHtml::load(
512 &matches.opt_strs("html-in-header"),
513 &matches.opt_strs("html-before-content"),
514 &matches.opt_strs("html-after-content"),
515 &matches.opt_strs("markdown-before-content"),
516 &matches.opt_strs("markdown-after-content"),
517 nightly_options::match_is_nightly_build(&matches),
524 None => return Err(3),
527 match matches.opt_str("r").as_deref() {
528 Some("rust") | None => {}
530 diag.struct_err(&format!("unknown input format: {}", s)).emit();
535 let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
536 if let Some(ref index_page) = index_page {
537 if !index_page.is_file() {
538 diag.struct_err("option `--index-page` argument must be a file").emit();
544 matches.opt_str("target").map_or(TargetTriple::from_triple(host_triple()), |target| {
545 if target.ends_with(".json") {
546 TargetTriple::TargetPath(PathBuf::from(target))
548 TargetTriple::TargetTriple(target)
552 let show_coverage = matches.opt_present("show-coverage");
554 let default_passes = if matches.opt_present("no-defaults") {
555 passes::DefaultPassOption::None
556 } else if show_coverage {
557 passes::DefaultPassOption::Coverage
559 passes::DefaultPassOption::Default
561 let manual_passes = matches.opt_strs("passes");
563 let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
566 diag.struct_err(&format!("unknown crate type: {}", e)).emit();
571 let output_format = match matches.opt_str("output-format") {
572 Some(s) => match OutputFormat::try_from(s.as_str()) {
575 && !(show_coverage || nightly_options::match_is_nightly_build(matches))
577 diag.struct_err("json output format isn't supported for doc generation")
580 } else if !out_fmt.is_json() && show_coverage {
582 "html output format isn't supported for the --show-coverage option",
590 diag.struct_err(&e).emit();
594 None => OutputFormat::default(),
596 let crate_name = matches.opt_str("crate-name");
597 let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
598 let playground_url = matches.opt_str("playground-url");
599 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
600 let display_warnings = matches.opt_present("display-warnings");
601 let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
602 let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
603 let enable_minification = !matches.opt_present("disable-minification");
604 let markdown_no_toc = matches.opt_present("markdown-no-toc");
605 let markdown_css = matches.opt_strs("markdown-css");
606 let markdown_playground_url = matches.opt_str("markdown-playground-url");
607 let crate_version = matches.opt_str("crate-version");
608 let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
609 let static_root_path = matches.opt_str("static-root-path");
610 let generate_search_filter = !matches.opt_present("disable-per-crate-search");
611 let test_run_directory = matches.opt_str("test-run-directory").map(PathBuf::from);
612 let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
613 let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
614 let codegen_options_strs = matches.opt_strs("C");
615 let debugging_opts_strs = matches.opt_strs("Z");
616 let lib_strs = matches.opt_strs("L");
617 let extern_strs = matches.opt_strs("extern");
618 let runtool = matches.opt_str("runtool");
619 let runtool_args = matches.opt_strs("runtool-arg");
620 let enable_per_target_ignores = matches.opt_present("enable-per-target-ignores");
621 let document_private = matches.opt_present("document-private-items");
622 let document_hidden = matches.opt_present("document-hidden-items");
623 let run_check = matches.opt_present("check");
624 let generate_redirect_map = matches.opt_present("generate-redirect-map");
626 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
638 codegen_options_strs,
658 enable_per_target_ignores,
661 render_options: RenderOptions {
666 sort_modules_alphabetically,
669 extern_html_root_urls,
678 markdown_playground_url,
679 generate_search_filter,
682 generate_redirect_map,
683 unstable_features: rustc_feature::UnstableFeatures::from_environment(
684 crate_name.as_deref(),
693 /// Returns `true` if the file given as `self.input` is a Markdown file.
694 crate fn markdown_input(&self) -> bool {
695 self.input.extension().map_or(false, |e| e == "md" || e == "markdown")
699 /// Prints deprecation warnings for deprecated options
700 fn check_deprecated_options(matches: &getopts::Matches, diag: &rustc_errors::Handler) {
701 let deprecated_flags = ["input-format", "output-format", "no-defaults", "passes"];
703 for flag in deprecated_flags.iter() {
704 if matches.opt_present(flag) {
705 if *flag == "output-format"
706 && (matches.opt_present("show-coverage")
707 || nightly_options::match_is_nightly_build(matches))
711 let mut err = diag.struct_warn(&format!("the `{}` flag is deprecated", flag));
713 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
714 for more information",
717 if *flag == "no-defaults" {
718 err.help("you may want to use --document-private-items");
725 let removed_flags = ["plugins", "plugin-path"];
727 for &flag in removed_flags.iter() {
728 if matches.opt_present(flag) {
729 diag.struct_warn(&format!("the '{}' flag no longer functions", flag))
730 .warn("see CVE-2018-1000622")
736 /// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
737 /// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
738 /// describing the issue.
739 fn parse_extern_html_roots(
740 matches: &getopts::Matches,
741 ) -> Result<BTreeMap<String, String>, &'static str> {
742 let mut externs = BTreeMap::new();
743 for arg in &matches.opt_strs("extern-html-root-url") {
745 arg.split_once('=').ok_or("--extern-html-root-url must be of the form name=url")?;
746 externs.insert(name.to_string(), url.to_string());