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