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