• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use std::collections::BTreeMap;
2 use std::ffi::OsStr;
3 use std::fmt;
4 use std::path::PathBuf;
5 use std::str::FromStr;
6 
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_session::config::{
9     self, parse_crate_types_from_list, parse_externs, parse_target_triple, CrateType,
10 };
11 use rustc_session::config::{get_cmd_lint_options, nightly_options};
12 use rustc_session::config::{
13     CodegenOptions, ErrorOutputType, Externs, JsonUnusedExterns, UnstableOptions,
14 };
15 use rustc_session::getopts;
16 use rustc_session::lint::Level;
17 use rustc_session::search_paths::SearchPath;
18 use rustc_session::EarlyErrorHandler;
19 use rustc_span::edition::Edition;
20 use rustc_target::spec::TargetTriple;
21 
22 use crate::core::new_handler;
23 use crate::externalfiles::ExternalHtml;
24 use crate::html;
25 use crate::html::markdown::IdMap;
26 use crate::html::render::StylePath;
27 use crate::html::static_files;
28 use crate::opts;
29 use crate::passes::{self, Condition};
30 use crate::scrape_examples::{AllCallLocations, ScrapeExamplesOptions};
31 use crate::theme;
32 
33 #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
34 pub(crate) enum OutputFormat {
35     Json,
36     #[default]
37     Html,
38 }
39 
40 impl OutputFormat {
is_json(&self) -> bool41     pub(crate) fn is_json(&self) -> bool {
42         matches!(self, OutputFormat::Json)
43     }
44 }
45 
46 impl TryFrom<&str> for OutputFormat {
47     type Error = String;
48 
try_from(value: &str) -> Result<Self, Self::Error>49     fn try_from(value: &str) -> Result<Self, Self::Error> {
50         match value {
51             "json" => Ok(OutputFormat::Json),
52             "html" => Ok(OutputFormat::Html),
53             _ => Err(format!("unknown output format `{}`", value)),
54         }
55     }
56 }
57 
58 /// Configuration options for rustdoc.
59 #[derive(Clone)]
60 pub(crate) struct Options {
61     // Basic options / Options passed directly to rustc
62     /// The crate root or Markdown file to load.
63     pub(crate) input: PathBuf,
64     /// The name of the crate being documented.
65     pub(crate) crate_name: Option<String>,
66     /// Whether or not this is a bin crate
67     pub(crate) bin_crate: bool,
68     /// Whether or not this is a proc-macro crate
69     pub(crate) proc_macro_crate: bool,
70     /// How to format errors and warnings.
71     pub(crate) error_format: ErrorOutputType,
72     /// Width of output buffer to truncate errors appropriately.
73     pub(crate) diagnostic_width: Option<usize>,
74     /// Library search paths to hand to the compiler.
75     pub(crate) libs: Vec<SearchPath>,
76     /// Library search paths strings to hand to the compiler.
77     pub(crate) lib_strs: Vec<String>,
78     /// The list of external crates to link against.
79     pub(crate) externs: Externs,
80     /// The list of external crates strings to link against.
81     pub(crate) extern_strs: Vec<String>,
82     /// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`.
83     pub(crate) cfgs: Vec<String>,
84     /// List of check cfg flags to hand to the compiler.
85     pub(crate) check_cfgs: Vec<String>,
86     /// Codegen options to hand to the compiler.
87     pub(crate) codegen_options: CodegenOptions,
88     /// Codegen options strings to hand to the compiler.
89     pub(crate) codegen_options_strs: Vec<String>,
90     /// Unstable (`-Z`) options to pass to the compiler.
91     pub(crate) unstable_opts: UnstableOptions,
92     /// Unstable (`-Z`) options strings to pass to the compiler.
93     pub(crate) unstable_opts_strs: Vec<String>,
94     /// The target used to compile the crate against.
95     pub(crate) target: TargetTriple,
96     /// Edition used when reading the crate. Defaults to "2015". Also used by default when
97     /// compiling doctests from the crate.
98     pub(crate) edition: Edition,
99     /// The path to the sysroot. Used during the compilation process.
100     pub(crate) maybe_sysroot: Option<PathBuf>,
101     /// Lint information passed over the command-line.
102     pub(crate) lint_opts: Vec<(String, Level)>,
103     /// Whether to ask rustc to describe the lints it knows.
104     pub(crate) describe_lints: bool,
105     /// What level to cap lints at.
106     pub(crate) lint_cap: Option<Level>,
107 
108     // Options specific to running doctests
109     /// Whether we should run doctests instead of generating docs.
110     pub(crate) should_test: bool,
111     /// List of arguments to pass to the test harness, if running tests.
112     pub(crate) test_args: Vec<String>,
113     /// The working directory in which to run tests.
114     pub(crate) test_run_directory: Option<PathBuf>,
115     /// Optional path to persist the doctest executables to, defaults to a
116     /// temporary directory if not set.
117     pub(crate) persist_doctests: Option<PathBuf>,
118     /// Runtool to run doctests with
119     pub(crate) runtool: Option<String>,
120     /// Arguments to pass to the runtool
121     pub(crate) runtool_args: Vec<String>,
122     /// Whether to allow ignoring doctests on a per-target basis
123     /// For example, using ignore-foo to ignore running the doctest on any target that
124     /// contains "foo" as a substring
125     pub(crate) enable_per_target_ignores: bool,
126     /// Do not run doctests, compile them if should_test is active.
127     pub(crate) no_run: bool,
128 
129     /// The path to a rustc-like binary to build tests with. If not set, we
130     /// default to loading from `$sysroot/bin/rustc`.
131     pub(crate) test_builder: Option<PathBuf>,
132 
133     // Options that affect the documentation process
134     /// Whether to run the `calculate-doc-coverage` pass, which counts the number of public items
135     /// with and without documentation.
136     pub(crate) show_coverage: bool,
137 
138     // Options that alter generated documentation pages
139     /// Crate version to note on the sidebar of generated docs.
140     pub(crate) crate_version: Option<String>,
141     /// The format that we output when rendering.
142     ///
143     /// Currently used only for the `--show-coverage` option.
144     pub(crate) output_format: OutputFormat,
145     /// If this option is set to `true`, rustdoc will only run checks and not generate
146     /// documentation.
147     pub(crate) run_check: bool,
148     /// Whether doctests should emit unused externs
149     pub(crate) json_unused_externs: JsonUnusedExterns,
150     /// Whether to skip capturing stdout and stderr of tests.
151     pub(crate) nocapture: bool,
152 
153     /// Configuration for scraping examples from the current crate. If this option is Some(..) then
154     /// the compiler will scrape examples and not generate documentation.
155     pub(crate) scrape_examples_options: Option<ScrapeExamplesOptions>,
156 
157     /// Note: this field is duplicated in `RenderOptions` because it's useful
158     /// to have it in both places.
159     pub(crate) unstable_features: rustc_feature::UnstableFeatures,
160 }
161 
162 impl fmt::Debug for Options {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result163     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164         struct FmtExterns<'a>(&'a Externs);
165 
166         impl<'a> fmt::Debug for FmtExterns<'a> {
167             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168                 f.debug_map().entries(self.0.iter()).finish()
169             }
170         }
171 
172         f.debug_struct("Options")
173             .field("input", &self.input)
174             .field("crate_name", &self.crate_name)
175             .field("bin_crate", &self.bin_crate)
176             .field("proc_macro_crate", &self.proc_macro_crate)
177             .field("error_format", &self.error_format)
178             .field("libs", &self.libs)
179             .field("externs", &FmtExterns(&self.externs))
180             .field("cfgs", &self.cfgs)
181             .field("check-cfgs", &self.check_cfgs)
182             .field("codegen_options", &"...")
183             .field("unstable_options", &"...")
184             .field("target", &self.target)
185             .field("edition", &self.edition)
186             .field("maybe_sysroot", &self.maybe_sysroot)
187             .field("lint_opts", &self.lint_opts)
188             .field("describe_lints", &self.describe_lints)
189             .field("lint_cap", &self.lint_cap)
190             .field("should_test", &self.should_test)
191             .field("test_args", &self.test_args)
192             .field("test_run_directory", &self.test_run_directory)
193             .field("persist_doctests", &self.persist_doctests)
194             .field("show_coverage", &self.show_coverage)
195             .field("crate_version", &self.crate_version)
196             .field("runtool", &self.runtool)
197             .field("runtool_args", &self.runtool_args)
198             .field("enable-per-target-ignores", &self.enable_per_target_ignores)
199             .field("run_check", &self.run_check)
200             .field("no_run", &self.no_run)
201             .field("nocapture", &self.nocapture)
202             .field("scrape_examples_options", &self.scrape_examples_options)
203             .field("unstable_features", &self.unstable_features)
204             .finish()
205     }
206 }
207 
208 /// Configuration options for the HTML page-creation process.
209 #[derive(Clone, Debug)]
210 pub(crate) struct RenderOptions {
211     /// Output directory to generate docs into. Defaults to `doc`.
212     pub(crate) output: PathBuf,
213     /// External files to insert into generated pages.
214     pub(crate) external_html: ExternalHtml,
215     /// A pre-populated `IdMap` with the default headings and any headings added by Markdown files
216     /// processed by `external_html`.
217     pub(crate) id_map: IdMap,
218     /// If present, playground URL to use in the "Run" button added to code samples.
219     ///
220     /// Be aware: This option can come both from the CLI and from crate attributes!
221     pub(crate) playground_url: Option<String>,
222     /// What sorting mode to use for module pages.
223     /// `ModuleSorting::Alphabetical` by default.
224     pub(crate) module_sorting: ModuleSorting,
225     /// List of themes to extend the docs with. Original argument name is included to assist in
226     /// displaying errors if it fails a theme check.
227     pub(crate) themes: Vec<StylePath>,
228     /// If present, CSS file that contains rules to add to the default CSS.
229     pub(crate) extension_css: Option<PathBuf>,
230     /// A map of crate names to the URL to use instead of querying the crate's `html_root_url`.
231     pub(crate) extern_html_root_urls: BTreeMap<String, String>,
232     /// Whether to give precedence to `html_root_url` or `--extern-html-root-url`.
233     pub(crate) extern_html_root_takes_precedence: bool,
234     /// A map of the default settings (values are as for DOM storage API). Keys should lack the
235     /// `rustdoc-` prefix.
236     pub(crate) default_settings: FxHashMap<String, String>,
237     /// If present, suffix added to CSS/JavaScript files when referencing them in generated pages.
238     pub(crate) resource_suffix: String,
239     /// Whether to create an index page in the root of the output directory. If this is true but
240     /// `enable_index_page` is None, generate a static listing of crates instead.
241     pub(crate) enable_index_page: bool,
242     /// A file to use as the index page at the root of the output directory. Overrides
243     /// `enable_index_page` to be true if set.
244     pub(crate) index_page: Option<PathBuf>,
245     /// An optional path to use as the location of static files. If not set, uses combinations of
246     /// `../` to reach the documentation root.
247     pub(crate) static_root_path: Option<String>,
248 
249     // Options specific to reading standalone Markdown files
250     /// Whether to generate a table of contents on the output file when reading a standalone
251     /// Markdown file.
252     pub(crate) markdown_no_toc: bool,
253     /// Additional CSS files to link in pages generated from standalone Markdown files.
254     pub(crate) markdown_css: Vec<String>,
255     /// If present, playground URL to use in the "Run" button added to code samples generated from
256     /// standalone Markdown files. If not present, `playground_url` is used.
257     pub(crate) markdown_playground_url: Option<String>,
258     /// Document items that have lower than `pub` visibility.
259     pub(crate) document_private: bool,
260     /// Document items that have `doc(hidden)`.
261     pub(crate) document_hidden: bool,
262     /// If `true`, generate a JSON file in the crate folder instead of HTML redirection files.
263     pub(crate) generate_redirect_map: bool,
264     /// Show the memory layout of types in the docs.
265     pub(crate) show_type_layout: bool,
266     /// Note: this field is duplicated in `Options` because it's useful to have
267     /// it in both places.
268     pub(crate) unstable_features: rustc_feature::UnstableFeatures,
269     pub(crate) emit: Vec<EmitType>,
270     /// If `true`, HTML source pages will generate links for items to their definition.
271     pub(crate) generate_link_to_definition: bool,
272     /// Set of function-call locations to include as examples
273     pub(crate) call_locations: AllCallLocations,
274     /// If `true`, Context::init will not emit shared files.
275     pub(crate) no_emit_shared: bool,
276 }
277 
278 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
279 pub(crate) enum ModuleSorting {
280     DeclarationOrder,
281     Alphabetical,
282 }
283 
284 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
285 pub(crate) enum EmitType {
286     Unversioned,
287     Toolchain,
288     InvocationSpecific,
289 }
290 
291 impl FromStr for EmitType {
292     type Err = ();
293 
from_str(s: &str) -> Result<Self, Self::Err>294     fn from_str(s: &str) -> Result<Self, Self::Err> {
295         use EmitType::*;
296         match s {
297             "unversioned-shared-resources" => Ok(Unversioned),
298             "toolchain-shared-resources" => Ok(Toolchain),
299             "invocation-specific" => Ok(InvocationSpecific),
300             _ => Err(()),
301         }
302     }
303 }
304 
305 impl RenderOptions {
should_emit_crate(&self) -> bool306     pub(crate) fn should_emit_crate(&self) -> bool {
307         self.emit.is_empty() || self.emit.contains(&EmitType::InvocationSpecific)
308     }
309 }
310 
311 impl Options {
312     /// Parses the given command-line for options. If an error message or other early-return has
313     /// been printed, returns `Err` with the exit code.
from_matches( handler: &mut EarlyErrorHandler, matches: &getopts::Matches, args: Vec<String>, ) -> Result<(Options, RenderOptions), i32>314     pub(crate) fn from_matches(
315         handler: &mut EarlyErrorHandler,
316         matches: &getopts::Matches,
317         args: Vec<String>,
318     ) -> Result<(Options, RenderOptions), i32> {
319         // Check for unstable options.
320         nightly_options::check_nightly_options(handler, matches, &opts());
321 
322         if args.is_empty() || matches.opt_present("h") || matches.opt_present("help") {
323             crate::usage("rustdoc");
324             return Err(0);
325         } else if matches.opt_present("version") {
326             rustc_driver::version!(&handler, "rustdoc", matches);
327             return Err(0);
328         }
329 
330         if rustc_driver::describe_flag_categories(handler, &matches) {
331             return Err(0);
332         }
333 
334         let color = config::parse_color(handler, matches);
335         let config::JsonConfig { json_rendered, json_unused_externs, .. } =
336             config::parse_json(handler, matches);
337         let error_format = config::parse_error_format(handler, matches, color, json_rendered);
338         let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_default();
339 
340         let codegen_options = CodegenOptions::build(handler, matches);
341         let unstable_opts = UnstableOptions::build(handler, matches);
342 
343         let diag = new_handler(error_format, None, diagnostic_width, &unstable_opts);
344 
345         // check for deprecated options
346         check_deprecated_options(matches, &diag);
347 
348         if matches.opt_strs("passes") == ["list"] {
349             println!("Available passes for running rustdoc:");
350             for pass in passes::PASSES {
351                 println!("{:>20} - {}", pass.name, pass.description);
352             }
353             println!("\nDefault passes for rustdoc:");
354             for p in passes::DEFAULT_PASSES {
355                 print!("{:>20}", p.pass.name);
356                 println_condition(p.condition);
357             }
358 
359             if nightly_options::match_is_nightly_build(matches) {
360                 println!("\nPasses run with `--show-coverage`:");
361                 for p in passes::COVERAGE_PASSES {
362                     print!("{:>20}", p.pass.name);
363                     println_condition(p.condition);
364                 }
365             }
366 
367             fn println_condition(condition: Condition) {
368                 use Condition::*;
369                 match condition {
370                     Always => println!(),
371                     WhenDocumentPrivate => println!("  (when --document-private-items)"),
372                     WhenNotDocumentPrivate => println!("  (when not --document-private-items)"),
373                     WhenNotDocumentHidden => println!("  (when not --document-hidden-items)"),
374                 }
375             }
376 
377             return Err(0);
378         }
379 
380         let mut emit = Vec::new();
381         for list in matches.opt_strs("emit") {
382             for kind in list.split(',') {
383                 match kind.parse() {
384                     Ok(kind) => emit.push(kind),
385                     Err(()) => {
386                         diag.err(format!("unrecognized emission type: {}", kind));
387                         return Err(1);
388                     }
389                 }
390             }
391         }
392 
393         // check for `--output-format=json`
394         if !matches!(matches.opt_str("output-format").as_deref(), None | Some("html"))
395             && !matches.opt_present("show-coverage")
396             && !nightly_options::is_unstable_enabled(matches)
397         {
398             handler.early_error(
399                 "the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/76578)",
400             );
401         }
402 
403         let to_check = matches.opt_strs("check-theme");
404         if !to_check.is_empty() {
405             let paths = match theme::load_css_paths(
406                 std::str::from_utf8(static_files::STATIC_FILES.theme_light_css.bytes).unwrap(),
407             ) {
408                 Ok(p) => p,
409                 Err(e) => {
410                     diag.struct_err(e).emit();
411                     return Err(1);
412                 }
413             };
414             let mut errors = 0;
415 
416             println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
417             for theme_file in to_check.iter() {
418                 print!(" - Checking \"{}\"...", theme_file);
419                 let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag);
420                 if !differences.is_empty() || !success {
421                     println!(" FAILED");
422                     errors += 1;
423                     if !differences.is_empty() {
424                         println!("{}", differences.join("\n"));
425                     }
426                 } else {
427                     println!(" OK");
428                 }
429             }
430             if errors != 0 {
431                 return Err(1);
432             }
433             return Err(0);
434         }
435 
436         let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(handler, matches);
437 
438         let input = PathBuf::from(if describe_lints {
439             "" // dummy, this won't be used
440         } else if matches.free.is_empty() {
441             diag.struct_err("missing file operand").emit();
442             return Err(1);
443         } else if matches.free.len() > 1 {
444             diag.struct_err("too many file operands").emit();
445             return Err(1);
446         } else {
447             &matches.free[0]
448         });
449 
450         let libs =
451             matches.opt_strs("L").iter().map(|s| SearchPath::from_cli_opt(handler, s)).collect();
452         let externs = parse_externs(handler, matches, &unstable_opts);
453         let extern_html_root_urls = match parse_extern_html_roots(matches) {
454             Ok(ex) => ex,
455             Err(err) => {
456                 diag.struct_err(err).emit();
457                 return Err(1);
458             }
459         };
460 
461         let default_settings: Vec<Vec<(String, String)>> = vec![
462             matches
463                 .opt_str("default-theme")
464                 .iter()
465                 .flat_map(|theme| {
466                     vec![
467                         ("use-system-theme".to_string(), "false".to_string()),
468                         ("theme".to_string(), theme.to_string()),
469                     ]
470                 })
471                 .collect(),
472             matches
473                 .opt_strs("default-setting")
474                 .iter()
475                 .map(|s| match s.split_once('=') {
476                     None => (s.clone(), "true".to_string()),
477                     Some((k, v)) => (k.to_string(), v.to_string()),
478                 })
479                 .collect(),
480         ];
481         let default_settings = default_settings
482             .into_iter()
483             .flatten()
484             .map(
485                 // The keys here become part of `data-` attribute names in the generated HTML.  The
486                 // browser does a strange mapping when converting them into attributes on the
487                 // `dataset` property on the DOM HTML Node:
488                 //   https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
489                 //
490                 // The original key values we have are the same as the DOM storage API keys and the
491                 // command line options, so contain `-`.  Our JavaScript needs to be able to look
492                 // these values up both in `dataset` and in the storage API, so it needs to be able
493                 // to convert the names back and forth.  Despite doing this kebab-case to
494                 // StudlyCaps transformation automatically, the JS DOM API does not provide a
495                 // mechanism for doing just the transformation on a string.  So we want to avoid
496                 // the StudlyCaps representation in the `dataset` property.
497                 //
498                 // We solve this by replacing all the `-`s with `_`s.  We do that here, when we
499                 // generate the `data-` attributes, and in the JS, when we look them up.  (See
500                 // `getSettingValue` in `storage.js.`) Converting `-` to `_` is simple in JS.
501                 //
502                 // The values will be HTML-escaped by the default Tera escaping.
503                 |(k, v)| (k.replace('-', "_"), v),
504             )
505             .collect();
506 
507         let test_args = matches.opt_strs("test-args");
508         let test_args: Vec<String> =
509             test_args.iter().flat_map(|s| s.split_whitespace()).map(|s| s.to_string()).collect();
510 
511         let should_test = matches.opt_present("test");
512         let no_run = matches.opt_present("no-run");
513 
514         if !should_test && no_run {
515             diag.err("the `--test` flag must be passed to enable `--no-run`");
516             return Err(1);
517         }
518 
519         let out_dir = matches.opt_str("out-dir").map(|s| PathBuf::from(&s));
520         let output = matches.opt_str("output").map(|s| PathBuf::from(&s));
521         let output = match (out_dir, output) {
522             (Some(_), Some(_)) => {
523                 diag.struct_err("cannot use both 'out-dir' and 'output' at once").emit();
524                 return Err(1);
525             }
526             (Some(out_dir), None) => out_dir,
527             (None, Some(output)) => output,
528             (None, None) => PathBuf::from("doc"),
529         };
530 
531         let cfgs = matches.opt_strs("cfg");
532         let check_cfgs = matches.opt_strs("check-cfg");
533 
534         let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
535 
536         if let Some(ref p) = extension_css {
537             if !p.is_file() {
538                 diag.struct_err("option --extend-css argument must be a file").emit();
539                 return Err(1);
540             }
541         }
542 
543         let mut themes = Vec::new();
544         if matches.opt_present("theme") {
545             let paths = match theme::load_css_paths(
546                 std::str::from_utf8(static_files::STATIC_FILES.theme_light_css.bytes).unwrap(),
547             ) {
548                 Ok(p) => p,
549                 Err(e) => {
550                     diag.struct_err(e).emit();
551                     return Err(1);
552                 }
553             };
554 
555             for (theme_file, theme_s) in
556                 matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
557             {
558                 if !theme_file.is_file() {
559                     diag.struct_err(format!("invalid argument: \"{}\"", theme_s))
560                         .help("arguments to --theme must be files")
561                         .emit();
562                     return Err(1);
563                 }
564                 if theme_file.extension() != Some(OsStr::new("css")) {
565                     diag.struct_err(format!("invalid argument: \"{}\"", theme_s))
566                         .help("arguments to --theme must have a .css extension")
567                         .emit();
568                     return Err(1);
569                 }
570                 let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
571                 if !success {
572                     diag.struct_err(format!("error loading theme file: \"{}\"", theme_s)).emit();
573                     return Err(1);
574                 } else if !ret.is_empty() {
575                     diag.struct_warn(format!(
576                         "theme file \"{}\" is missing CSS rules from the default theme",
577                         theme_s
578                     ))
579                     .warn("the theme may appear incorrect when loaded")
580                     .help(format!(
581                         "to see what rules are missing, call `rustdoc --check-theme \"{}\"`",
582                         theme_s
583                     ))
584                     .emit();
585                 }
586                 themes.push(StylePath { path: theme_file });
587             }
588         }
589 
590         let edition = config::parse_crate_edition(handler, matches);
591 
592         let mut id_map = html::markdown::IdMap::new();
593         let Some(external_html) = ExternalHtml::load(
594             &matches.opt_strs("html-in-header"),
595             &matches.opt_strs("html-before-content"),
596             &matches.opt_strs("html-after-content"),
597             &matches.opt_strs("markdown-before-content"),
598             &matches.opt_strs("markdown-after-content"),
599             nightly_options::match_is_nightly_build(matches),
600             &diag,
601             &mut id_map,
602             edition,
603             &None,
604         ) else {
605             return Err(3);
606         };
607 
608         match matches.opt_str("r").as_deref() {
609             Some("rust") | None => {}
610             Some(s) => {
611                 diag.struct_err(format!("unknown input format: {}", s)).emit();
612                 return Err(1);
613             }
614         }
615 
616         let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
617         if let Some(ref index_page) = index_page {
618             if !index_page.is_file() {
619                 diag.struct_err("option `--index-page` argument must be a file").emit();
620                 return Err(1);
621             }
622         }
623 
624         let target = parse_target_triple(handler, matches);
625 
626         let show_coverage = matches.opt_present("show-coverage");
627 
628         let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
629             Ok(types) => types,
630             Err(e) => {
631                 diag.struct_err(format!("unknown crate type: {}", e)).emit();
632                 return Err(1);
633             }
634         };
635 
636         let output_format = match matches.opt_str("output-format") {
637             Some(s) => match OutputFormat::try_from(s.as_str()) {
638                 Ok(out_fmt) => {
639                     if !out_fmt.is_json() && show_coverage {
640                         diag.struct_err(
641                             "html output format isn't supported for the --show-coverage option",
642                         )
643                         .emit();
644                         return Err(1);
645                     }
646                     out_fmt
647                 }
648                 Err(e) => {
649                     diag.struct_err(e).emit();
650                     return Err(1);
651                 }
652             },
653             None => OutputFormat::default(),
654         };
655         let crate_name = matches.opt_str("crate-name");
656         let bin_crate = crate_types.contains(&CrateType::Executable);
657         let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
658         let playground_url = matches.opt_str("playground-url");
659         let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
660         let module_sorting = if matches.opt_present("sort-modules-by-appearance") {
661             ModuleSorting::DeclarationOrder
662         } else {
663             ModuleSorting::Alphabetical
664         };
665         let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
666         let markdown_no_toc = matches.opt_present("markdown-no-toc");
667         let markdown_css = matches.opt_strs("markdown-css");
668         let markdown_playground_url = matches.opt_str("markdown-playground-url");
669         let crate_version = matches.opt_str("crate-version");
670         let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
671         let static_root_path = matches.opt_str("static-root-path");
672         let test_run_directory = matches.opt_str("test-run-directory").map(PathBuf::from);
673         let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
674         let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
675         let codegen_options_strs = matches.opt_strs("C");
676         let unstable_opts_strs = matches.opt_strs("Z");
677         let lib_strs = matches.opt_strs("L");
678         let extern_strs = matches.opt_strs("extern");
679         let runtool = matches.opt_str("runtool");
680         let runtool_args = matches.opt_strs("runtool-arg");
681         let enable_per_target_ignores = matches.opt_present("enable-per-target-ignores");
682         let document_private = matches.opt_present("document-private-items");
683         let document_hidden = matches.opt_present("document-hidden-items");
684         let run_check = matches.opt_present("check");
685         let generate_redirect_map = matches.opt_present("generate-redirect-map");
686         let show_type_layout = matches.opt_present("show-type-layout");
687         let nocapture = matches.opt_present("nocapture");
688         let generate_link_to_definition = matches.opt_present("generate-link-to-definition");
689         let extern_html_root_takes_precedence =
690             matches.opt_present("extern-html-root-takes-precedence");
691 
692         if generate_link_to_definition && (show_coverage || output_format != OutputFormat::Html) {
693             diag.struct_err(
694                 "--generate-link-to-definition option can only be used with HTML output format",
695             )
696             .emit();
697             return Err(1);
698         }
699 
700         let scrape_examples_options = ScrapeExamplesOptions::new(matches, &diag)?;
701         let with_examples = matches.opt_strs("with-examples");
702         let call_locations = crate::scrape_examples::load_call_locations(with_examples, &diag)?;
703 
704         let unstable_features =
705             rustc_feature::UnstableFeatures::from_environment(crate_name.as_deref());
706         let options = Options {
707             input,
708             bin_crate,
709             proc_macro_crate,
710             error_format,
711             diagnostic_width,
712             libs,
713             lib_strs,
714             externs,
715             extern_strs,
716             cfgs,
717             check_cfgs,
718             codegen_options,
719             codegen_options_strs,
720             unstable_opts,
721             unstable_opts_strs,
722             target,
723             edition,
724             maybe_sysroot,
725             lint_opts,
726             describe_lints,
727             lint_cap,
728             should_test,
729             test_args,
730             show_coverage,
731             crate_version,
732             test_run_directory,
733             persist_doctests,
734             runtool,
735             runtool_args,
736             enable_per_target_ignores,
737             test_builder,
738             run_check,
739             no_run,
740             nocapture,
741             crate_name,
742             output_format,
743             json_unused_externs,
744             scrape_examples_options,
745             unstable_features,
746         };
747         let render_options = RenderOptions {
748             output,
749             external_html,
750             id_map,
751             playground_url,
752             module_sorting,
753             themes,
754             extension_css,
755             extern_html_root_urls,
756             extern_html_root_takes_precedence,
757             default_settings,
758             resource_suffix,
759             enable_index_page,
760             index_page,
761             static_root_path,
762             markdown_no_toc,
763             markdown_css,
764             markdown_playground_url,
765             document_private,
766             document_hidden,
767             generate_redirect_map,
768             show_type_layout,
769             unstable_features,
770             emit,
771             generate_link_to_definition,
772             call_locations,
773             no_emit_shared: false,
774         };
775         Ok((options, render_options))
776     }
777 
778     /// Returns `true` if the file given as `self.input` is a Markdown file.
markdown_input(&self) -> bool779     pub(crate) fn markdown_input(&self) -> bool {
780         self.input.extension().map_or(false, |e| e == "md" || e == "markdown")
781     }
782 }
783 
784 /// Prints deprecation warnings for deprecated options
check_deprecated_options(matches: &getopts::Matches, diag: &rustc_errors::Handler)785 fn check_deprecated_options(matches: &getopts::Matches, diag: &rustc_errors::Handler) {
786     let deprecated_flags = [];
787 
788     for &flag in deprecated_flags.iter() {
789         if matches.opt_present(flag) {
790             diag.struct_warn(format!("the `{}` flag is deprecated", flag))
791                 .note(
792                     "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
793                     for more information",
794                 )
795                 .emit();
796         }
797     }
798 
799     let removed_flags = ["plugins", "plugin-path", "no-defaults", "passes", "input-format"];
800 
801     for &flag in removed_flags.iter() {
802         if matches.opt_present(flag) {
803             let mut err = diag.struct_warn(format!("the `{}` flag no longer functions", flag));
804             err.note(
805                 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
806                 for more information",
807             );
808 
809             if flag == "no-defaults" || flag == "passes" {
810                 err.help("you may want to use --document-private-items");
811             } else if flag == "plugins" || flag == "plugin-path" {
812                 err.warn("see CVE-2018-1000622");
813             }
814 
815             err.emit();
816         }
817     }
818 }
819 
820 /// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
821 /// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
822 /// describing the issue.
parse_extern_html_roots( matches: &getopts::Matches, ) -> Result<BTreeMap<String, String>, &'static str>823 fn parse_extern_html_roots(
824     matches: &getopts::Matches,
825 ) -> Result<BTreeMap<String, String>, &'static str> {
826     let mut externs = BTreeMap::new();
827     for arg in &matches.opt_strs("extern-html-root-url") {
828         let (name, url) =
829             arg.split_once('=').ok_or("--extern-html-root-url must be of the form name=url")?;
830         externs.insert(name.to_string(), url.to_string());
831     }
832     Ok(externs)
833 }
834