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 HtmlStaticFiles,
326 HtmlNonStaticFiles,
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::HtmlStaticFiles),
337 "invocation-specific" => Ok(Self::HtmlNonStaticFiles),
338 "html-static-files" => Ok(Self::HtmlStaticFiles),
340 "html-non-static-files" => Ok(Self::HtmlNonStaticFiles),
341 "dep-info" => Ok(Self::DepInfo(None)),
342 option => match option.strip_prefix("dep-info=") {
343 Some("-") => Ok(Self::DepInfo(Some(OutFileName::Stdout))),
344 Some(f) => Ok(Self::DepInfo(Some(OutFileName::Real(f.into())))),
345 None => Err(()),
346 },
347 }
348 }
349}
350
351impl RenderOptions {
352 pub(crate) fn should_emit_crate(&self) -> bool {
353 self.emit.is_empty() || self.emit.contains(&EmitType::HtmlNonStaticFiles)
354 }
355
356 pub(crate) fn dep_info(&self) -> Option<Option<&OutFileName>> {
357 for emit in &self.emit {
358 if let EmitType::DepInfo(file) = emit {
359 return Some(file.as_ref());
360 }
361 }
362 None
363 }
364}
365
366fn make_input(early_dcx: &EarlyDiagCtxt, input: &str) -> Input {
370 if input == "-" {
371 let mut src = String::new();
372 if io::stdin().read_to_string(&mut src).is_err() {
373 early_dcx.early_fatal("couldn't read from stdin, as it did not contain valid UTF-8");
376 }
377 Input::Str { name: FileName::anon_source_code(&src), input: src }
378 } else {
379 Input::File(PathBuf::from(input))
380 }
381}
382
383impl Options {
384 pub(crate) fn from_matches(
387 early_dcx: &mut EarlyDiagCtxt,
388 matches: &getopts::Matches,
389 args: Vec<String>,
390 ) -> Option<(InputMode, Options, RenderOptions, Vec<PathBuf>)> {
391 nightly_options::check_nightly_options(early_dcx, matches, &opts());
393
394 if args.is_empty() || matches.opt_present("h") || matches.opt_present("help") {
395 crate::usage("rustdoc");
396 return None;
397 } else if matches.opt_present("version") {
398 rustc_driver::version!(&early_dcx, "rustdoc", matches);
399 return None;
400 }
401
402 if rustc_driver::describe_flag_categories(early_dcx, matches) {
403 return None;
404 }
405
406 let color = config::parse_color(early_dcx, matches);
407 let crate_name = matches.opt_str("crate-name");
408 let unstable_features =
409 rustc_feature::UnstableFeatures::from_environment(crate_name.as_deref());
410 let config::JsonConfig { json_rendered, json_unused_externs, json_color, .. } =
411 config::parse_json(early_dcx, matches);
412 let error_format =
413 config::parse_error_format(early_dcx, matches, color, json_color, json_rendered);
414 let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_default();
415
416 let mut target_modifiers = BTreeMap::<OptionsTargetModifiers, String>::new();
417 let codegen_options = CodegenOptions::build(early_dcx, matches, &mut target_modifiers);
418 let unstable_opts = UnstableOptions::build(early_dcx, matches, &mut target_modifiers);
419
420 let remap_path_prefix = match parse_remap_path_prefix(matches) {
421 Ok(prefix_mappings) => prefix_mappings,
422 Err(err) => {
423 early_dcx.early_fatal(err);
424 }
425 };
426
427 let dcx = new_dcx(error_format, None, diagnostic_width, &unstable_opts);
428 let dcx = dcx.handle();
429
430 check_deprecated_options(matches, dcx);
432
433 if matches.opt_strs("passes") == ["list"] {
434 println!("Available passes for running rustdoc:");
435 for pass in passes::PASSES {
436 println!("{:>20} - {}", pass.name, pass.description);
437 }
438 println!("\nDefault passes for rustdoc:");
439 for p in passes::DEFAULT_PASSES {
440 print!("{:>20}", p.pass.name);
441 println_condition(p.condition);
442 }
443
444 if nightly_options::match_is_nightly_build(matches) {
445 println!("\nPasses run with `--show-coverage`:");
446 for p in passes::COVERAGE_PASSES {
447 print!("{:>20}", p.pass.name);
448 println_condition(p.condition);
449 }
450 }
451
452 fn println_condition(condition: Condition) {
453 use Condition::*;
454 match condition {
455 Always => println!(),
456 WhenDocumentPrivate => println!(" (when --document-private-items)"),
457 WhenNotDocumentPrivate => println!(" (when not --document-private-items)"),
458 WhenNotDocumentHidden => println!(" (when not --document-hidden-items)"),
459 }
460 }
461
462 return None;
463 }
464
465 let should_test = matches.opt_present("test");
466
467 let mut emit = FxIndexMap::<_, EmitType>::default();
468 for list in matches.opt_strs("emit") {
469 if should_test {
470 dcx.fatal("the `--test` flag and the `--emit` flag are not supported together");
471 }
472 for kind in list.split(',') {
473 match kind.parse() {
474 Ok(kind) => {
475 emit.insert(std::mem::discriminant(&kind), kind);
480 }
481 Err(()) => dcx.fatal(format!("unrecognized emission type: {kind}")),
482 }
483 }
484 }
485 let emit = emit.into_values().collect::<Vec<_>>();
486
487 let show_coverage = matches.opt_present("show-coverage");
488 let output_format_s = matches.opt_str("output-format");
489 let output_format = match output_format_s {
490 Some(ref s) => match OutputFormat::try_from(s.as_str()) {
491 Ok(out_fmt) => out_fmt,
492 Err(e) => dcx.fatal(e),
493 },
494 None => OutputFormat::default(),
495 };
496
497 match (
499 output_format_s.as_ref().map(|_| output_format),
500 show_coverage,
501 nightly_options::is_unstable_enabled(matches),
502 ) {
503 (None | Some(OutputFormat::Json), true, _) => {}
504 (_, true, _) => {
505 dcx.fatal(format!(
506 "`--output-format={}` is not supported for the `--show-coverage` option",
507 output_format_s.unwrap_or_default(),
508 ));
509 }
510 (_, false, true) => {}
512 (None | Some(OutputFormat::Html), false, _) => {}
513 (Some(OutputFormat::Json), false, false) => {
514 dcx.fatal(
515 "the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/76578)",
516 );
517 }
518 (Some(OutputFormat::Doctest), false, false) => {
519 dcx.fatal(
520 "the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/134529)",
521 );
522 }
523 }
524
525 if output_format == OutputFormat::Json {
526 if let Some(emit_flag) = emit.iter().find_map(|emit| match emit {
527 EmitType::HtmlStaticFiles => Some("html-static-files"),
528 EmitType::HtmlNonStaticFiles => Some("html-non-static-files"),
529 EmitType::DepInfo(_) => None,
530 }) {
531 dcx.fatal(format!(
532 "the `--emit={emit_flag}` flag is not supported with `--output-format=json`",
533 ));
534 }
535 }
536
537 let to_check = matches.opt_strs("check-theme");
538 if !to_check.is_empty() {
539 let mut content =
540 std::str::from_utf8(static_files::STATIC_FILES.rustdoc_css.src_bytes).unwrap();
541 if let Some((_, inside)) = content.split_once("/* Begin theme: light */") {
542 content = inside;
543 }
544 if let Some((inside, _)) = content.split_once("/* End theme: light */") {
545 content = inside;
546 }
547 let paths = match theme::load_css_paths(content) {
548 Ok(p) => p,
549 Err(e) => dcx.fatal(e),
550 };
551 let mut errors = 0;
552
553 println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
554 for theme_file in to_check.iter() {
555 print!(" - Checking \"{theme_file}\"...");
556 let (success, differences) = theme::test_theme_against(theme_file, &paths, dcx);
557 if !differences.is_empty() || !success {
558 println!(" FAILED");
559 errors += 1;
560 if !differences.is_empty() {
561 println!("{}", differences.join("\n"));
562 }
563 } else {
564 println!(" OK");
565 }
566 }
567 if errors != 0 {
568 dcx.fatal("[check-theme] one or more tests failed");
569 }
570 return None;
571 }
572
573 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(early_dcx, matches);
574
575 let input = if describe_lints {
576 InputMode::HasFile(make_input(early_dcx, ""))
577 } else {
578 match matches.free.as_slice() {
579 [] if matches.opt_str("merge").as_deref() == Some("finalize") => {
580 InputMode::NoInputMergeFinalize
581 }
582 [] => dcx.fatal("missing file operand"),
583 [input] => InputMode::HasFile(make_input(early_dcx, input)),
584 _ => dcx.fatal("too many file operands"),
585 }
586 };
587
588 let externs = parse_externs(early_dcx, matches, &unstable_opts);
589 let extern_html_root_urls = match parse_extern_html_roots(matches) {
590 Ok(ex) => ex,
591 Err(err) => dcx.fatal(err),
592 };
593
594 let parts_out_dir =
595 match matches.opt_str("parts-out-dir").map(PathToParts::from_flag).transpose() {
596 Ok(parts_out_dir) => parts_out_dir,
597 Err(e) => dcx.fatal(e),
598 };
599 let include_parts_dir = match parse_include_parts_dir(matches) {
600 Ok(include_parts_dir) => include_parts_dir,
601 Err(e) => dcx.fatal(e),
602 };
603
604 let default_settings: Vec<Vec<(String, String)>> = vec![
605 matches
606 .opt_str("default-theme")
607 .iter()
608 .flat_map(|theme| {
609 vec![
610 ("use-system-theme".to_string(), "false".to_string()),
611 ("theme".to_string(), theme.to_string()),
612 ]
613 })
614 .collect(),
615 matches
616 .opt_strs("default-setting")
617 .iter()
618 .map(|s| match s.split_once('=') {
619 None => (s.clone(), "true".to_string()),
620 Some((k, v)) => (k.to_string(), v.to_string()),
621 })
622 .collect(),
623 ];
624 let default_settings = default_settings
625 .into_iter()
626 .flatten()
627 .map(
628 |(k, v)| (k.replace('-', "_"), v),
647 )
648 .collect();
649
650 let test_args = matches.opt_strs("test-args");
651 let test_args: Vec<String> =
652 test_args.iter().flat_map(|s| s.split_whitespace()).map(|s| s.to_string()).collect();
653
654 let no_run = matches.opt_present("no-run");
655
656 if !should_test && no_run {
657 dcx.fatal("the `--test` flag must be passed to enable `--no-run`");
658 }
659
660 let mut output_to_stdout = false;
661 let test_builder_wrappers =
662 matches.opt_strs("test-builder-wrapper").iter().map(PathBuf::from).collect();
663 let output = match (matches.opt_str("out-dir"), matches.opt_str("output")) {
664 (Some(_), Some(_)) => {
665 dcx.fatal("cannot use both 'out-dir' and 'output' at once");
666 }
667 (Some(out_dir), None) | (None, Some(out_dir)) => {
668 output_to_stdout = out_dir == "-";
669 PathBuf::from(out_dir)
670 }
671 (None, None) => PathBuf::from("doc"),
672 };
673
674 let cfgs = matches.opt_strs("cfg");
675 let check_cfgs = matches.opt_strs("check-cfg");
676
677 let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
678
679 let mut loaded_paths = Vec::new();
680
681 if let Some(ref p) = extension_css {
682 loaded_paths.push(p.clone());
683 if !p.is_file() {
684 dcx.fatal("option --extend-css argument must be a file");
685 }
686 }
687
688 let mut themes = Vec::new();
689 if matches.opt_present("theme") {
690 let mut content =
691 std::str::from_utf8(static_files::STATIC_FILES.rustdoc_css.src_bytes).unwrap();
692 if let Some((_, inside)) = content.split_once("/* Begin theme: light */") {
693 content = inside;
694 }
695 if let Some((inside, _)) = content.split_once("/* End theme: light */") {
696 content = inside;
697 }
698 let paths = match theme::load_css_paths(content) {
699 Ok(p) => p,
700 Err(e) => dcx.fatal(e),
701 };
702
703 for (theme_file, theme_s) in
704 matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
705 {
706 if !theme_file.is_file() {
707 dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
708 .with_help("arguments to --theme must be files")
709 .emit();
710 }
711 if theme_file.extension() != Some(OsStr::new("css")) {
712 dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
713 .with_help("arguments to --theme must have a .css extension")
714 .emit();
715 }
716 let (success, ret) = theme::test_theme_against(&theme_file, &paths, dcx);
717 if !success {
718 dcx.fatal(format!("error loading theme file: \"{theme_s}\""));
719 } else if !ret.is_empty() {
720 dcx.struct_warn(format!(
721 "theme file \"{theme_s}\" is missing CSS rules from the default theme",
722 ))
723 .with_warn("the theme may appear incorrect when loaded")
724 .with_help(format!(
725 "to see what rules are missing, call `rustdoc --check-theme \"{theme_s}\"`",
726 ))
727 .emit();
728 }
729 loaded_paths.push(theme_file.clone());
730 themes.push(StylePath { path: theme_file });
731 }
732 }
733
734 let edition = config::parse_crate_edition(early_dcx, matches);
735
736 let mut id_map = html::markdown::IdMap::new();
737 let Some(external_html) = ExternalHtml::load(
738 &matches.opt_strs("html-in-header"),
739 &matches.opt_strs("html-before-content"),
740 &matches.opt_strs("html-after-content"),
741 &matches.opt_strs("markdown-before-content"),
742 &matches.opt_strs("markdown-after-content"),
743 nightly_options::match_is_nightly_build(matches),
744 dcx,
745 &mut id_map,
746 edition,
747 &None,
748 &mut loaded_paths,
749 ) else {
750 dcx.fatal("`ExternalHtml::load` failed");
751 };
752
753 match matches.opt_str("r").as_deref() {
754 Some("rust") | None => {}
755 Some(s) => dcx.fatal(format!("unknown input format: {s}")),
756 }
757
758 let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
759 if let Some(ref index_page) = index_page
760 && !index_page.is_file()
761 {
762 dcx.fatal("option `--index-page` argument must be a file");
763 }
764
765 let target = parse_target_triple(early_dcx, matches);
766 let sysroot = Sysroot::new(matches.opt_str("sysroot").map(PathBuf::from));
767
768 let libs = matches
769 .opt_strs("L")
770 .iter()
771 .map(|s| {
772 SearchPath::from_cli_opt(
773 sysroot.path(),
774 &target,
775 early_dcx,
776 s,
777 #[allow(rustc::bad_opt_access)] unstable_opts.unstable_options,
779 )
780 })
781 .collect();
782
783 let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
784 Ok(types) => types,
785 Err(e) => {
786 dcx.fatal(format!("unknown crate type: {e}"));
787 }
788 };
789
790 let bin_crate = crate_types.contains(&CrateType::Executable);
791 let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
792 let playground_url = matches.opt_str("playground-url");
793 let module_sorting = if matches.opt_present("sort-modules-by-appearance") {
794 ModuleSorting::DeclarationOrder
795 } else {
796 ModuleSorting::Alphabetical
797 };
798 let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
799 let markdown_no_toc = matches.opt_present("markdown-no-toc");
800 let markdown_css = matches.opt_strs("markdown-css");
801 let markdown_playground_url = matches.opt_str("markdown-playground-url");
802 let crate_version = matches.opt_str("crate-version");
803 let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
804 let static_root_path = matches.opt_str("static-root-path");
805 let test_run_directory = matches.opt_str("test-run-directory").map(PathBuf::from);
806 let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
807 let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
808 let codegen_options_strs = matches.opt_strs("C");
809 let unstable_opts_strs = matches.opt_strs("Z");
810 let lib_strs = matches.opt_strs("L");
811 let extern_strs = matches.opt_strs("extern");
812 let test_runtool = matches.opt_str("test-runtool");
813 let test_runtool_args = matches.opt_strs("test-runtool-arg");
814 let document_private = matches.opt_present("document-private-items");
815 let document_hidden = matches.opt_present("document-hidden-items");
816 let run_check = matches.opt_present("check");
817 let generate_redirect_map = matches.opt_present("generate-redirect-map");
818 let show_type_layout = matches.opt_present("show-type-layout");
819 let no_capture = matches.opt_present("no-capture");
820 let generate_link_to_definition = matches.opt_present("generate-link-to-definition");
821 let generate_macro_expansion = matches.opt_present("generate-macro-expansion");
822 let extern_html_root_takes_precedence =
823 matches.opt_present("extern-html-root-takes-precedence");
824 let html_no_source = matches.opt_present("html-no-source");
825 let should_merge = match parse_merge(matches) {
826 Ok(result) => result,
827 Err(e) => dcx.fatal(format!("--merge option error: {e}")),
828 };
829 let merge_doctests = parse_merge_doctests(matches, edition, dcx);
830 tracing::debug!("merge_doctests: {merge_doctests:?}");
831
832 if generate_link_to_definition && (show_coverage || output_format != OutputFormat::Html) {
833 dcx.struct_warn(
834 "`--generate-link-to-definition` option can only be used with HTML output format",
835 )
836 .with_note("`--generate-link-to-definition` option will be ignored")
837 .emit();
838 }
839 if generate_macro_expansion && (show_coverage || output_format != OutputFormat::Html) {
840 dcx.struct_warn(
841 "`--generate-macro-expansion` option can only be used with HTML output format",
842 )
843 .with_note("`--generate-macro-expansion` option will be ignored")
844 .emit();
845 }
846
847 let scrape_examples_options = ScrapeExamplesOptions::new(matches, dcx);
848 let with_examples = matches.opt_strs("with-examples");
849 let call_locations =
850 crate::scrape_examples::load_call_locations(with_examples, dcx, &mut loaded_paths);
851 let doctest_build_args = matches.opt_strs("doctest-build-arg");
852
853 let disable_minification = matches.opt_present("disable-minification");
854
855 let options = Options {
856 bin_crate,
857 proc_macro_crate,
858 error_format,
859 diagnostic_width,
860 libs,
861 lib_strs,
862 externs,
863 extern_strs,
864 cfgs,
865 check_cfgs,
866 codegen_options,
867 codegen_options_strs,
868 unstable_opts,
869 unstable_opts_strs,
870 target,
871 edition,
872 sysroot,
873 lint_opts,
874 describe_lints,
875 lint_cap,
876 should_test,
877 test_args,
878 show_coverage,
879 crate_version,
880 test_run_directory,
881 persist_doctests,
882 merge_doctests,
883 test_runtool,
884 test_runtool_args,
885 test_builder,
886 run_check,
887 no_run,
888 test_builder_wrappers,
889 remap_path_prefix,
890 no_capture,
891 crate_name,
892 output_format,
893 json_unused_externs,
894 scrape_examples_options,
895 unstable_features,
896 doctest_build_args,
897 target_modifiers,
898 };
899 let render_options = RenderOptions {
900 output,
901 external_html,
902 id_map,
903 playground_url,
904 module_sorting,
905 themes,
906 extension_css,
907 extern_html_root_urls,
908 extern_html_root_takes_precedence,
909 default_settings,
910 resource_suffix,
911 enable_index_page,
912 index_page,
913 static_root_path,
914 markdown_no_toc,
915 markdown_css,
916 markdown_playground_url,
917 document_private,
918 document_hidden,
919 generate_redirect_map,
920 show_type_layout,
921 unstable_features,
922 emit,
923 generate_link_to_definition,
924 generate_macro_expansion,
925 call_locations,
926 no_emit_shared: false,
927 html_no_source,
928 output_to_stdout,
929 should_merge,
930 include_parts_dir,
931 parts_out_dir,
932 disable_minification,
933 };
934 Some((input, options, render_options, loaded_paths))
935 }
936}
937
938pub(crate) fn markdown_input(input: &Input) -> Option<&Path> {
940 input.opt_path().filter(|p| matches!(p.extension(), Some(e) if e == "md" || e == "markdown"))
941}
942
943fn parse_remap_path_prefix(
944 matches: &getopts::Matches,
945) -> Result<Vec<(PathBuf, PathBuf)>, &'static str> {
946 matches
947 .opt_strs("remap-path-prefix")
948 .into_iter()
949 .map(|remap| {
950 remap
951 .rsplit_once('=')
952 .ok_or("--remap-path-prefix must contain '=' between FROM and TO")
953 .map(|(from, to)| (PathBuf::from(from), PathBuf::from(to)))
954 })
955 .collect()
956}
957
958fn check_deprecated_options(matches: &getopts::Matches, dcx: DiagCtxtHandle<'_>) {
960 let deprecated_flags = [];
961
962 for &flag in deprecated_flags.iter() {
963 if matches.opt_present(flag) {
964 dcx.struct_warn(format!("the `{flag}` flag is deprecated"))
965 .with_note(
966 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
967 for more information",
968 )
969 .emit();
970 }
971 }
972
973 let removed_flags = ["plugins", "plugin-path", "no-defaults", "passes", "input-format"];
974
975 for &flag in removed_flags.iter() {
976 if matches.opt_present(flag) {
977 let mut err = dcx.struct_warn(format!("the `{flag}` flag no longer functions"));
978 err.note(
979 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
980 for more information",
981 );
982
983 if flag == "no-defaults" || flag == "passes" {
984 err.help("you may want to use --document-private-items");
985 } else if flag == "plugins" || flag == "plugin-path" {
986 err.warn("see CVE-2018-1000622");
987 }
988
989 err.emit();
990 }
991 }
992}
993
994fn parse_extern_html_roots(
998 matches: &getopts::Matches,
999) -> Result<BTreeMap<String, String>, &'static str> {
1000 let mut externs = BTreeMap::new();
1001 for arg in &matches.opt_strs("extern-html-root-url") {
1002 let (name, url) =
1003 arg.split_once('=').ok_or("--extern-html-root-url must be of the form name=url")?;
1004 externs.insert(name.to_string(), url.to_string());
1005 }
1006 Ok(externs)
1007}
1008
1009#[derive(Clone, Debug)]
1014pub(crate) struct PathToParts(pub(crate) PathBuf);
1015
1016impl PathToParts {
1017 fn from_flag(path: String) -> Result<PathToParts, String> {
1018 let path = PathBuf::from(path);
1019 if path.exists() && !path.is_dir() {
1021 Err(format!(
1022 "--parts-out-dir and --include-parts-dir expect directories, found: {}",
1023 path.display(),
1024 ))
1025 } else {
1026 Ok(PathToParts(path))
1028 }
1029 }
1030}
1031
1032fn parse_include_parts_dir(m: &getopts::Matches) -> Result<Vec<PathToParts>, String> {
1034 let mut ret = Vec::new();
1035 for p in m.opt_strs("include-parts-dir") {
1036 let p = PathToParts::from_flag(p)?;
1037 if !p.0.is_dir() {
1039 return Err(format!(
1040 "--include-parts-dir expected {} to be a directory",
1041 p.0.display()
1042 ));
1043 }
1044 ret.push(p);
1045 }
1046 Ok(ret)
1047}
1048
1049#[derive(Debug, Clone)]
1051pub(crate) struct ShouldMerge {
1052 pub(crate) read_rendered_cci: bool,
1054 pub(crate) write_rendered_cci: bool,
1056}
1057
1058fn parse_merge(m: &getopts::Matches) -> Result<ShouldMerge, &'static str> {
1061 match m.opt_str("merge").as_deref() {
1062 None => Ok(ShouldMerge { read_rendered_cci: true, write_rendered_cci: true }),
1064 Some("none") if m.opt_present("include-parts-dir") => {
1065 Err("--include-parts-dir not allowed if --merge=none")
1066 }
1067 Some("none") => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: false }),
1068 Some("shared") if m.opt_present("parts-out-dir") || m.opt_present("include-parts-dir") => {
1069 Err("--parts-out-dir and --include-parts-dir not allowed if --merge=shared")
1070 }
1071 Some("shared") => Ok(ShouldMerge { read_rendered_cci: true, write_rendered_cci: true }),
1072 Some("finalize") if m.opt_present("parts-out-dir") => {
1073 Err("--parts-out-dir not allowed if --merge=finalize")
1074 }
1075 Some("finalize") => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: true }),
1076 Some(_) => Err("argument to --merge must be `none`, `shared`, or `finalize`"),
1077 }
1078}
1079
1080fn parse_merge_doctests(
1081 m: &getopts::Matches,
1082 edition: Edition,
1083 dcx: DiagCtxtHandle<'_>,
1084) -> MergeDoctests {
1085 match m.opt_str("merge-doctests").as_deref() {
1086 Some("y") | Some("yes") | Some("on") | Some("true") => MergeDoctests::Always,
1087 Some("n") | Some("no") | Some("off") | Some("false") => MergeDoctests::Never,
1088 Some("auto") => MergeDoctests::Auto,
1089 None if edition < Edition::Edition2024 => MergeDoctests::Never,
1090 None => MergeDoctests::Auto,
1091 Some(_) => {
1092 dcx.fatal("argument to --merge-doctests must be a boolean (true/false) or 'auto'")
1093 }
1094 }
1095}