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