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