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