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