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