1 use std::collections::{BTreeMap, HashMap};
2 use std::convert::TryFrom;
5 use std::path::PathBuf;
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_hir::def_id::DefId;
9 use rustc_middle::middle::privacy::AccessLevels;
10 use rustc_session::config::{self, parse_crate_types_from_list, parse_externs, CrateType};
11 use rustc_session::config::{
12 build_codegen_options, build_debugging_options, get_cmd_lint_options, host_triple,
15 use rustc_session::config::{CodegenOptions, DebuggingOptions, ErrorOutputType, Externs};
16 use rustc_session::getopts;
17 use rustc_session::lint::Level;
18 use rustc_session::search_paths::SearchPath;
19 use rustc_span::edition::{Edition, DEFAULT_EDITION};
20 use rustc_target::spec::TargetTriple;
22 use crate::core::new_handler;
23 use crate::externalfiles::ExternalHtml;
25 use crate::html::markdown::IdMap;
26 use crate::html::render::StylePath;
27 use crate::html::static_files;
29 use crate::passes::{self, Condition, DefaultPassOption};
32 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
33 crate enum OutputFormat {
39 crate fn is_json(&self) -> bool {
41 OutputFormat::Json => true,
47 impl TryFrom<&str> for OutputFormat {
50 fn try_from(value: &str) -> Result<Self, Self::Error> {
52 "json" => Ok(OutputFormat::Json),
53 "html" => Ok(OutputFormat::Html),
54 _ => Err(format!("unknown output format `{}`", value)),
59 /// Configuration options for rustdoc.
61 crate struct Options {
62 // Basic options / Options passed directly to rustc
63 /// The crate root or Markdown file to load.
65 /// The name of the crate being documented.
66 crate crate_name: Option<String>,
67 /// Whether or not this is a proc-macro crate
68 crate proc_macro_crate: bool,
69 /// How to format errors and warnings.
70 crate error_format: ErrorOutputType,
71 /// Library search paths to hand to the compiler.
72 crate libs: Vec<SearchPath>,
73 /// Library search paths strings to hand to the compiler.
74 crate lib_strs: Vec<String>,
75 /// The list of external crates to link against.
76 crate externs: Externs,
77 /// The list of external crates strings to link against.
78 crate extern_strs: Vec<String>,
79 /// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`.
80 crate cfgs: Vec<String>,
81 /// Codegen options to hand to the compiler.
82 crate codegen_options: CodegenOptions,
83 /// Codegen options strings to hand to the compiler.
84 crate codegen_options_strs: Vec<String>,
85 /// Debugging (`-Z`) options to pass to the compiler.
86 crate debugging_opts: DebuggingOptions,
87 /// Debugging (`-Z`) options strings to pass to the compiler.
88 crate debugging_opts_strs: Vec<String>,
89 /// The target used to compile the crate against.
90 crate target: TargetTriple,
91 /// Edition used when reading the crate. Defaults to "2015". Also used by default when
92 /// compiling doctests from the crate.
93 crate edition: Edition,
94 /// The path to the sysroot. Used during the compilation process.
95 crate maybe_sysroot: Option<PathBuf>,
96 /// Lint information passed over the command-line.
97 crate lint_opts: Vec<(String, Level)>,
98 /// Whether to ask rustc to describe the lints it knows. Practically speaking, this will not be
99 /// used, since we abort if we have no input file, but it's included for completeness.
100 crate describe_lints: bool,
101 /// What level to cap lints at.
102 crate lint_cap: Option<Level>,
104 // Options specific to running doctests
105 /// Whether we should run doctests instead of generating docs.
106 crate should_test: bool,
107 /// List of arguments to pass to the test harness, if running tests.
108 crate test_args: Vec<String>,
109 /// Optional path to persist the doctest executables to, defaults to a
110 /// temporary directory if not set.
111 crate persist_doctests: Option<PathBuf>,
112 /// Runtool to run doctests with
113 crate runtool: Option<String>,
114 /// Arguments to pass to the runtool
115 crate runtool_args: Vec<String>,
116 /// Whether to allow ignoring doctests on a per-target basis
117 /// For example, using ignore-foo to ignore running the doctest on any target that
118 /// contains "foo" as a substring
119 crate enable_per_target_ignores: bool,
121 /// The path to a rustc-like binary to build tests with. If not set, we
122 /// default to loading from $sysroot/bin/rustc.
123 crate test_builder: Option<PathBuf>,
125 // Options that affect the documentation process
126 /// The selected default set of passes to use.
128 /// Be aware: This option can come both from the CLI and from crate attributes!
129 crate default_passes: DefaultPassOption,
130 /// Any passes manually selected by the user.
132 /// Be aware: This option can come both from the CLI and from crate attributes!
133 crate manual_passes: Vec<String>,
134 /// Whether to display warnings during doc generation or while gathering doctests. By default,
135 /// all non-rustdoc-specific lints are allowed when generating docs.
136 crate display_warnings: bool,
137 /// Whether to run the `calculate-doc-coverage` pass, which counts the number of public items
138 /// with and without documentation.
139 crate show_coverage: bool,
141 // Options that alter generated documentation pages
142 /// Crate version to note on the sidebar of generated docs.
143 crate crate_version: Option<String>,
144 /// Collected options specific to outputting final pages.
145 crate render_options: RenderOptions,
146 /// Output format rendering (used only for "show-coverage" option for the moment)
147 crate output_format: Option<OutputFormat>,
148 /// If this option is set to `true`, rustdoc will only run checks and not generate
150 crate run_check: bool,
153 impl fmt::Debug for Options {
154 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155 struct FmtExterns<'a>(&'a Externs);
157 impl<'a> fmt::Debug for FmtExterns<'a> {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 f.debug_map().entries(self.0.iter()).finish()
163 f.debug_struct("Options")
164 .field("input", &self.input)
165 .field("crate_name", &self.crate_name)
166 .field("proc_macro_crate", &self.proc_macro_crate)
167 .field("error_format", &self.error_format)
168 .field("libs", &self.libs)
169 .field("externs", &FmtExterns(&self.externs))
170 .field("cfgs", &self.cfgs)
171 .field("codegen_options", &"...")
172 .field("debugging_options", &"...")
173 .field("target", &self.target)
174 .field("edition", &self.edition)
175 .field("maybe_sysroot", &self.maybe_sysroot)
176 .field("lint_opts", &self.lint_opts)
177 .field("describe_lints", &self.describe_lints)
178 .field("lint_cap", &self.lint_cap)
179 .field("should_test", &self.should_test)
180 .field("test_args", &self.test_args)
181 .field("persist_doctests", &self.persist_doctests)
182 .field("default_passes", &self.default_passes)
183 .field("manual_passes", &self.manual_passes)
184 .field("display_warnings", &self.display_warnings)
185 .field("show_coverage", &self.show_coverage)
186 .field("crate_version", &self.crate_version)
187 .field("render_options", &self.render_options)
188 .field("runtool", &self.runtool)
189 .field("runtool_args", &self.runtool_args)
190 .field("enable-per-target-ignores", &self.enable_per_target_ignores)
191 .field("run_check", &self.run_check)
196 /// Configuration options for the HTML page-creation process.
197 #[derive(Clone, Debug)]
198 crate struct RenderOptions {
199 /// Output directory to generate docs into. Defaults to `doc`.
200 crate output: PathBuf,
201 /// External files to insert into generated pages.
202 crate external_html: ExternalHtml,
203 /// A pre-populated `IdMap` with the default headings and any headings added by Markdown files
204 /// processed by `external_html`.
206 /// If present, playground URL to use in the "Run" button added to code samples.
208 /// Be aware: This option can come both from the CLI and from crate attributes!
209 crate playground_url: Option<String>,
210 /// Whether to sort modules alphabetically on a module page instead of using declaration order.
211 /// `true` by default.
213 // FIXME(misdreavus): the flag name is `--sort-modules-by-appearance` but the meaning is
214 // inverted once read.
215 crate sort_modules_alphabetically: bool,
216 /// List of themes to extend the docs with. Original argument name is included to assist in
217 /// displaying errors if it fails a theme check.
218 crate themes: Vec<StylePath>,
219 /// If present, CSS file that contains rules to add to the default CSS.
220 crate extension_css: Option<PathBuf>,
221 /// A map of crate names to the URL to use instead of querying the crate's `html_root_url`.
222 crate extern_html_root_urls: BTreeMap<String, String>,
223 /// A map of the default settings (values are as for DOM storage API). Keys should lack the
224 /// `rustdoc-` prefix.
225 crate default_settings: HashMap<String, String>,
226 /// If present, suffix added to CSS/JavaScript files when referencing them in generated pages.
227 crate resource_suffix: String,
228 /// Whether to run the static CSS/JavaScript through a minifier when outputting them. `true` by
231 // FIXME(misdreavus): the flag name is `--disable-minification` but the meaning is inverted
233 crate enable_minification: bool,
234 /// Whether to create an index page in the root of the output directory. If this is true but
235 /// `enable_index_page` is None, generate a static listing of crates instead.
236 crate enable_index_page: bool,
237 /// A file to use as the index page at the root of the output directory. Overrides
238 /// `enable_index_page` to be true if set.
239 crate index_page: Option<PathBuf>,
240 /// An optional path to use as the location of static files. If not set, uses combinations of
241 /// `../` to reach the documentation root.
242 crate static_root_path: Option<String>,
244 // Options specific to reading standalone Markdown files
245 /// Whether to generate a table of contents on the output file when reading a standalone
247 crate markdown_no_toc: bool,
248 /// Additional CSS files to link in pages generated from standalone Markdown files.
249 crate markdown_css: Vec<String>,
250 /// If present, playground URL to use in the "Run" button added to code samples generated from
251 /// standalone Markdown files. If not present, `playground_url` is used.
252 crate markdown_playground_url: Option<String>,
253 /// If false, the `select` element to have search filtering by crates on rendered docs
254 /// won't be generated.
255 crate generate_search_filter: bool,
256 /// Document items that have lower than `pub` visibility.
257 crate document_private: bool,
258 /// Document items that have `doc(hidden)`.
259 crate document_hidden: bool,
260 crate unstable_features: rustc_feature::UnstableFeatures,
263 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
264 /// Later on moved into `CACHE_KEY`.
265 #[derive(Default, Clone)]
266 crate struct RenderInfo {
267 crate inlined: FxHashSet<DefId>,
268 crate external_paths: crate::core::ExternalPaths,
269 crate exact_paths: FxHashMap<DefId, Vec<String>>,
270 crate access_levels: AccessLevels<DefId>,
271 crate deref_trait_did: Option<DefId>,
272 crate deref_mut_trait_did: Option<DefId>,
273 crate owned_box_did: Option<DefId>,
274 crate output_format: Option<OutputFormat>,
278 /// Parses the given command-line for options. If an error message or other early-return has
279 /// been printed, returns `Err` with the exit code.
280 crate fn from_matches(matches: &getopts::Matches) -> Result<Options, i32> {
281 // Check for unstable options.
282 nightly_options::check_nightly_options(&matches, &opts());
284 if matches.opt_present("h") || matches.opt_present("help") {
285 crate::usage("rustdoc");
287 } else if matches.opt_present("version") {
288 rustc_driver::version("rustdoc", &matches);
292 if matches.opt_strs("passes") == ["list"] {
293 println!("Available passes for running rustdoc:");
294 for pass in passes::PASSES {
295 println!("{:>20} - {}", pass.name, pass.description);
297 println!("\nDefault passes for rustdoc:");
298 for p in passes::DEFAULT_PASSES {
299 print!("{:>20}", p.pass.name);
300 println_condition(p.condition);
303 if nightly_options::match_is_nightly_build(matches) {
304 println!("\nPasses run with `--show-coverage`:");
305 for p in passes::COVERAGE_PASSES {
306 print!("{:>20}", p.pass.name);
307 println_condition(p.condition);
311 fn println_condition(condition: Condition) {
314 Always => println!(),
315 WhenDocumentPrivate => println!(" (when --document-private-items)"),
316 WhenNotDocumentPrivate => println!(" (when not --document-private-items)"),
317 WhenNotDocumentHidden => println!(" (when not --document-hidden-items)"),
324 let color = config::parse_color(&matches);
325 let (json_rendered, _artifacts) = config::parse_json(&matches);
326 let error_format = config::parse_error_format(&matches, color, json_rendered);
328 let codegen_options = build_codegen_options(matches, error_format);
329 let debugging_opts = build_debugging_options(matches, error_format);
331 let diag = new_handler(error_format, None, &debugging_opts);
333 // check for deprecated options
334 check_deprecated_options(&matches, &diag);
336 let to_check = matches.opt_strs("check-theme");
337 if !to_check.is_empty() {
338 let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
341 println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
342 for theme_file in to_check.iter() {
343 print!(" - Checking \"{}\"...", theme_file);
344 let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag);
345 if !differences.is_empty() || !success {
348 if !differences.is_empty() {
349 println!("{}", differences.join("\n"));
361 if matches.free.is_empty() {
362 diag.struct_err("missing file operand").emit();
365 if matches.free.len() > 1 {
366 diag.struct_err("too many file operands").emit();
369 let input = PathBuf::from(&matches.free[0]);
374 .map(|s| SearchPath::from_cli_opt(s, error_format))
376 let externs = parse_externs(&matches, &debugging_opts, error_format);
377 let extern_html_root_urls = match parse_extern_html_roots(&matches) {
380 diag.struct_err(err).emit();
385 let default_settings: Vec<Vec<(String, String)>> = vec![
387 .opt_str("default-theme")
391 ("use-system-theme".to_string(), "false".to_string()),
392 ("theme".to_string(), theme.to_string()),
398 .opt_strs("default-setting")
400 .map(|s| match s.split_once('=') {
401 None => (s.clone(), "true".to_string()),
402 Some((k, v)) => (k.to_string(), v.to_string()),
406 let default_settings = default_settings.into_iter().flatten().collect();
408 let test_args = matches.opt_strs("test-args");
409 let test_args: Vec<String> =
410 test_args.iter().flat_map(|s| s.split_whitespace()).map(|s| s.to_string()).collect();
412 let should_test = matches.opt_present("test");
415 matches.opt_str("o").map(|s| PathBuf::from(&s)).unwrap_or_else(|| PathBuf::from("doc"));
416 let cfgs = matches.opt_strs("cfg");
418 let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
420 if let Some(ref p) = extension_css {
422 diag.struct_err("option --extend-css argument must be a file").emit();
427 let mut themes = Vec::new();
428 if matches.opt_present("theme") {
429 let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
431 for (theme_file, theme_s) in
432 matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
434 if !theme_file.is_file() {
435 diag.struct_err(&format!("invalid argument: \"{}\"", theme_s))
436 .help("arguments to --theme must be files")
440 if theme_file.extension() != Some(OsStr::new("css")) {
441 diag.struct_err(&format!("invalid argument: \"{}\"", theme_s)).emit();
444 let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
446 diag.struct_err(&format!("error loading theme file: \"{}\"", theme_s)).emit();
448 } else if !ret.is_empty() {
449 diag.struct_warn(&format!(
450 "theme file \"{}\" is missing CSS rules from the default theme",
453 .warn("the theme may appear incorrect when loaded")
455 "to see what rules are missing, call `rustdoc --check-theme \"{}\"`",
460 themes.push(StylePath { path: theme_file, disabled: true });
464 let edition = if let Some(e) = matches.opt_str("edition") {
468 diag.struct_err("could not parse edition").emit();
476 let mut id_map = html::markdown::IdMap::new();
477 id_map.populate(html::render::initial_ids());
478 let external_html = match ExternalHtml::load(
479 &matches.opt_strs("html-in-header"),
480 &matches.opt_strs("html-before-content"),
481 &matches.opt_strs("html-after-content"),
482 &matches.opt_strs("markdown-before-content"),
483 &matches.opt_strs("markdown-after-content"),
484 nightly_options::match_is_nightly_build(&matches),
491 None => return Err(3),
494 match matches.opt_str("r").as_deref() {
495 Some("rust") | None => {}
497 diag.struct_err(&format!("unknown input format: {}", s)).emit();
502 let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
503 if let Some(ref index_page) = index_page {
504 if !index_page.is_file() {
505 diag.struct_err("option `--index-page` argument must be a file").emit();
511 matches.opt_str("target").map_or(TargetTriple::from_triple(host_triple()), |target| {
512 if target.ends_with(".json") {
513 TargetTriple::TargetPath(PathBuf::from(target))
515 TargetTriple::TargetTriple(target)
519 let show_coverage = matches.opt_present("show-coverage");
521 let default_passes = if matches.opt_present("no-defaults") {
522 passes::DefaultPassOption::None
523 } else if show_coverage {
524 passes::DefaultPassOption::Coverage
526 passes::DefaultPassOption::Default
528 let manual_passes = matches.opt_strs("passes");
530 let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
533 diag.struct_err(&format!("unknown crate type: {}", e)).emit();
538 let output_format = match matches.opt_str("output-format") {
539 Some(s) => match OutputFormat::try_from(s.as_str()) {
542 && !(show_coverage || nightly_options::match_is_nightly_build(matches))
544 diag.struct_err("json output format isn't supported for doc generation")
547 } else if !o.is_json() && show_coverage {
549 "html output format isn't supported for the --show-coverage option",
557 diag.struct_err(&e).emit();
563 let crate_name = matches.opt_str("crate-name");
564 let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
565 let playground_url = matches.opt_str("playground-url");
566 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
567 let display_warnings = matches.opt_present("display-warnings");
568 let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
569 let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
570 let enable_minification = !matches.opt_present("disable-minification");
571 let markdown_no_toc = matches.opt_present("markdown-no-toc");
572 let markdown_css = matches.opt_strs("markdown-css");
573 let markdown_playground_url = matches.opt_str("markdown-playground-url");
574 let crate_version = matches.opt_str("crate-version");
575 let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
576 let static_root_path = matches.opt_str("static-root-path");
577 let generate_search_filter = !matches.opt_present("disable-per-crate-search");
578 let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
579 let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
580 let codegen_options_strs = matches.opt_strs("C");
581 let debugging_opts_strs = matches.opt_strs("Z");
582 let lib_strs = matches.opt_strs("L");
583 let extern_strs = matches.opt_strs("extern");
584 let runtool = matches.opt_str("runtool");
585 let runtool_args = matches.opt_strs("runtool-arg");
586 let enable_per_target_ignores = matches.opt_present("enable-per-target-ignores");
587 let document_private = matches.opt_present("document-private-items");
588 let document_hidden = matches.opt_present("document-hidden-items");
589 let run_check = matches.opt_present("check");
591 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
603 codegen_options_strs,
622 enable_per_target_ignores,
625 render_options: RenderOptions {
630 sort_modules_alphabetically,
633 extern_html_root_urls,
642 markdown_playground_url,
643 generate_search_filter,
646 unstable_features: rustc_feature::UnstableFeatures::from_environment(
647 crate_name.as_deref(),
655 /// Returns `true` if the file given as `self.input` is a Markdown file.
656 crate fn markdown_input(&self) -> bool {
657 self.input.extension().map_or(false, |e| e == "md" || e == "markdown")
661 /// Prints deprecation warnings for deprecated options
662 fn check_deprecated_options(matches: &getopts::Matches, diag: &rustc_errors::Handler) {
663 let deprecated_flags = ["input-format", "output-format", "no-defaults", "passes"];
665 for flag in deprecated_flags.iter() {
666 if matches.opt_present(flag) {
667 if *flag == "output-format"
668 && (matches.opt_present("show-coverage")
669 || nightly_options::match_is_nightly_build(matches))
674 diag.struct_warn(&format!("the '{}' flag is considered deprecated", flag));
676 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
677 for more information",
680 if *flag == "no-defaults" {
681 err.help("you may want to use --document-private-items");
688 let removed_flags = ["plugins", "plugin-path"];
690 for &flag in removed_flags.iter() {
691 if matches.opt_present(flag) {
692 diag.struct_warn(&format!("the '{}' flag no longer functions", flag))
693 .warn("see CVE-2018-1000622")
699 /// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
700 /// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
701 /// describing the issue.
702 fn parse_extern_html_roots(
703 matches: &getopts::Matches,
704 ) -> Result<BTreeMap<String, String>, &'static str> {
705 let mut externs = BTreeMap::new();
706 for arg in &matches.opt_strs("extern-html-root-url") {
708 arg.split_once('=').ok_or("--extern-html-root-url must be of the form name=url")?;
709 externs.insert(name.to_string(), url.to_string());