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