1use std::collections::BTreeMap;
2use std::ffi::OsStr;
3use std::io::Read;
4use std::path::{Path, PathBuf};
5use std::str::FromStr;
6use std::{fmt, io};
7
8use rustc_data_structures::fx::FxIndexMap;
9use rustc_errors::DiagCtxtHandle;
10use rustc_session::config::{
11 self, CodegenOptions, CrateType, ErrorOutputType, Externs, Input, JsonUnusedExterns,
12 OptionsTargetModifiers, UnstableOptions, get_cmd_lint_options, nightly_options,
13 parse_crate_types_from_list, parse_externs, parse_target_triple,
14};
15use rustc_session::lint::Level;
16use rustc_session::search_paths::SearchPath;
17use rustc_session::{EarlyDiagCtxt, getopts};
18use rustc_span::FileName;
19use rustc_span::edition::Edition;
20use rustc_target::spec::TargetTuple;
21
22use crate::core::new_dcx;
23use crate::externalfiles::ExternalHtml;
24use crate::html::markdown::IdMap;
25use crate::html::render::StylePath;
26use crate::html::static_files;
27use crate::passes::{self, Condition};
28use crate::scrape_examples::{AllCallLocations, ScrapeExamplesOptions};
29use crate::{html, opts, theme};
30
31#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
32pub(crate) enum OutputFormat {
33 Json,
34 #[default]
35 Html,
36 Doctest,
37}
38
39impl OutputFormat {
40 pub(crate) fn is_json(&self) -> bool {
41 matches!(self, OutputFormat::Json)
42 }
43}
44
45impl TryFrom<&str> for OutputFormat {
46 type Error = String;
47
48 fn try_from(value: &str) -> Result<Self, Self::Error> {
49 match value {
50 "json" => Ok(OutputFormat::Json),
51 "html" => Ok(OutputFormat::Html),
52 "doctest" => Ok(OutputFormat::Doctest),
53 _ => Err(format!("unknown output format `{value}`")),
54 }
55 }
56}
57
58pub(crate) enum InputMode {
60 NoInputMergeFinalize,
62 HasFile(Input),
64}
65
66#[derive(Clone)]
68pub(crate) struct Options {
69 pub(crate) crate_name: Option<String>,
72 pub(crate) bin_crate: bool,
74 pub(crate) proc_macro_crate: bool,
76 pub(crate) error_format: ErrorOutputType,
78 pub(crate) diagnostic_width: Option<usize>,
80 pub(crate) libs: Vec<SearchPath>,
82 pub(crate) lib_strs: Vec<String>,
84 pub(crate) externs: Externs,
86 pub(crate) extern_strs: Vec<String>,
88 pub(crate) cfgs: Vec<String>,
90 pub(crate) check_cfgs: Vec<String>,
92 pub(crate) codegen_options: CodegenOptions,
94 pub(crate) codegen_options_strs: Vec<String>,
96 pub(crate) unstable_opts: UnstableOptions,
98 pub(crate) unstable_opts_strs: Vec<String>,
100 pub(crate) target: TargetTuple,
102 pub(crate) edition: Edition,
105 pub(crate) maybe_sysroot: Option<PathBuf>,
107 pub(crate) lint_opts: Vec<(String, Level)>,
109 pub(crate) describe_lints: bool,
111 pub(crate) lint_cap: Option<Level>,
113
114 pub(crate) should_test: bool,
117 pub(crate) test_args: Vec<String>,
119 pub(crate) test_run_directory: Option<PathBuf>,
121 pub(crate) persist_doctests: Option<PathBuf>,
124 pub(crate) runtool: Option<String>,
126 pub(crate) runtool_args: Vec<String>,
128 pub(crate) enable_per_target_ignores: bool,
132 pub(crate) no_run: bool,
134 pub(crate) remap_path_prefix: Vec<(PathBuf, PathBuf)>,
136
137 pub(crate) test_builder: Option<PathBuf>,
140
141 pub(crate) test_builder_wrappers: Vec<PathBuf>,
143
144 pub(crate) show_coverage: bool,
148
149 pub(crate) crate_version: Option<String>,
152 pub(crate) output_format: OutputFormat,
156 pub(crate) run_check: bool,
159 pub(crate) json_unused_externs: JsonUnusedExterns,
161 pub(crate) nocapture: bool,
163
164 pub(crate) scrape_examples_options: Option<ScrapeExamplesOptions>,
167
168 pub(crate) unstable_features: rustc_feature::UnstableFeatures,
171
172 pub(crate) expanded_args: Vec<String>,
177
178 pub(crate) doctest_compilation_args: Vec<String>,
180}
181
182impl fmt::Debug for Options {
183 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184 struct FmtExterns<'a>(&'a Externs);
185
186 impl fmt::Debug for FmtExterns<'_> {
187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188 f.debug_map().entries(self.0.iter()).finish()
189 }
190 }
191
192 f.debug_struct("Options")
193 .field("crate_name", &self.crate_name)
194 .field("bin_crate", &self.bin_crate)
195 .field("proc_macro_crate", &self.proc_macro_crate)
196 .field("error_format", &self.error_format)
197 .field("libs", &self.libs)
198 .field("externs", &FmtExterns(&self.externs))
199 .field("cfgs", &self.cfgs)
200 .field("check-cfgs", &self.check_cfgs)
201 .field("codegen_options", &"...")
202 .field("unstable_options", &"...")
203 .field("target", &self.target)
204 .field("edition", &self.edition)
205 .field("maybe_sysroot", &self.maybe_sysroot)
206 .field("lint_opts", &self.lint_opts)
207 .field("describe_lints", &self.describe_lints)
208 .field("lint_cap", &self.lint_cap)
209 .field("should_test", &self.should_test)
210 .field("test_args", &self.test_args)
211 .field("test_run_directory", &self.test_run_directory)
212 .field("persist_doctests", &self.persist_doctests)
213 .field("show_coverage", &self.show_coverage)
214 .field("crate_version", &self.crate_version)
215 .field("runtool", &self.runtool)
216 .field("runtool_args", &self.runtool_args)
217 .field("enable-per-target-ignores", &self.enable_per_target_ignores)
218 .field("run_check", &self.run_check)
219 .field("no_run", &self.no_run)
220 .field("test_builder_wrappers", &self.test_builder_wrappers)
221 .field("remap-file-prefix", &self.remap_path_prefix)
222 .field("nocapture", &self.nocapture)
223 .field("scrape_examples_options", &self.scrape_examples_options)
224 .field("unstable_features", &self.unstable_features)
225 .finish()
226 }
227}
228
229#[derive(Clone, Debug)]
231pub(crate) struct RenderOptions {
232 pub(crate) output: PathBuf,
234 pub(crate) external_html: ExternalHtml,
236 pub(crate) id_map: IdMap,
239 pub(crate) playground_url: Option<String>,
243 pub(crate) module_sorting: ModuleSorting,
246 pub(crate) themes: Vec<StylePath>,
249 pub(crate) extension_css: Option<PathBuf>,
251 pub(crate) extern_html_root_urls: BTreeMap<String, String>,
253 pub(crate) extern_html_root_takes_precedence: bool,
255 pub(crate) default_settings: FxIndexMap<String, String>,
258 pub(crate) resource_suffix: String,
260 pub(crate) enable_index_page: bool,
263 pub(crate) index_page: Option<PathBuf>,
266 pub(crate) static_root_path: Option<String>,
269
270 pub(crate) markdown_no_toc: bool,
274 pub(crate) markdown_css: Vec<String>,
276 pub(crate) markdown_playground_url: Option<String>,
279 pub(crate) document_private: bool,
281 pub(crate) document_hidden: bool,
283 pub(crate) generate_redirect_map: bool,
285 pub(crate) show_type_layout: bool,
287 pub(crate) unstable_features: rustc_feature::UnstableFeatures,
290 pub(crate) emit: Vec<EmitType>,
291 pub(crate) generate_link_to_definition: bool,
293 pub(crate) call_locations: AllCallLocations,
295 pub(crate) no_emit_shared: bool,
297 pub(crate) html_no_source: bool,
299 pub(crate) output_to_stdout: bool,
302 pub(crate) should_merge: ShouldMerge,
304 pub(crate) include_parts_dir: Vec<PathToParts>,
306 pub(crate) parts_out_dir: Option<PathToParts>,
308 pub(crate) disable_minification: bool,
310}
311
312#[derive(Copy, Clone, Debug, PartialEq, Eq)]
313pub(crate) enum ModuleSorting {
314 DeclarationOrder,
315 Alphabetical,
316}
317
318#[derive(Copy, Clone, Debug, PartialEq, Eq)]
319pub(crate) enum EmitType {
320 Unversioned,
321 Toolchain,
322 InvocationSpecific,
323}
324
325impl FromStr for EmitType {
326 type Err = ();
327
328 fn from_str(s: &str) -> Result<Self, Self::Err> {
329 use EmitType::*;
330 match s {
331 "unversioned-shared-resources" => Ok(Unversioned),
332 "toolchain-shared-resources" => Ok(Toolchain),
333 "invocation-specific" => Ok(InvocationSpecific),
334 _ => Err(()),
335 }
336 }
337}
338
339impl RenderOptions {
340 pub(crate) fn should_emit_crate(&self) -> bool {
341 self.emit.is_empty() || self.emit.contains(&EmitType::InvocationSpecific)
342 }
343}
344
345fn make_input(early_dcx: &EarlyDiagCtxt, input: &str) -> Input {
349 if input == "-" {
350 let mut src = String::new();
351 if io::stdin().read_to_string(&mut src).is_err() {
352 early_dcx.early_fatal("couldn't read from stdin, as it did not contain valid UTF-8");
355 }
356 Input::Str { name: FileName::anon_source_code(&src), input: src }
357 } else {
358 Input::File(PathBuf::from(input))
359 }
360}
361
362impl Options {
363 pub(crate) fn from_matches(
366 early_dcx: &mut EarlyDiagCtxt,
367 matches: &getopts::Matches,
368 args: Vec<String>,
369 ) -> Option<(InputMode, Options, RenderOptions)> {
370 nightly_options::check_nightly_options(early_dcx, matches, &opts());
372
373 if args.is_empty() || matches.opt_present("h") || matches.opt_present("help") {
374 crate::usage("rustdoc");
375 return None;
376 } else if matches.opt_present("version") {
377 rustc_driver::version!(&early_dcx, "rustdoc", matches);
378 return None;
379 }
380
381 if rustc_driver::describe_flag_categories(early_dcx, matches) {
382 return None;
383 }
384
385 let color = config::parse_color(early_dcx, matches);
386 let config::JsonConfig { json_rendered, json_unused_externs, json_color, .. } =
387 config::parse_json(early_dcx, matches);
388 let error_format =
389 config::parse_error_format(early_dcx, matches, color, json_color, json_rendered);
390 let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_default();
391
392 let mut target_modifiers = BTreeMap::<OptionsTargetModifiers, String>::new();
393 let codegen_options = CodegenOptions::build(early_dcx, matches, &mut target_modifiers);
394 let unstable_opts = UnstableOptions::build(early_dcx, matches, &mut target_modifiers);
395
396 let remap_path_prefix = match parse_remap_path_prefix(matches) {
397 Ok(prefix_mappings) => prefix_mappings,
398 Err(err) => {
399 early_dcx.early_fatal(err);
400 }
401 };
402
403 let dcx = new_dcx(error_format, None, diagnostic_width, &unstable_opts);
404 let dcx = dcx.handle();
405
406 check_deprecated_options(matches, dcx);
408
409 if matches.opt_strs("passes") == ["list"] {
410 println!("Available passes for running rustdoc:");
411 for pass in passes::PASSES {
412 println!("{:>20} - {}", pass.name, pass.description);
413 }
414 println!("\nDefault passes for rustdoc:");
415 for p in passes::DEFAULT_PASSES {
416 print!("{:>20}", p.pass.name);
417 println_condition(p.condition);
418 }
419
420 if nightly_options::match_is_nightly_build(matches) {
421 println!("\nPasses run with `--show-coverage`:");
422 for p in passes::COVERAGE_PASSES {
423 print!("{:>20}", p.pass.name);
424 println_condition(p.condition);
425 }
426 }
427
428 fn println_condition(condition: Condition) {
429 use Condition::*;
430 match condition {
431 Always => println!(),
432 WhenDocumentPrivate => println!(" (when --document-private-items)"),
433 WhenNotDocumentPrivate => println!(" (when not --document-private-items)"),
434 WhenNotDocumentHidden => println!(" (when not --document-hidden-items)"),
435 }
436 }
437
438 return None;
439 }
440
441 let mut emit = Vec::new();
442 for list in matches.opt_strs("emit") {
443 for kind in list.split(',') {
444 match kind.parse() {
445 Ok(kind) => emit.push(kind),
446 Err(()) => dcx.fatal(format!("unrecognized emission type: {kind}")),
447 }
448 }
449 }
450
451 let show_coverage = matches.opt_present("show-coverage");
452 let output_format_s = matches.opt_str("output-format");
453 let output_format = match output_format_s {
454 Some(ref s) => match OutputFormat::try_from(s.as_str()) {
455 Ok(out_fmt) => out_fmt,
456 Err(e) => dcx.fatal(e),
457 },
458 None => OutputFormat::default(),
459 };
460
461 match (
463 output_format_s.as_ref().map(|_| output_format),
464 show_coverage,
465 nightly_options::is_unstable_enabled(matches),
466 ) {
467 (None | Some(OutputFormat::Json), true, _) => {}
468 (_, true, _) => {
469 dcx.fatal(format!(
470 "`--output-format={}` is not supported for the `--show-coverage` option",
471 output_format_s.unwrap_or_default(),
472 ));
473 }
474 (_, false, true) => {}
476 (None | Some(OutputFormat::Html), false, _) => {}
477 (Some(OutputFormat::Json), false, false) => {
478 dcx.fatal(
479 "the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/76578)",
480 );
481 }
482 (Some(OutputFormat::Doctest), false, false) => {
483 dcx.fatal(
484 "the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/134529)",
485 );
486 }
487 }
488
489 let to_check = matches.opt_strs("check-theme");
490 if !to_check.is_empty() {
491 let mut content =
492 std::str::from_utf8(static_files::STATIC_FILES.rustdoc_css.src_bytes).unwrap();
493 if let Some((_, inside)) = content.split_once("/* Begin theme: light */") {
494 content = inside;
495 }
496 if let Some((inside, _)) = content.split_once("/* End theme: light */") {
497 content = inside;
498 }
499 let paths = match theme::load_css_paths(content) {
500 Ok(p) => p,
501 Err(e) => dcx.fatal(e),
502 };
503 let mut errors = 0;
504
505 println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
506 for theme_file in to_check.iter() {
507 print!(" - Checking \"{theme_file}\"...");
508 let (success, differences) = theme::test_theme_against(theme_file, &paths, dcx);
509 if !differences.is_empty() || !success {
510 println!(" FAILED");
511 errors += 1;
512 if !differences.is_empty() {
513 println!("{}", differences.join("\n"));
514 }
515 } else {
516 println!(" OK");
517 }
518 }
519 if errors != 0 {
520 dcx.fatal("[check-theme] one or more tests failed");
521 }
522 return None;
523 }
524
525 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(early_dcx, matches);
526
527 let input = if describe_lints {
528 InputMode::HasFile(make_input(early_dcx, ""))
529 } else {
530 match matches.free.as_slice() {
531 [] if matches.opt_str("merge").as_deref() == Some("finalize") => {
532 InputMode::NoInputMergeFinalize
533 }
534 [] => dcx.fatal("missing file operand"),
535 [input] => InputMode::HasFile(make_input(early_dcx, input)),
536 _ => dcx.fatal("too many file operands"),
537 }
538 };
539
540 let externs = parse_externs(early_dcx, matches, &unstable_opts);
541 let extern_html_root_urls = match parse_extern_html_roots(matches) {
542 Ok(ex) => ex,
543 Err(err) => dcx.fatal(err),
544 };
545
546 let parts_out_dir =
547 match matches.opt_str("parts-out-dir").map(PathToParts::from_flag).transpose() {
548 Ok(parts_out_dir) => parts_out_dir,
549 Err(e) => dcx.fatal(e),
550 };
551 let include_parts_dir = match parse_include_parts_dir(matches) {
552 Ok(include_parts_dir) => include_parts_dir,
553 Err(e) => dcx.fatal(e),
554 };
555
556 let default_settings: Vec<Vec<(String, String)>> = vec![
557 matches
558 .opt_str("default-theme")
559 .iter()
560 .flat_map(|theme| {
561 vec![
562 ("use-system-theme".to_string(), "false".to_string()),
563 ("theme".to_string(), theme.to_string()),
564 ]
565 })
566 .collect(),
567 matches
568 .opt_strs("default-setting")
569 .iter()
570 .map(|s| match s.split_once('=') {
571 None => (s.clone(), "true".to_string()),
572 Some((k, v)) => (k.to_string(), v.to_string()),
573 })
574 .collect(),
575 ];
576 let default_settings = default_settings
577 .into_iter()
578 .flatten()
579 .map(
580 |(k, v)| (k.replace('-', "_"), v),
599 )
600 .collect();
601
602 let test_args = matches.opt_strs("test-args");
603 let test_args: Vec<String> =
604 test_args.iter().flat_map(|s| s.split_whitespace()).map(|s| s.to_string()).collect();
605
606 let should_test = matches.opt_present("test");
607 let no_run = matches.opt_present("no-run");
608
609 if !should_test && no_run {
610 dcx.fatal("the `--test` flag must be passed to enable `--no-run`");
611 }
612
613 let mut output_to_stdout = false;
614 let test_builder_wrappers =
615 matches.opt_strs("test-builder-wrapper").iter().map(PathBuf::from).collect();
616 let output = match (matches.opt_str("out-dir"), matches.opt_str("output")) {
617 (Some(_), Some(_)) => {
618 dcx.fatal("cannot use both 'out-dir' and 'output' at once");
619 }
620 (Some(out_dir), None) | (None, Some(out_dir)) => {
621 output_to_stdout = out_dir == "-";
622 PathBuf::from(out_dir)
623 }
624 (None, None) => PathBuf::from("doc"),
625 };
626
627 let cfgs = matches.opt_strs("cfg");
628 let check_cfgs = matches.opt_strs("check-cfg");
629
630 let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
631
632 if let Some(ref p) = extension_css {
633 if !p.is_file() {
634 dcx.fatal("option --extend-css argument must be a file");
635 }
636 }
637
638 let mut themes = Vec::new();
639 if matches.opt_present("theme") {
640 let mut content =
641 std::str::from_utf8(static_files::STATIC_FILES.rustdoc_css.src_bytes).unwrap();
642 if let Some((_, inside)) = content.split_once("/* Begin theme: light */") {
643 content = inside;
644 }
645 if let Some((inside, _)) = content.split_once("/* End theme: light */") {
646 content = inside;
647 }
648 let paths = match theme::load_css_paths(content) {
649 Ok(p) => p,
650 Err(e) => dcx.fatal(e),
651 };
652
653 for (theme_file, theme_s) in
654 matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
655 {
656 if !theme_file.is_file() {
657 dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
658 .with_help("arguments to --theme must be files")
659 .emit();
660 }
661 if theme_file.extension() != Some(OsStr::new("css")) {
662 dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
663 .with_help("arguments to --theme must have a .css extension")
664 .emit();
665 }
666 let (success, ret) = theme::test_theme_against(&theme_file, &paths, dcx);
667 if !success {
668 dcx.fatal(format!("error loading theme file: \"{theme_s}\""));
669 } else if !ret.is_empty() {
670 dcx.struct_warn(format!(
671 "theme file \"{theme_s}\" is missing CSS rules from the default theme",
672 ))
673 .with_warn("the theme may appear incorrect when loaded")
674 .with_help(format!(
675 "to see what rules are missing, call `rustdoc --check-theme \"{theme_s}\"`",
676 ))
677 .emit();
678 }
679 themes.push(StylePath { path: theme_file });
680 }
681 }
682
683 let edition = config::parse_crate_edition(early_dcx, matches);
684
685 let mut id_map = html::markdown::IdMap::new();
686 let Some(external_html) = ExternalHtml::load(
687 &matches.opt_strs("html-in-header"),
688 &matches.opt_strs("html-before-content"),
689 &matches.opt_strs("html-after-content"),
690 &matches.opt_strs("markdown-before-content"),
691 &matches.opt_strs("markdown-after-content"),
692 nightly_options::match_is_nightly_build(matches),
693 dcx,
694 &mut id_map,
695 edition,
696 &None,
697 ) else {
698 dcx.fatal("`ExternalHtml::load` failed");
699 };
700
701 match matches.opt_str("r").as_deref() {
702 Some("rust") | None => {}
703 Some(s) => dcx.fatal(format!("unknown input format: {s}")),
704 }
705
706 let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
707 if let Some(ref index_page) = index_page {
708 if !index_page.is_file() {
709 dcx.fatal("option `--index-page` argument must be a file");
710 }
711 }
712
713 let target = parse_target_triple(early_dcx, matches);
714 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
715
716 let sysroot = match &maybe_sysroot {
717 Some(s) => s.clone(),
718 None => {
719 rustc_session::filesearch::get_or_default_sysroot().expect("Failed finding sysroot")
720 }
721 };
722
723 let libs = matches
724 .opt_strs("L")
725 .iter()
726 .map(|s| {
727 SearchPath::from_cli_opt(
728 &sysroot,
729 &target,
730 early_dcx,
731 s,
732 #[allow(rustc::bad_opt_access)] unstable_opts.unstable_options,
734 )
735 })
736 .collect();
737
738 let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
739 Ok(types) => types,
740 Err(e) => {
741 dcx.fatal(format!("unknown crate type: {e}"));
742 }
743 };
744
745 let crate_name = matches.opt_str("crate-name");
746 let bin_crate = crate_types.contains(&CrateType::Executable);
747 let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
748 let playground_url = matches.opt_str("playground-url");
749 let module_sorting = if matches.opt_present("sort-modules-by-appearance") {
750 ModuleSorting::DeclarationOrder
751 } else {
752 ModuleSorting::Alphabetical
753 };
754 let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
755 let markdown_no_toc = matches.opt_present("markdown-no-toc");
756 let markdown_css = matches.opt_strs("markdown-css");
757 let markdown_playground_url = matches.opt_str("markdown-playground-url");
758 let crate_version = matches.opt_str("crate-version");
759 let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
760 let static_root_path = matches.opt_str("static-root-path");
761 let test_run_directory = matches.opt_str("test-run-directory").map(PathBuf::from);
762 let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
763 let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
764 let codegen_options_strs = matches.opt_strs("C");
765 let unstable_opts_strs = matches.opt_strs("Z");
766 let lib_strs = matches.opt_strs("L");
767 let extern_strs = matches.opt_strs("extern");
768 let runtool = matches.opt_str("runtool");
769 let runtool_args = matches.opt_strs("runtool-arg");
770 let enable_per_target_ignores = matches.opt_present("enable-per-target-ignores");
771 let document_private = matches.opt_present("document-private-items");
772 let document_hidden = matches.opt_present("document-hidden-items");
773 let run_check = matches.opt_present("check");
774 let generate_redirect_map = matches.opt_present("generate-redirect-map");
775 let show_type_layout = matches.opt_present("show-type-layout");
776 let nocapture = matches.opt_present("nocapture");
777 let generate_link_to_definition = matches.opt_present("generate-link-to-definition");
778 let extern_html_root_takes_precedence =
779 matches.opt_present("extern-html-root-takes-precedence");
780 let html_no_source = matches.opt_present("html-no-source");
781 let should_merge = match parse_merge(matches) {
782 Ok(result) => result,
783 Err(e) => dcx.fatal(format!("--merge option error: {e}")),
784 };
785
786 if generate_link_to_definition && (show_coverage || output_format != OutputFormat::Html) {
787 dcx.struct_warn(
788 "`--generate-link-to-definition` option can only be used with HTML output format",
789 )
790 .with_note("`--generate-link-to-definition` option will be ignored")
791 .emit();
792 }
793
794 let scrape_examples_options = ScrapeExamplesOptions::new(matches, dcx);
795 let with_examples = matches.opt_strs("with-examples");
796 let call_locations = crate::scrape_examples::load_call_locations(with_examples, dcx);
797 let doctest_compilation_args = matches.opt_strs("doctest-compilation-args");
798
799 let unstable_features =
800 rustc_feature::UnstableFeatures::from_environment(crate_name.as_deref());
801
802 let disable_minification = matches.opt_present("disable-minification");
803
804 let options = Options {
805 bin_crate,
806 proc_macro_crate,
807 error_format,
808 diagnostic_width,
809 libs,
810 lib_strs,
811 externs,
812 extern_strs,
813 cfgs,
814 check_cfgs,
815 codegen_options,
816 codegen_options_strs,
817 unstable_opts,
818 unstable_opts_strs,
819 target,
820 edition,
821 maybe_sysroot,
822 lint_opts,
823 describe_lints,
824 lint_cap,
825 should_test,
826 test_args,
827 show_coverage,
828 crate_version,
829 test_run_directory,
830 persist_doctests,
831 runtool,
832 runtool_args,
833 enable_per_target_ignores,
834 test_builder,
835 run_check,
836 no_run,
837 test_builder_wrappers,
838 remap_path_prefix,
839 nocapture,
840 crate_name,
841 output_format,
842 json_unused_externs,
843 scrape_examples_options,
844 unstable_features,
845 expanded_args: args,
846 doctest_compilation_args,
847 };
848 let render_options = RenderOptions {
849 output,
850 external_html,
851 id_map,
852 playground_url,
853 module_sorting,
854 themes,
855 extension_css,
856 extern_html_root_urls,
857 extern_html_root_takes_precedence,
858 default_settings,
859 resource_suffix,
860 enable_index_page,
861 index_page,
862 static_root_path,
863 markdown_no_toc,
864 markdown_css,
865 markdown_playground_url,
866 document_private,
867 document_hidden,
868 generate_redirect_map,
869 show_type_layout,
870 unstable_features,
871 emit,
872 generate_link_to_definition,
873 call_locations,
874 no_emit_shared: false,
875 html_no_source,
876 output_to_stdout,
877 should_merge,
878 include_parts_dir,
879 parts_out_dir,
880 disable_minification,
881 };
882 Some((input, options, render_options))
883 }
884}
885
886pub(crate) fn markdown_input(input: &Input) -> Option<&Path> {
888 input.opt_path().filter(|p| matches!(p.extension(), Some(e) if e == "md" || e == "markdown"))
889}
890
891fn parse_remap_path_prefix(
892 matches: &getopts::Matches,
893) -> Result<Vec<(PathBuf, PathBuf)>, &'static str> {
894 matches
895 .opt_strs("remap-path-prefix")
896 .into_iter()
897 .map(|remap| {
898 remap
899 .rsplit_once('=')
900 .ok_or("--remap-path-prefix must contain '=' between FROM and TO")
901 .map(|(from, to)| (PathBuf::from(from), PathBuf::from(to)))
902 })
903 .collect()
904}
905
906fn check_deprecated_options(matches: &getopts::Matches, dcx: DiagCtxtHandle<'_>) {
908 let deprecated_flags = [];
909
910 for &flag in deprecated_flags.iter() {
911 if matches.opt_present(flag) {
912 dcx.struct_warn(format!("the `{flag}` flag is deprecated"))
913 .with_note(
914 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
915 for more information",
916 )
917 .emit();
918 }
919 }
920
921 let removed_flags = ["plugins", "plugin-path", "no-defaults", "passes", "input-format"];
922
923 for &flag in removed_flags.iter() {
924 if matches.opt_present(flag) {
925 let mut err = dcx.struct_warn(format!("the `{flag}` flag no longer functions"));
926 err.note(
927 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
928 for more information",
929 );
930
931 if flag == "no-defaults" || flag == "passes" {
932 err.help("you may want to use --document-private-items");
933 } else if flag == "plugins" || flag == "plugin-path" {
934 err.warn("see CVE-2018-1000622");
935 }
936
937 err.emit();
938 }
939 }
940}
941
942fn parse_extern_html_roots(
946 matches: &getopts::Matches,
947) -> Result<BTreeMap<String, String>, &'static str> {
948 let mut externs = BTreeMap::new();
949 for arg in &matches.opt_strs("extern-html-root-url") {
950 let (name, url) =
951 arg.split_once('=').ok_or("--extern-html-root-url must be of the form name=url")?;
952 externs.insert(name.to_string(), url.to_string());
953 }
954 Ok(externs)
955}
956
957#[derive(Clone, Debug)]
961pub(crate) struct PathToParts(pub(crate) PathBuf);
962
963impl PathToParts {
964 fn from_flag(path: String) -> Result<PathToParts, String> {
965 let mut path = PathBuf::from(path);
966 if path.exists() && !path.is_dir() {
968 Err(format!(
969 "--parts-out-dir and --include-parts-dir expect directories, found: {}",
970 path.display(),
971 ))
972 } else {
973 path.push("crate-info");
975 Ok(PathToParts(path))
976 }
977 }
978}
979
980fn parse_include_parts_dir(m: &getopts::Matches) -> Result<Vec<PathToParts>, String> {
982 let mut ret = Vec::new();
983 for p in m.opt_strs("include-parts-dir") {
984 let p = PathToParts::from_flag(p)?;
985 if !p.0.is_file() {
987 return Err(format!("--include-parts-dir expected {} to be a file", p.0.display()));
988 }
989 ret.push(p);
990 }
991 Ok(ret)
992}
993
994#[derive(Debug, Clone)]
996pub(crate) struct ShouldMerge {
997 pub(crate) read_rendered_cci: bool,
999 pub(crate) write_rendered_cci: bool,
1001}
1002
1003fn parse_merge(m: &getopts::Matches) -> Result<ShouldMerge, &'static str> {
1006 match m.opt_str("merge").as_deref() {
1007 None => Ok(ShouldMerge { read_rendered_cci: true, write_rendered_cci: true }),
1009 Some("none") if m.opt_present("include-parts-dir") => {
1010 Err("--include-parts-dir not allowed if --merge=none")
1011 }
1012 Some("none") => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: false }),
1013 Some("shared") if m.opt_present("parts-out-dir") || m.opt_present("include-parts-dir") => {
1014 Err("--parts-out-dir and --include-parts-dir not allowed if --merge=shared")
1015 }
1016 Some("shared") => Ok(ShouldMerge { read_rendered_cci: true, write_rendered_cci: true }),
1017 Some("finalize") if m.opt_present("parts-out-dir") => {
1018 Err("--parts-out-dir not allowed if --merge=finalize")
1019 }
1020 Some("finalize") => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: true }),
1021 Some(_) => Err("argument to --merge must be `none`, `shared`, or `finalize`"),
1022 }
1023}