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