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, OutFileName, Sysroot, UnstableOptions, get_cmd_lint_options,
13 nightly_options, 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) sysroot: Sysroot,
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) test_runtool: Option<String>,
126 pub(crate) test_runtool_args: Vec<String>,
128 pub(crate) no_run: bool,
130 pub(crate) remap_path_prefix: Vec<(PathBuf, PathBuf)>,
132
133 pub(crate) test_builder: Option<PathBuf>,
136
137 pub(crate) test_builder_wrappers: Vec<PathBuf>,
139
140 pub(crate) show_coverage: bool,
144
145 pub(crate) crate_version: Option<String>,
148 pub(crate) output_format: OutputFormat,
152 pub(crate) run_check: bool,
155 pub(crate) json_unused_externs: JsonUnusedExterns,
157 pub(crate) no_capture: bool,
159
160 pub(crate) scrape_examples_options: Option<ScrapeExamplesOptions>,
163
164 pub(crate) unstable_features: rustc_feature::UnstableFeatures,
167
168 pub(crate) doctest_build_args: Vec<String>,
170
171 pub(crate) target_modifiers: BTreeMap<OptionsTargetModifiers, String>,
173}
174
175impl fmt::Debug for Options {
176 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177 struct FmtExterns<'a>(&'a Externs);
178
179 impl fmt::Debug for FmtExterns<'_> {
180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181 f.debug_map().entries(self.0.iter()).finish()
182 }
183 }
184
185 f.debug_struct("Options")
186 .field("crate_name", &self.crate_name)
187 .field("bin_crate", &self.bin_crate)
188 .field("proc_macro_crate", &self.proc_macro_crate)
189 .field("error_format", &self.error_format)
190 .field("libs", &self.libs)
191 .field("externs", &FmtExterns(&self.externs))
192 .field("cfgs", &self.cfgs)
193 .field("check-cfgs", &self.check_cfgs)
194 .field("codegen_options", &"...")
195 .field("unstable_options", &"...")
196 .field("target", &self.target)
197 .field("edition", &self.edition)
198 .field("sysroot", &self.sysroot)
199 .field("lint_opts", &self.lint_opts)
200 .field("describe_lints", &self.describe_lints)
201 .field("lint_cap", &self.lint_cap)
202 .field("should_test", &self.should_test)
203 .field("test_args", &self.test_args)
204 .field("test_run_directory", &self.test_run_directory)
205 .field("persist_doctests", &self.persist_doctests)
206 .field("show_coverage", &self.show_coverage)
207 .field("crate_version", &self.crate_version)
208 .field("test_runtool", &self.test_runtool)
209 .field("test_runtool_args", &self.test_runtool_args)
210 .field("run_check", &self.run_check)
211 .field("no_run", &self.no_run)
212 .field("test_builder_wrappers", &self.test_builder_wrappers)
213 .field("remap-file-prefix", &self.remap_path_prefix)
214 .field("no_capture", &self.no_capture)
215 .field("scrape_examples_options", &self.scrape_examples_options)
216 .field("unstable_features", &self.unstable_features)
217 .finish()
218 }
219}
220
221#[derive(Clone, Debug)]
223pub(crate) struct RenderOptions {
224 pub(crate) output: PathBuf,
226 pub(crate) external_html: ExternalHtml,
228 pub(crate) id_map: IdMap,
231 pub(crate) playground_url: Option<String>,
235 pub(crate) module_sorting: ModuleSorting,
238 pub(crate) themes: Vec<StylePath>,
241 pub(crate) extension_css: Option<PathBuf>,
243 pub(crate) extern_html_root_urls: BTreeMap<String, String>,
245 pub(crate) extern_html_root_takes_precedence: bool,
247 pub(crate) default_settings: FxIndexMap<String, String>,
250 pub(crate) resource_suffix: String,
252 pub(crate) enable_index_page: bool,
255 pub(crate) index_page: Option<PathBuf>,
258 pub(crate) static_root_path: Option<String>,
261
262 pub(crate) markdown_no_toc: bool,
266 pub(crate) markdown_css: Vec<String>,
268 pub(crate) markdown_playground_url: Option<String>,
271 pub(crate) document_private: bool,
273 pub(crate) document_hidden: bool,
275 pub(crate) generate_redirect_map: bool,
277 pub(crate) show_type_layout: bool,
279 pub(crate) unstable_features: rustc_feature::UnstableFeatures,
282 pub(crate) emit: Vec<EmitType>,
283 pub(crate) generate_link_to_definition: bool,
285 pub(crate) call_locations: AllCallLocations,
287 pub(crate) no_emit_shared: bool,
289 pub(crate) html_no_source: bool,
291 pub(crate) output_to_stdout: bool,
294 pub(crate) should_merge: ShouldMerge,
296 pub(crate) include_parts_dir: Vec<PathToParts>,
298 pub(crate) parts_out_dir: Option<PathToParts>,
300 pub(crate) disable_minification: bool,
302 pub(crate) generate_macro_expansion: bool,
304}
305
306#[derive(Copy, Clone, Debug, PartialEq, Eq)]
307pub(crate) enum ModuleSorting {
308 DeclarationOrder,
309 Alphabetical,
310}
311
312#[derive(Clone, Debug, PartialEq, Eq)]
313pub(crate) enum EmitType {
314 Toolchain,
315 InvocationSpecific,
316 DepInfo(Option<OutFileName>),
317}
318
319impl FromStr for EmitType {
320 type Err = ();
321
322 fn from_str(s: &str) -> Result<Self, Self::Err> {
323 match s {
324 "toolchain-shared-resources" => Ok(Self::Toolchain),
325 "invocation-specific" => Ok(Self::InvocationSpecific),
326 "dep-info" => Ok(Self::DepInfo(None)),
327 option => match option.strip_prefix("dep-info=") {
328 Some("-") => Ok(Self::DepInfo(Some(OutFileName::Stdout))),
329 Some(f) => Ok(Self::DepInfo(Some(OutFileName::Real(f.into())))),
330 None => Err(()),
331 },
332 }
333 }
334}
335
336impl RenderOptions {
337 pub(crate) fn should_emit_crate(&self) -> bool {
338 self.emit.is_empty() || self.emit.contains(&EmitType::InvocationSpecific)
339 }
340
341 pub(crate) fn dep_info(&self) -> Option<Option<&OutFileName>> {
342 for emit in &self.emit {
343 if let EmitType::DepInfo(file) = emit {
344 return Some(file.as_ref());
345 }
346 }
347 None
348 }
349}
350
351fn make_input(early_dcx: &EarlyDiagCtxt, input: &str) -> Input {
355 if input == "-" {
356 let mut src = String::new();
357 if io::stdin().read_to_string(&mut src).is_err() {
358 early_dcx.early_fatal("couldn't read from stdin, as it did not contain valid UTF-8");
361 }
362 Input::Str { name: FileName::anon_source_code(&src), input: src }
363 } else {
364 Input::File(PathBuf::from(input))
365 }
366}
367
368impl Options {
369 pub(crate) fn from_matches(
372 early_dcx: &mut EarlyDiagCtxt,
373 matches: &getopts::Matches,
374 args: Vec<String>,
375 ) -> Option<(InputMode, Options, RenderOptions, Vec<PathBuf>)> {
376 nightly_options::check_nightly_options(early_dcx, matches, &opts());
378
379 if args.is_empty() || matches.opt_present("h") || matches.opt_present("help") {
380 crate::usage("rustdoc");
381 return None;
382 } else if matches.opt_present("version") {
383 rustc_driver::version!(&early_dcx, "rustdoc", matches);
384 return None;
385 }
386
387 if rustc_driver::describe_flag_categories(early_dcx, matches) {
388 return None;
389 }
390
391 let color = config::parse_color(early_dcx, matches);
392 let crate_name = matches.opt_str("crate-name");
393 let unstable_features =
394 rustc_feature::UnstableFeatures::from_environment(crate_name.as_deref());
395 let config::JsonConfig { json_rendered, json_unused_externs, json_color, .. } =
396 config::parse_json(early_dcx, matches, unstable_features.is_nightly_build());
397 let error_format = config::parse_error_format(
398 early_dcx,
399 matches,
400 color,
401 json_color,
402 json_rendered,
403 unstable_features.is_nightly_build(),
404 );
405 let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_default();
406
407 let mut target_modifiers = BTreeMap::<OptionsTargetModifiers, String>::new();
408 let codegen_options = CodegenOptions::build(early_dcx, matches, &mut target_modifiers);
409 let unstable_opts = UnstableOptions::build(early_dcx, matches, &mut target_modifiers);
410
411 let remap_path_prefix = match parse_remap_path_prefix(matches) {
412 Ok(prefix_mappings) => prefix_mappings,
413 Err(err) => {
414 early_dcx.early_fatal(err);
415 }
416 };
417
418 let dcx = new_dcx(error_format, None, diagnostic_width, &unstable_opts);
419 let dcx = dcx.handle();
420
421 check_deprecated_options(matches, dcx);
423
424 if matches.opt_strs("passes") == ["list"] {
425 println!("Available passes for running rustdoc:");
426 for pass in passes::PASSES {
427 println!("{:>20} - {}", pass.name, pass.description);
428 }
429 println!("\nDefault passes for rustdoc:");
430 for p in passes::DEFAULT_PASSES {
431 print!("{:>20}", p.pass.name);
432 println_condition(p.condition);
433 }
434
435 if nightly_options::match_is_nightly_build(matches) {
436 println!("\nPasses run with `--show-coverage`:");
437 for p in passes::COVERAGE_PASSES {
438 print!("{:>20}", p.pass.name);
439 println_condition(p.condition);
440 }
441 }
442
443 fn println_condition(condition: Condition) {
444 use Condition::*;
445 match condition {
446 Always => println!(),
447 WhenDocumentPrivate => println!(" (when --document-private-items)"),
448 WhenNotDocumentPrivate => println!(" (when not --document-private-items)"),
449 WhenNotDocumentHidden => println!(" (when not --document-hidden-items)"),
450 }
451 }
452
453 return None;
454 }
455
456 let mut emit = FxIndexMap::<_, EmitType>::default();
457 for list in matches.opt_strs("emit") {
458 for kind in list.split(',') {
459 match kind.parse() {
460 Ok(kind) => {
461 emit.insert(std::mem::discriminant(&kind), kind);
466 }
467 Err(()) => dcx.fatal(format!("unrecognized emission type: {kind}")),
468 }
469 }
470 }
471 let emit = emit.into_values().collect::<Vec<_>>();
472
473 let show_coverage = matches.opt_present("show-coverage");
474 let output_format_s = matches.opt_str("output-format");
475 let output_format = match output_format_s {
476 Some(ref s) => match OutputFormat::try_from(s.as_str()) {
477 Ok(out_fmt) => out_fmt,
478 Err(e) => dcx.fatal(e),
479 },
480 None => OutputFormat::default(),
481 };
482
483 match (
485 output_format_s.as_ref().map(|_| output_format),
486 show_coverage,
487 nightly_options::is_unstable_enabled(matches),
488 ) {
489 (None | Some(OutputFormat::Json), true, _) => {}
490 (_, true, _) => {
491 dcx.fatal(format!(
492 "`--output-format={}` is not supported for the `--show-coverage` option",
493 output_format_s.unwrap_or_default(),
494 ));
495 }
496 (_, false, true) => {}
498 (None | Some(OutputFormat::Html), false, _) => {}
499 (Some(OutputFormat::Json), false, false) => {
500 dcx.fatal(
501 "the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/76578)",
502 );
503 }
504 (Some(OutputFormat::Doctest), false, false) => {
505 dcx.fatal(
506 "the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/134529)",
507 );
508 }
509 }
510
511 let to_check = matches.opt_strs("check-theme");
512 if !to_check.is_empty() {
513 let mut content =
514 std::str::from_utf8(static_files::STATIC_FILES.rustdoc_css.src_bytes).unwrap();
515 if let Some((_, inside)) = content.split_once("/* Begin theme: light */") {
516 content = inside;
517 }
518 if let Some((inside, _)) = content.split_once("/* End theme: light */") {
519 content = inside;
520 }
521 let paths = match theme::load_css_paths(content) {
522 Ok(p) => p,
523 Err(e) => dcx.fatal(e),
524 };
525 let mut errors = 0;
526
527 println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
528 for theme_file in to_check.iter() {
529 print!(" - Checking \"{theme_file}\"...");
530 let (success, differences) = theme::test_theme_against(theme_file, &paths, dcx);
531 if !differences.is_empty() || !success {
532 println!(" FAILED");
533 errors += 1;
534 if !differences.is_empty() {
535 println!("{}", differences.join("\n"));
536 }
537 } else {
538 println!(" OK");
539 }
540 }
541 if errors != 0 {
542 dcx.fatal("[check-theme] one or more tests failed");
543 }
544 return None;
545 }
546
547 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(early_dcx, matches);
548
549 let input = if describe_lints {
550 InputMode::HasFile(make_input(early_dcx, ""))
551 } else {
552 match matches.free.as_slice() {
553 [] if matches.opt_str("merge").as_deref() == Some("finalize") => {
554 InputMode::NoInputMergeFinalize
555 }
556 [] => dcx.fatal("missing file operand"),
557 [input] => InputMode::HasFile(make_input(early_dcx, input)),
558 _ => dcx.fatal("too many file operands"),
559 }
560 };
561
562 let externs = parse_externs(early_dcx, matches, &unstable_opts);
563 let extern_html_root_urls = match parse_extern_html_roots(matches) {
564 Ok(ex) => ex,
565 Err(err) => dcx.fatal(err),
566 };
567
568 let parts_out_dir =
569 match matches.opt_str("parts-out-dir").map(PathToParts::from_flag).transpose() {
570 Ok(parts_out_dir) => parts_out_dir,
571 Err(e) => dcx.fatal(e),
572 };
573 let include_parts_dir = match parse_include_parts_dir(matches) {
574 Ok(include_parts_dir) => include_parts_dir,
575 Err(e) => dcx.fatal(e),
576 };
577
578 let default_settings: Vec<Vec<(String, String)>> = vec![
579 matches
580 .opt_str("default-theme")
581 .iter()
582 .flat_map(|theme| {
583 vec![
584 ("use-system-theme".to_string(), "false".to_string()),
585 ("theme".to_string(), theme.to_string()),
586 ]
587 })
588 .collect(),
589 matches
590 .opt_strs("default-setting")
591 .iter()
592 .map(|s| match s.split_once('=') {
593 None => (s.clone(), "true".to_string()),
594 Some((k, v)) => (k.to_string(), v.to_string()),
595 })
596 .collect(),
597 ];
598 let default_settings = default_settings
599 .into_iter()
600 .flatten()
601 .map(
602 |(k, v)| (k.replace('-', "_"), v),
621 )
622 .collect();
623
624 let test_args = matches.opt_strs("test-args");
625 let test_args: Vec<String> =
626 test_args.iter().flat_map(|s| s.split_whitespace()).map(|s| s.to_string()).collect();
627
628 let should_test = matches.opt_present("test");
629 let no_run = matches.opt_present("no-run");
630
631 if !should_test && no_run {
632 dcx.fatal("the `--test` flag must be passed to enable `--no-run`");
633 }
634
635 let mut output_to_stdout = false;
636 let test_builder_wrappers =
637 matches.opt_strs("test-builder-wrapper").iter().map(PathBuf::from).collect();
638 let output = match (matches.opt_str("out-dir"), matches.opt_str("output")) {
639 (Some(_), Some(_)) => {
640 dcx.fatal("cannot use both 'out-dir' and 'output' at once");
641 }
642 (Some(out_dir), None) | (None, Some(out_dir)) => {
643 output_to_stdout = out_dir == "-";
644 PathBuf::from(out_dir)
645 }
646 (None, None) => PathBuf::from("doc"),
647 };
648
649 let cfgs = matches.opt_strs("cfg");
650 let check_cfgs = matches.opt_strs("check-cfg");
651
652 let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
653
654 let mut loaded_paths = Vec::new();
655
656 if let Some(ref p) = extension_css {
657 loaded_paths.push(p.clone());
658 if !p.is_file() {
659 dcx.fatal("option --extend-css argument must be a file");
660 }
661 }
662
663 let mut themes = Vec::new();
664 if matches.opt_present("theme") {
665 let mut content =
666 std::str::from_utf8(static_files::STATIC_FILES.rustdoc_css.src_bytes).unwrap();
667 if let Some((_, inside)) = content.split_once("/* Begin theme: light */") {
668 content = inside;
669 }
670 if let Some((inside, _)) = content.split_once("/* End theme: light */") {
671 content = inside;
672 }
673 let paths = match theme::load_css_paths(content) {
674 Ok(p) => p,
675 Err(e) => dcx.fatal(e),
676 };
677
678 for (theme_file, theme_s) in
679 matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
680 {
681 if !theme_file.is_file() {
682 dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
683 .with_help("arguments to --theme must be files")
684 .emit();
685 }
686 if theme_file.extension() != Some(OsStr::new("css")) {
687 dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
688 .with_help("arguments to --theme must have a .css extension")
689 .emit();
690 }
691 let (success, ret) = theme::test_theme_against(&theme_file, &paths, dcx);
692 if !success {
693 dcx.fatal(format!("error loading theme file: \"{theme_s}\""));
694 } else if !ret.is_empty() {
695 dcx.struct_warn(format!(
696 "theme file \"{theme_s}\" is missing CSS rules from the default theme",
697 ))
698 .with_warn("the theme may appear incorrect when loaded")
699 .with_help(format!(
700 "to see what rules are missing, call `rustdoc --check-theme \"{theme_s}\"`",
701 ))
702 .emit();
703 }
704 loaded_paths.push(theme_file.clone());
705 themes.push(StylePath { path: theme_file });
706 }
707 }
708
709 let edition = config::parse_crate_edition(early_dcx, matches);
710
711 let mut id_map = html::markdown::IdMap::new();
712 let Some(external_html) = ExternalHtml::load(
713 &matches.opt_strs("html-in-header"),
714 &matches.opt_strs("html-before-content"),
715 &matches.opt_strs("html-after-content"),
716 &matches.opt_strs("markdown-before-content"),
717 &matches.opt_strs("markdown-after-content"),
718 nightly_options::match_is_nightly_build(matches),
719 dcx,
720 &mut id_map,
721 edition,
722 &None,
723 &mut loaded_paths,
724 ) else {
725 dcx.fatal("`ExternalHtml::load` failed");
726 };
727
728 match matches.opt_str("r").as_deref() {
729 Some("rust") | None => {}
730 Some(s) => dcx.fatal(format!("unknown input format: {s}")),
731 }
732
733 let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
734 if let Some(ref index_page) = index_page
735 && !index_page.is_file()
736 {
737 dcx.fatal("option `--index-page` argument must be a file");
738 }
739
740 let target = parse_target_triple(early_dcx, matches);
741 let sysroot = Sysroot::new(matches.opt_str("sysroot").map(PathBuf::from));
742
743 let libs = matches
744 .opt_strs("L")
745 .iter()
746 .map(|s| {
747 SearchPath::from_cli_opt(
748 sysroot.path(),
749 &target,
750 early_dcx,
751 s,
752 #[allow(rustc::bad_opt_access)] unstable_opts.unstable_options,
754 )
755 })
756 .collect();
757
758 let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
759 Ok(types) => types,
760 Err(e) => {
761 dcx.fatal(format!("unknown crate type: {e}"));
762 }
763 };
764
765 let bin_crate = crate_types.contains(&CrateType::Executable);
766 let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
767 let playground_url = matches.opt_str("playground-url");
768 let module_sorting = if matches.opt_present("sort-modules-by-appearance") {
769 ModuleSorting::DeclarationOrder
770 } else {
771 ModuleSorting::Alphabetical
772 };
773 let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
774 let markdown_no_toc = matches.opt_present("markdown-no-toc");
775 let markdown_css = matches.opt_strs("markdown-css");
776 let markdown_playground_url = matches.opt_str("markdown-playground-url");
777 let crate_version = matches.opt_str("crate-version");
778 let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
779 let static_root_path = matches.opt_str("static-root-path");
780 let test_run_directory = matches.opt_str("test-run-directory").map(PathBuf::from);
781 let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
782 let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
783 let codegen_options_strs = matches.opt_strs("C");
784 let unstable_opts_strs = matches.opt_strs("Z");
785 let lib_strs = matches.opt_strs("L");
786 let extern_strs = matches.opt_strs("extern");
787 let test_runtool = matches.opt_str("test-runtool");
788 let test_runtool_args = matches.opt_strs("test-runtool-arg");
789 let document_private = matches.opt_present("document-private-items");
790 let document_hidden = matches.opt_present("document-hidden-items");
791 let run_check = matches.opt_present("check");
792 let generate_redirect_map = matches.opt_present("generate-redirect-map");
793 let show_type_layout = matches.opt_present("show-type-layout");
794 let no_capture = matches.opt_present("no-capture");
795 let generate_link_to_definition = matches.opt_present("generate-link-to-definition");
796 let generate_macro_expansion = matches.opt_present("generate-macro-expansion");
797 let extern_html_root_takes_precedence =
798 matches.opt_present("extern-html-root-takes-precedence");
799 let html_no_source = matches.opt_present("html-no-source");
800 let should_merge = match parse_merge(matches) {
801 Ok(result) => result,
802 Err(e) => dcx.fatal(format!("--merge option error: {e}")),
803 };
804
805 if generate_link_to_definition && (show_coverage || output_format != OutputFormat::Html) {
806 dcx.struct_warn(
807 "`--generate-link-to-definition` option can only be used with HTML output format",
808 )
809 .with_note("`--generate-link-to-definition` option will be ignored")
810 .emit();
811 }
812 if generate_macro_expansion && (show_coverage || output_format != OutputFormat::Html) {
813 dcx.struct_warn(
814 "`--generate-macro-expansion` option can only be used with HTML output format",
815 )
816 .with_note("`--generate-macro-expansion` option will be ignored")
817 .emit();
818 }
819
820 let scrape_examples_options = ScrapeExamplesOptions::new(matches, dcx);
821 let with_examples = matches.opt_strs("with-examples");
822 let call_locations =
823 crate::scrape_examples::load_call_locations(with_examples, dcx, &mut loaded_paths);
824 let doctest_build_args = matches.opt_strs("doctest-build-arg");
825
826 let disable_minification = matches.opt_present("disable-minification");
827
828 let options = Options {
829 bin_crate,
830 proc_macro_crate,
831 error_format,
832 diagnostic_width,
833 libs,
834 lib_strs,
835 externs,
836 extern_strs,
837 cfgs,
838 check_cfgs,
839 codegen_options,
840 codegen_options_strs,
841 unstable_opts,
842 unstable_opts_strs,
843 target,
844 edition,
845 sysroot,
846 lint_opts,
847 describe_lints,
848 lint_cap,
849 should_test,
850 test_args,
851 show_coverage,
852 crate_version,
853 test_run_directory,
854 persist_doctests,
855 test_runtool,
856 test_runtool_args,
857 test_builder,
858 run_check,
859 no_run,
860 test_builder_wrappers,
861 remap_path_prefix,
862 no_capture,
863 crate_name,
864 output_format,
865 json_unused_externs,
866 scrape_examples_options,
867 unstable_features,
868 doctest_build_args,
869 target_modifiers,
870 };
871 let render_options = RenderOptions {
872 output,
873 external_html,
874 id_map,
875 playground_url,
876 module_sorting,
877 themes,
878 extension_css,
879 extern_html_root_urls,
880 extern_html_root_takes_precedence,
881 default_settings,
882 resource_suffix,
883 enable_index_page,
884 index_page,
885 static_root_path,
886 markdown_no_toc,
887 markdown_css,
888 markdown_playground_url,
889 document_private,
890 document_hidden,
891 generate_redirect_map,
892 show_type_layout,
893 unstable_features,
894 emit,
895 generate_link_to_definition,
896 generate_macro_expansion,
897 call_locations,
898 no_emit_shared: false,
899 html_no_source,
900 output_to_stdout,
901 should_merge,
902 include_parts_dir,
903 parts_out_dir,
904 disable_minification,
905 };
906 Some((input, options, render_options, loaded_paths))
907 }
908}
909
910pub(crate) fn markdown_input(input: &Input) -> Option<&Path> {
912 input.opt_path().filter(|p| matches!(p.extension(), Some(e) if e == "md" || e == "markdown"))
913}
914
915fn parse_remap_path_prefix(
916 matches: &getopts::Matches,
917) -> Result<Vec<(PathBuf, PathBuf)>, &'static str> {
918 matches
919 .opt_strs("remap-path-prefix")
920 .into_iter()
921 .map(|remap| {
922 remap
923 .rsplit_once('=')
924 .ok_or("--remap-path-prefix must contain '=' between FROM and TO")
925 .map(|(from, to)| (PathBuf::from(from), PathBuf::from(to)))
926 })
927 .collect()
928}
929
930fn check_deprecated_options(matches: &getopts::Matches, dcx: DiagCtxtHandle<'_>) {
932 let deprecated_flags = [];
933
934 for &flag in deprecated_flags.iter() {
935 if matches.opt_present(flag) {
936 dcx.struct_warn(format!("the `{flag}` flag is deprecated"))
937 .with_note(
938 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
939 for more information",
940 )
941 .emit();
942 }
943 }
944
945 let removed_flags = ["plugins", "plugin-path", "no-defaults", "passes", "input-format"];
946
947 for &flag in removed_flags.iter() {
948 if matches.opt_present(flag) {
949 let mut err = dcx.struct_warn(format!("the `{flag}` flag no longer functions"));
950 err.note(
951 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
952 for more information",
953 );
954
955 if flag == "no-defaults" || flag == "passes" {
956 err.help("you may want to use --document-private-items");
957 } else if flag == "plugins" || flag == "plugin-path" {
958 err.warn("see CVE-2018-1000622");
959 }
960
961 err.emit();
962 }
963 }
964}
965
966fn parse_extern_html_roots(
970 matches: &getopts::Matches,
971) -> Result<BTreeMap<String, String>, &'static str> {
972 let mut externs = BTreeMap::new();
973 for arg in &matches.opt_strs("extern-html-root-url") {
974 let (name, url) =
975 arg.split_once('=').ok_or("--extern-html-root-url must be of the form name=url")?;
976 externs.insert(name.to_string(), url.to_string());
977 }
978 Ok(externs)
979}
980
981#[derive(Clone, Debug)]
985pub(crate) struct PathToParts(pub(crate) PathBuf);
986
987impl PathToParts {
988 fn from_flag(path: String) -> Result<PathToParts, String> {
989 let mut path = PathBuf::from(path);
990 if path.exists() && !path.is_dir() {
992 Err(format!(
993 "--parts-out-dir and --include-parts-dir expect directories, found: {}",
994 path.display(),
995 ))
996 } else {
997 path.push("crate-info");
999 Ok(PathToParts(path))
1000 }
1001 }
1002}
1003
1004fn parse_include_parts_dir(m: &getopts::Matches) -> Result<Vec<PathToParts>, String> {
1006 let mut ret = Vec::new();
1007 for p in m.opt_strs("include-parts-dir") {
1008 let p = PathToParts::from_flag(p)?;
1009 if !p.0.is_file() {
1011 return Err(format!("--include-parts-dir expected {} to be a file", p.0.display()));
1012 }
1013 ret.push(p);
1014 }
1015 Ok(ret)
1016}
1017
1018#[derive(Debug, Clone)]
1020pub(crate) struct ShouldMerge {
1021 pub(crate) read_rendered_cci: bool,
1023 pub(crate) write_rendered_cci: bool,
1025}
1026
1027fn parse_merge(m: &getopts::Matches) -> Result<ShouldMerge, &'static str> {
1030 match m.opt_str("merge").as_deref() {
1031 None => Ok(ShouldMerge { read_rendered_cci: true, write_rendered_cci: true }),
1033 Some("none") if m.opt_present("include-parts-dir") => {
1034 Err("--include-parts-dir not allowed if --merge=none")
1035 }
1036 Some("none") => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: false }),
1037 Some("shared") if m.opt_present("parts-out-dir") || m.opt_present("include-parts-dir") => {
1038 Err("--parts-out-dir and --include-parts-dir not allowed if --merge=shared")
1039 }
1040 Some("shared") => Ok(ShouldMerge { read_rendered_cci: true, write_rendered_cci: true }),
1041 Some("finalize") if m.opt_present("parts-out-dir") => {
1042 Err("--parts-out-dir not allowed if --merge=finalize")
1043 }
1044 Some("finalize") => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: true }),
1045 Some(_) => Err("argument to --merge must be `none`, `shared`, or `finalize`"),
1046 }
1047}