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