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