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