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