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