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) sysroot: PathBuf,
107 pub(crate) maybe_sysroot: Option<PathBuf>,
109 pub(crate) lint_opts: Vec<(String, Level)>,
111 pub(crate) describe_lints: bool,
113 pub(crate) lint_cap: Option<Level>,
115
116 pub(crate) should_test: bool,
119 pub(crate) test_args: Vec<String>,
121 pub(crate) test_run_directory: Option<PathBuf>,
123 pub(crate) persist_doctests: Option<PathBuf>,
126 pub(crate) runtool: Option<String>,
128 pub(crate) runtool_args: Vec<String>,
130 pub(crate) enable_per_target_ignores: bool,
134 pub(crate) no_run: bool,
136 pub(crate) remap_path_prefix: Vec<(PathBuf, PathBuf)>,
138
139 pub(crate) test_builder: Option<PathBuf>,
142
143 pub(crate) test_builder_wrappers: Vec<PathBuf>,
145
146 pub(crate) show_coverage: bool,
150
151 pub(crate) crate_version: Option<String>,
154 pub(crate) output_format: OutputFormat,
158 pub(crate) run_check: bool,
161 pub(crate) json_unused_externs: JsonUnusedExterns,
163 pub(crate) nocapture: bool,
165
166 pub(crate) scrape_examples_options: Option<ScrapeExamplesOptions>,
169
170 pub(crate) unstable_features: rustc_feature::UnstableFeatures,
173
174 pub(crate) expanded_args: Vec<String>,
179
180 pub(crate) doctest_compilation_args: Vec<String>,
182}
183
184impl fmt::Debug for Options {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 struct FmtExterns<'a>(&'a Externs);
187
188 impl fmt::Debug for FmtExterns<'_> {
189 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190 f.debug_map().entries(self.0.iter()).finish()
191 }
192 }
193
194 f.debug_struct("Options")
195 .field("crate_name", &self.crate_name)
196 .field("bin_crate", &self.bin_crate)
197 .field("proc_macro_crate", &self.proc_macro_crate)
198 .field("error_format", &self.error_format)
199 .field("libs", &self.libs)
200 .field("externs", &FmtExterns(&self.externs))
201 .field("cfgs", &self.cfgs)
202 .field("check-cfgs", &self.check_cfgs)
203 .field("codegen_options", &"...")
204 .field("unstable_options", &"...")
205 .field("target", &self.target)
206 .field("edition", &self.edition)
207 .field("sysroot", &self.sysroot)
208 .field("maybe_sysroot", &self.maybe_sysroot)
209 .field("lint_opts", &self.lint_opts)
210 .field("describe_lints", &self.describe_lints)
211 .field("lint_cap", &self.lint_cap)
212 .field("should_test", &self.should_test)
213 .field("test_args", &self.test_args)
214 .field("test_run_directory", &self.test_run_directory)
215 .field("persist_doctests", &self.persist_doctests)
216 .field("show_coverage", &self.show_coverage)
217 .field("crate_version", &self.crate_version)
218 .field("runtool", &self.runtool)
219 .field("runtool_args", &self.runtool_args)
220 .field("enable-per-target-ignores", &self.enable_per_target_ignores)
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("nocapture", &self.nocapture)
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}
314
315#[derive(Copy, Clone, Debug, PartialEq, Eq)]
316pub(crate) enum ModuleSorting {
317 DeclarationOrder,
318 Alphabetical,
319}
320
321#[derive(Clone, Debug, PartialEq, Eq)]
322pub(crate) enum EmitType {
323 Unversioned,
324 Toolchain,
325 InvocationSpecific,
326 DepInfo(Option<PathBuf>),
327}
328
329impl FromStr for EmitType {
330 type Err = ();
331
332 fn from_str(s: &str) -> Result<Self, Self::Err> {
333 match s {
334 "unversioned-shared-resources" => Ok(Self::Unversioned),
335 "toolchain-shared-resources" => Ok(Self::Toolchain),
336 "invocation-specific" => Ok(Self::InvocationSpecific),
337 "dep-info" => Ok(Self::DepInfo(None)),
338 option => {
339 if let Some(file) = option.strip_prefix("dep-info=") {
340 Ok(Self::DepInfo(Some(Path::new(file).into())))
341 } else {
342 Err(())
343 }
344 }
345 }
346 }
347}
348
349impl RenderOptions {
350 pub(crate) fn should_emit_crate(&self) -> bool {
351 self.emit.is_empty() || self.emit.contains(&EmitType::InvocationSpecific)
352 }
353
354 pub(crate) fn dep_info(&self) -> Option<Option<&Path>> {
355 for emit in &self.emit {
356 if let EmitType::DepInfo(file) = emit {
357 return Some(file.as_deref());
358 }
359 }
360 None
361 }
362}
363
364fn make_input(early_dcx: &EarlyDiagCtxt, input: &str) -> Input {
368 if input == "-" {
369 let mut src = String::new();
370 if io::stdin().read_to_string(&mut src).is_err() {
371 early_dcx.early_fatal("couldn't read from stdin, as it did not contain valid UTF-8");
374 }
375 Input::Str { name: FileName::anon_source_code(&src), input: src }
376 } else {
377 Input::File(PathBuf::from(input))
378 }
379}
380
381impl Options {
382 pub(crate) fn from_matches(
385 early_dcx: &mut EarlyDiagCtxt,
386 matches: &getopts::Matches,
387 args: Vec<String>,
388 ) -> Option<(InputMode, Options, RenderOptions)> {
389 nightly_options::check_nightly_options(early_dcx, matches, &opts());
391
392 if args.is_empty() || matches.opt_present("h") || matches.opt_present("help") {
393 crate::usage("rustdoc");
394 return None;
395 } else if matches.opt_present("version") {
396 rustc_driver::version!(&early_dcx, "rustdoc", matches);
397 return None;
398 }
399
400 if rustc_driver::describe_flag_categories(early_dcx, matches) {
401 return None;
402 }
403
404 let color = config::parse_color(early_dcx, matches);
405 let config::JsonConfig { json_rendered, json_unused_externs, json_color, .. } =
406 config::parse_json(early_dcx, matches);
407 let error_format =
408 config::parse_error_format(early_dcx, matches, color, json_color, json_rendered);
409 let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_default();
410
411 let mut target_modifiers = BTreeMap::<OptionsTargetModifiers, String>::new();
412 let codegen_options = CodegenOptions::build(early_dcx, matches, &mut target_modifiers);
413 let unstable_opts = UnstableOptions::build(early_dcx, matches, &mut target_modifiers);
414
415 let remap_path_prefix = match parse_remap_path_prefix(matches) {
416 Ok(prefix_mappings) => prefix_mappings,
417 Err(err) => {
418 early_dcx.early_fatal(err);
419 }
420 };
421
422 let dcx = new_dcx(error_format, None, diagnostic_width, &unstable_opts);
423 let dcx = dcx.handle();
424
425 check_deprecated_options(matches, dcx);
427
428 if matches.opt_strs("passes") == ["list"] {
429 println!("Available passes for running rustdoc:");
430 for pass in passes::PASSES {
431 println!("{:>20} - {}", pass.name, pass.description);
432 }
433 println!("\nDefault passes for rustdoc:");
434 for p in passes::DEFAULT_PASSES {
435 print!("{:>20}", p.pass.name);
436 println_condition(p.condition);
437 }
438
439 if nightly_options::match_is_nightly_build(matches) {
440 println!("\nPasses run with `--show-coverage`:");
441 for p in passes::COVERAGE_PASSES {
442 print!("{:>20}", p.pass.name);
443 println_condition(p.condition);
444 }
445 }
446
447 fn println_condition(condition: Condition) {
448 use Condition::*;
449 match condition {
450 Always => println!(),
451 WhenDocumentPrivate => println!(" (when --document-private-items)"),
452 WhenNotDocumentPrivate => println!(" (when not --document-private-items)"),
453 WhenNotDocumentHidden => println!(" (when not --document-hidden-items)"),
454 }
455 }
456
457 return None;
458 }
459
460 let mut emit = Vec::new();
461 for list in matches.opt_strs("emit") {
462 for kind in list.split(',') {
463 match kind.parse() {
464 Ok(kind) => emit.push(kind),
465 Err(()) => dcx.fatal(format!("unrecognized emission type: {kind}")),
466 }
467 }
468 }
469
470 let show_coverage = matches.opt_present("show-coverage");
471 let output_format_s = matches.opt_str("output-format");
472 let output_format = match output_format_s {
473 Some(ref s) => match OutputFormat::try_from(s.as_str()) {
474 Ok(out_fmt) => out_fmt,
475 Err(e) => dcx.fatal(e),
476 },
477 None => OutputFormat::default(),
478 };
479
480 match (
482 output_format_s.as_ref().map(|_| output_format),
483 show_coverage,
484 nightly_options::is_unstable_enabled(matches),
485 ) {
486 (None | Some(OutputFormat::Json), true, _) => {}
487 (_, true, _) => {
488 dcx.fatal(format!(
489 "`--output-format={}` is not supported for the `--show-coverage` option",
490 output_format_s.unwrap_or_default(),
491 ));
492 }
493 (_, false, true) => {}
495 (None | Some(OutputFormat::Html), false, _) => {}
496 (Some(OutputFormat::Json), false, false) => {
497 dcx.fatal(
498 "the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/76578)",
499 );
500 }
501 (Some(OutputFormat::Doctest), false, false) => {
502 dcx.fatal(
503 "the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/134529)",
504 );
505 }
506 }
507
508 let to_check = matches.opt_strs("check-theme");
509 if !to_check.is_empty() {
510 let mut content =
511 std::str::from_utf8(static_files::STATIC_FILES.rustdoc_css.src_bytes).unwrap();
512 if let Some((_, inside)) = content.split_once("/* Begin theme: light */") {
513 content = inside;
514 }
515 if let Some((inside, _)) = content.split_once("/* End theme: light */") {
516 content = inside;
517 }
518 let paths = match theme::load_css_paths(content) {
519 Ok(p) => p,
520 Err(e) => dcx.fatal(e),
521 };
522 let mut errors = 0;
523
524 println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
525 for theme_file in to_check.iter() {
526 print!(" - Checking \"{theme_file}\"...");
527 let (success, differences) = theme::test_theme_against(theme_file, &paths, dcx);
528 if !differences.is_empty() || !success {
529 println!(" FAILED");
530 errors += 1;
531 if !differences.is_empty() {
532 println!("{}", differences.join("\n"));
533 }
534 } else {
535 println!(" OK");
536 }
537 }
538 if errors != 0 {
539 dcx.fatal("[check-theme] one or more tests failed");
540 }
541 return None;
542 }
543
544 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(early_dcx, matches);
545
546 let input = if describe_lints {
547 InputMode::HasFile(make_input(early_dcx, ""))
548 } else {
549 match matches.free.as_slice() {
550 [] if matches.opt_str("merge").as_deref() == Some("finalize") => {
551 InputMode::NoInputMergeFinalize
552 }
553 [] => dcx.fatal("missing file operand"),
554 [input] => InputMode::HasFile(make_input(early_dcx, input)),
555 _ => dcx.fatal("too many file operands"),
556 }
557 };
558
559 let externs = parse_externs(early_dcx, matches, &unstable_opts);
560 let extern_html_root_urls = match parse_extern_html_roots(matches) {
561 Ok(ex) => ex,
562 Err(err) => dcx.fatal(err),
563 };
564
565 let parts_out_dir =
566 match matches.opt_str("parts-out-dir").map(PathToParts::from_flag).transpose() {
567 Ok(parts_out_dir) => parts_out_dir,
568 Err(e) => dcx.fatal(e),
569 };
570 let include_parts_dir = match parse_include_parts_dir(matches) {
571 Ok(include_parts_dir) => include_parts_dir,
572 Err(e) => dcx.fatal(e),
573 };
574
575 let default_settings: Vec<Vec<(String, String)>> = vec![
576 matches
577 .opt_str("default-theme")
578 .iter()
579 .flat_map(|theme| {
580 vec![
581 ("use-system-theme".to_string(), "false".to_string()),
582 ("theme".to_string(), theme.to_string()),
583 ]
584 })
585 .collect(),
586 matches
587 .opt_strs("default-setting")
588 .iter()
589 .map(|s| match s.split_once('=') {
590 None => (s.clone(), "true".to_string()),
591 Some((k, v)) => (k.to_string(), v.to_string()),
592 })
593 .collect(),
594 ];
595 let default_settings = default_settings
596 .into_iter()
597 .flatten()
598 .map(
599 |(k, v)| (k.replace('-', "_"), v),
618 )
619 .collect();
620
621 let test_args = matches.opt_strs("test-args");
622 let test_args: Vec<String> =
623 test_args.iter().flat_map(|s| s.split_whitespace()).map(|s| s.to_string()).collect();
624
625 let should_test = matches.opt_present("test");
626 let no_run = matches.opt_present("no-run");
627
628 if !should_test && no_run {
629 dcx.fatal("the `--test` flag must be passed to enable `--no-run`");
630 }
631
632 let mut output_to_stdout = false;
633 let test_builder_wrappers =
634 matches.opt_strs("test-builder-wrapper").iter().map(PathBuf::from).collect();
635 let output = match (matches.opt_str("out-dir"), matches.opt_str("output")) {
636 (Some(_), Some(_)) => {
637 dcx.fatal("cannot use both 'out-dir' and 'output' at once");
638 }
639 (Some(out_dir), None) | (None, Some(out_dir)) => {
640 output_to_stdout = out_dir == "-";
641 PathBuf::from(out_dir)
642 }
643 (None, None) => PathBuf::from("doc"),
644 };
645
646 let cfgs = matches.opt_strs("cfg");
647 let check_cfgs = matches.opt_strs("check-cfg");
648
649 let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
650
651 if let Some(ref p) = extension_css
652 && !p.is_file()
653 {
654 dcx.fatal("option --extend-css argument must be a file");
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 themes.push(StylePath { path: theme_file });
699 }
700 }
701
702 let edition = config::parse_crate_edition(early_dcx, matches);
703
704 let mut id_map = html::markdown::IdMap::new();
705 let Some(external_html) = ExternalHtml::load(
706 &matches.opt_strs("html-in-header"),
707 &matches.opt_strs("html-before-content"),
708 &matches.opt_strs("html-after-content"),
709 &matches.opt_strs("markdown-before-content"),
710 &matches.opt_strs("markdown-after-content"),
711 nightly_options::match_is_nightly_build(matches),
712 dcx,
713 &mut id_map,
714 edition,
715 &None,
716 ) else {
717 dcx.fatal("`ExternalHtml::load` failed");
718 };
719
720 match matches.opt_str("r").as_deref() {
721 Some("rust") | None => {}
722 Some(s) => dcx.fatal(format!("unknown input format: {s}")),
723 }
724
725 let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
726 if let Some(ref index_page) = index_page
727 && !index_page.is_file()
728 {
729 dcx.fatal("option `--index-page` argument must be a file");
730 }
731
732 let target = parse_target_triple(early_dcx, matches);
733 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
734
735 let sysroot = rustc_session::filesearch::materialize_sysroot(maybe_sysroot.clone());
736
737 let libs = matches
738 .opt_strs("L")
739 .iter()
740 .map(|s| {
741 SearchPath::from_cli_opt(
742 &sysroot,
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 runtool = matches.opt_str("runtool");
783 let runtool_args = matches.opt_strs("runtool-arg");
784 let enable_per_target_ignores = matches.opt_present("enable-per-target-ignores");
785 let document_private = matches.opt_present("document-private-items");
786 let document_hidden = matches.opt_present("document-hidden-items");
787 let run_check = matches.opt_present("check");
788 let generate_redirect_map = matches.opt_present("generate-redirect-map");
789 let show_type_layout = matches.opt_present("show-type-layout");
790 let nocapture = matches.opt_present("nocapture");
791 let generate_link_to_definition = matches.opt_present("generate-link-to-definition");
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
808 let scrape_examples_options = ScrapeExamplesOptions::new(matches, dcx);
809 let with_examples = matches.opt_strs("with-examples");
810 let call_locations = crate::scrape_examples::load_call_locations(with_examples, dcx);
811 let doctest_compilation_args = matches.opt_strs("doctest-compilation-args");
812
813 let unstable_features =
814 rustc_feature::UnstableFeatures::from_environment(crate_name.as_deref());
815
816 let disable_minification = matches.opt_present("disable-minification");
817
818 let options = Options {
819 bin_crate,
820 proc_macro_crate,
821 error_format,
822 diagnostic_width,
823 libs,
824 lib_strs,
825 externs,
826 extern_strs,
827 cfgs,
828 check_cfgs,
829 codegen_options,
830 codegen_options_strs,
831 unstable_opts,
832 unstable_opts_strs,
833 target,
834 edition,
835 sysroot,
836 maybe_sysroot,
837 lint_opts,
838 describe_lints,
839 lint_cap,
840 should_test,
841 test_args,
842 show_coverage,
843 crate_version,
844 test_run_directory,
845 persist_doctests,
846 runtool,
847 runtool_args,
848 enable_per_target_ignores,
849 test_builder,
850 run_check,
851 no_run,
852 test_builder_wrappers,
853 remap_path_prefix,
854 nocapture,
855 crate_name,
856 output_format,
857 json_unused_externs,
858 scrape_examples_options,
859 unstable_features,
860 expanded_args: args,
861 doctest_compilation_args,
862 };
863 let render_options = RenderOptions {
864 output,
865 external_html,
866 id_map,
867 playground_url,
868 module_sorting,
869 themes,
870 extension_css,
871 extern_html_root_urls,
872 extern_html_root_takes_precedence,
873 default_settings,
874 resource_suffix,
875 enable_index_page,
876 index_page,
877 static_root_path,
878 markdown_no_toc,
879 markdown_css,
880 markdown_playground_url,
881 document_private,
882 document_hidden,
883 generate_redirect_map,
884 show_type_layout,
885 unstable_features,
886 emit,
887 generate_link_to_definition,
888 call_locations,
889 no_emit_shared: false,
890 html_no_source,
891 output_to_stdout,
892 should_merge,
893 include_parts_dir,
894 parts_out_dir,
895 disable_minification,
896 };
897 Some((input, options, render_options))
898 }
899}
900
901pub(crate) fn markdown_input(input: &Input) -> Option<&Path> {
903 input.opt_path().filter(|p| matches!(p.extension(), Some(e) if e == "md" || e == "markdown"))
904}
905
906fn parse_remap_path_prefix(
907 matches: &getopts::Matches,
908) -> Result<Vec<(PathBuf, PathBuf)>, &'static str> {
909 matches
910 .opt_strs("remap-path-prefix")
911 .into_iter()
912 .map(|remap| {
913 remap
914 .rsplit_once('=')
915 .ok_or("--remap-path-prefix must contain '=' between FROM and TO")
916 .map(|(from, to)| (PathBuf::from(from), PathBuf::from(to)))
917 })
918 .collect()
919}
920
921fn check_deprecated_options(matches: &getopts::Matches, dcx: DiagCtxtHandle<'_>) {
923 let deprecated_flags = [];
924
925 for &flag in deprecated_flags.iter() {
926 if matches.opt_present(flag) {
927 dcx.struct_warn(format!("the `{flag}` flag is deprecated"))
928 .with_note(
929 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
930 for more information",
931 )
932 .emit();
933 }
934 }
935
936 let removed_flags = ["plugins", "plugin-path", "no-defaults", "passes", "input-format"];
937
938 for &flag in removed_flags.iter() {
939 if matches.opt_present(flag) {
940 let mut err = dcx.struct_warn(format!("the `{flag}` flag no longer functions"));
941 err.note(
942 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
943 for more information",
944 );
945
946 if flag == "no-defaults" || flag == "passes" {
947 err.help("you may want to use --document-private-items");
948 } else if flag == "plugins" || flag == "plugin-path" {
949 err.warn("see CVE-2018-1000622");
950 }
951
952 err.emit();
953 }
954 }
955}
956
957fn parse_extern_html_roots(
961 matches: &getopts::Matches,
962) -> Result<BTreeMap<String, String>, &'static str> {
963 let mut externs = BTreeMap::new();
964 for arg in &matches.opt_strs("extern-html-root-url") {
965 let (name, url) =
966 arg.split_once('=').ok_or("--extern-html-root-url must be of the form name=url")?;
967 externs.insert(name.to_string(), url.to_string());
968 }
969 Ok(externs)
970}
971
972#[derive(Clone, Debug)]
976pub(crate) struct PathToParts(pub(crate) PathBuf);
977
978impl PathToParts {
979 fn from_flag(path: String) -> Result<PathToParts, String> {
980 let mut path = PathBuf::from(path);
981 if path.exists() && !path.is_dir() {
983 Err(format!(
984 "--parts-out-dir and --include-parts-dir expect directories, found: {}",
985 path.display(),
986 ))
987 } else {
988 path.push("crate-info");
990 Ok(PathToParts(path))
991 }
992 }
993}
994
995fn parse_include_parts_dir(m: &getopts::Matches) -> Result<Vec<PathToParts>, String> {
997 let mut ret = Vec::new();
998 for p in m.opt_strs("include-parts-dir") {
999 let p = PathToParts::from_flag(p)?;
1000 if !p.0.is_file() {
1002 return Err(format!("--include-parts-dir expected {} to be a file", p.0.display()));
1003 }
1004 ret.push(p);
1005 }
1006 Ok(ret)
1007}
1008
1009#[derive(Debug, Clone)]
1011pub(crate) struct ShouldMerge {
1012 pub(crate) read_rendered_cci: bool,
1014 pub(crate) write_rendered_cci: bool,
1016}
1017
1018fn parse_merge(m: &getopts::Matches) -> Result<ShouldMerge, &'static str> {
1021 match m.opt_str("merge").as_deref() {
1022 None => Ok(ShouldMerge { read_rendered_cci: true, write_rendered_cci: true }),
1024 Some("none") if m.opt_present("include-parts-dir") => {
1025 Err("--include-parts-dir not allowed if --merge=none")
1026 }
1027 Some("none") => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: false }),
1028 Some("shared") if m.opt_present("parts-out-dir") || m.opt_present("include-parts-dir") => {
1029 Err("--parts-out-dir and --include-parts-dir not allowed if --merge=shared")
1030 }
1031 Some("shared") => Ok(ShouldMerge { read_rendered_cci: true, write_rendered_cci: true }),
1032 Some("finalize") if m.opt_present("parts-out-dir") => {
1033 Err("--parts-out-dir not allowed if --merge=finalize")
1034 }
1035 Some("finalize") => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: true }),
1036 Some(_) => Err("argument to --merge must be `none`, `shared`, or `finalize`"),
1037 }
1038}