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