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;
21use smallvec::SmallVec;
22
23use crate::core::new_dcx;
24use crate::externalfiles::ExternalHtml;
25use crate::html::markdown::IdMap;
26use crate::html::render::StylePath;
27use crate::html::static_files;
28use crate::passes::{self, Condition};
29use crate::scrape_examples::{AllCallLocations, ScrapeExamplesOptions};
30use crate::{html, opts, theme};
31
32#[derive(Clone, Copy, PartialEq, Eq, Debug)]
33pub(crate) enum OutputFormat {
34 IrJson,
38 CoverageJson,
40 Html,
41 Doctest,
42}
43
44pub(crate) enum InputMode {
46 NoInputMergeFinalize,
48 HasFile(Input),
50}
51
52#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
54pub(crate) enum MergeDoctests {
55 #[default]
56 Never,
57 Always,
58 Auto,
59}
60
61#[derive(Clone)]
63pub(crate) struct Options {
64 pub(crate) crate_name: Option<String>,
67 pub(crate) bin_crate: bool,
69 pub(crate) proc_macro_crate: bool,
71 pub(crate) error_format: ErrorOutputType,
73 pub(crate) diagnostic_width: Option<usize>,
75 pub(crate) libs: Vec<SearchPath>,
77 pub(crate) lib_strs: Vec<String>,
79 pub(crate) externs: Externs,
81 pub(crate) extern_strs: Vec<String>,
83 pub(crate) cfgs: Vec<String>,
85 pub(crate) check_cfgs: Vec<String>,
87 pub(crate) codegen_options: CodegenOptions,
89 pub(crate) codegen_options_strs: Vec<String>,
91 pub(crate) unstable_opts: UnstableOptions,
93 pub(crate) unstable_opts_strs: Vec<String>,
95 pub(crate) target: TargetTuple,
97 pub(crate) edition: Edition,
100 pub(crate) sysroot: Sysroot,
102 pub(crate) lint_opts: Vec<(String, Level)>,
104 pub(crate) describe_lints: bool,
106 pub(crate) lint_cap: Option<Level>,
108
109 pub(crate) should_test: bool,
112 pub(crate) test_args: Vec<String>,
114 pub(crate) test_run_directory: Option<PathBuf>,
116 pub(crate) persist_doctests: Option<PathBuf>,
119 pub(crate) merge_doctests: MergeDoctests,
121 pub(crate) test_runtool: Option<String>,
123 pub(crate) test_runtool_args: Vec<String>,
125 pub(crate) no_run: bool,
127 pub(crate) remap_path_prefix: Vec<(PathBuf, PathBuf)>,
129 pub(crate) remap_path_scope: RemapPathScopeComponents,
131
132 pub(crate) test_builder: Option<PathBuf>,
135
136 pub(crate) test_builder_wrappers: Vec<PathBuf>,
138
139 pub(crate) show_coverage: bool,
143
144 pub(crate) crate_version: Option<String>,
147 pub(crate) output_format: OutputFormat,
151 pub(crate) run_check: bool,
154 pub(crate) json_unused_externs: JsonUnusedExterns,
156 pub(crate) no_capture: bool,
158
159 pub(crate) scrape_examples_options: Option<ScrapeExamplesOptions>,
162
163 pub(crate) unstable_features: rustc_feature::UnstableFeatures,
166
167 pub(crate) doctest_build_args: Vec<String>,
169
170 pub(crate) target_modifiers: BTreeMap<OptionsTargetModifiers, String>,
172}
173
174impl fmt::Debug for Options {
175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176 struct FmtExterns<'a>(&'a Externs);
177
178 impl fmt::Debug for FmtExterns<'_> {
179 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180 f.debug_map().entries(self.0.iter()).finish()
181 }
182 }
183
184 f.debug_struct("Options")
185 .field("crate_name", &self.crate_name)
186 .field("bin_crate", &self.bin_crate)
187 .field("proc_macro_crate", &self.proc_macro_crate)
188 .field("error_format", &self.error_format)
189 .field("libs", &self.libs)
190 .field("externs", &FmtExterns(&self.externs))
191 .field("cfgs", &self.cfgs)
192 .field("check-cfgs", &self.check_cfgs)
193 .field("codegen_options", &"...")
194 .field("unstable_options", &"...")
195 .field("target", &self.target)
196 .field("edition", &self.edition)
197 .field("sysroot", &self.sysroot)
198 .field("lint_opts", &self.lint_opts)
199 .field("describe_lints", &self.describe_lints)
200 .field("lint_cap", &self.lint_cap)
201 .field("should_test", &self.should_test)
202 .field("test_args", &self.test_args)
203 .field("test_run_directory", &self.test_run_directory)
204 .field("persist_doctests", &self.persist_doctests)
205 .field("show_coverage", &self.show_coverage)
206 .field("crate_version", &self.crate_version)
207 .field("test_runtool", &self.test_runtool)
208 .field("test_runtool_args", &self.test_runtool_args)
209 .field("run_check", &self.run_check)
210 .field("no_run", &self.no_run)
211 .field("test_builder_wrappers", &self.test_builder_wrappers)
212 .field("remap-file-prefix", &self.remap_path_prefix)
213 .field("remap-file-scope", &self.remap_path_scope)
214 .field("no_capture", &self.no_capture)
215 .field("scrape_examples_options", &self.scrape_examples_options)
216 .field("unstable_features", &self.unstable_features)
217 .finish()
218 }
219}
220
221#[derive(Clone, Debug)]
223pub(crate) struct RenderOptions {
224 pub(crate) output: PathBuf,
226 pub(crate) external_html: ExternalHtml,
228 pub(crate) id_map: IdMap,
231 pub(crate) playground_url: Option<String>,
235 pub(crate) module_sorting: ModuleSorting,
238 pub(crate) themes: Vec<StylePath>,
241 pub(crate) extension_css: Option<PathBuf>,
243 pub(crate) extern_html_root_urls: BTreeMap<String, String>,
245 pub(crate) extern_html_root_takes_precedence: bool,
247 pub(crate) default_settings: FxIndexMap<String, String>,
250 pub(crate) resource_suffix: String,
252 pub(crate) enable_index_page: bool,
255 pub(crate) index_page: Option<PathBuf>,
258 pub(crate) static_root_path: Option<String>,
261
262 pub(crate) markdown_no_toc: bool,
266 pub(crate) markdown_css: Vec<String>,
268 pub(crate) markdown_playground_url: Option<String>,
271 pub(crate) document_private: bool,
273 pub(crate) document_hidden: bool,
275 pub(crate) generate_redirect_map: bool,
277 pub(crate) show_type_layout: bool,
279 pub(crate) unstable_features: rustc_feature::UnstableFeatures,
282 pub(crate) emit: SmallVec<[EmitType; 2]>,
283 pub(crate) generate_link_to_definition: bool,
285 pub(crate) call_locations: AllCallLocations,
287 pub(crate) no_emit_shared: bool,
289 pub(crate) html_no_source: bool,
291 pub(crate) output_to_stdout: bool,
294 pub(crate) should_merge: ShouldMerge,
296 pub(crate) include_parts_dir: Vec<PathToParts>,
298 pub(crate) parts_out_dir: Option<PathToParts>,
300 pub(crate) disable_minification: bool,
302 pub(crate) generate_macro_expansion: bool,
304}
305
306#[derive(Copy, Clone, Debug, PartialEq, Eq)]
307pub(crate) enum ModuleSorting {
308 DeclarationOrder,
309 Alphabetical,
310}
311
312#[derive(Clone, Debug, PartialEq, Eq)]
313pub(crate) enum EmitType {
314 HtmlStaticFiles,
315 HtmlNonStaticFiles,
316 IrJsonFiles,
318 CoverageJsonFiles,
319 DepInfo(Option<OutFileName>),
320}
321
322impl fmt::Display for EmitType {
323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
324 f.write_str(match self {
325 Self::HtmlStaticFiles => "html-static-files",
326 Self::HtmlNonStaticFiles => "html-non-static-files",
327 Self::IrJsonFiles => "ir-json-files",
328 Self::CoverageJsonFiles => "coverage-json-files",
329 Self::DepInfo(_) => "dep-info",
330 })
331 }
332}
333
334impl FromStr for EmitType {
335 type Err = ();
336
337 fn from_str(s: &str) -> Result<Self, Self::Err> {
338 match s {
339 "toolchain-shared-resources" => Ok(Self::HtmlStaticFiles),
341 "invocation-specific" => Ok(Self::HtmlNonStaticFiles),
342 "html-static-files" => Ok(Self::HtmlStaticFiles),
344 "html-non-static-files" => Ok(Self::HtmlNonStaticFiles),
345 "dep-info" => Ok(Self::DepInfo(None)),
346 option => match option.strip_prefix("dep-info=") {
347 Some("-") => Ok(Self::DepInfo(Some(OutFileName::Stdout))),
348 Some(f) => Ok(Self::DepInfo(Some(OutFileName::Real(f.into())))),
349 None => Err(()),
350 },
351 }
352 }
353}
354
355impl RenderOptions {
356 pub(crate) fn dep_info(&self) -> Option<Option<&OutFileName>> {
357 self.emit.iter().find_map(|emit| match emit {
358 EmitType::DepInfo(file) => Some(file.as_ref()),
359 _ => None,
360 })
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, Vec<PathBuf>)> {
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 crate_name = matches.opt_str("crate-name");
406 let unstable_features =
407 rustc_feature::UnstableFeatures::from_environment(crate_name.as_deref());
408 let config::JsonConfig { json_rendered, json_unused_externs, json_color, .. } =
409 config::parse_json(early_dcx, matches);
410 let error_format =
411 config::parse_error_format(early_dcx, matches, color, json_color, json_rendered);
412 let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_default();
413
414 let mut collected_options = Default::default();
415 let codegen_options = CodegenOptions::build(early_dcx, matches, &mut collected_options);
416 let unstable_opts = UnstableOptions::build(early_dcx, matches, &mut collected_options);
417
418 let remap_path_prefix = match parse_remap_path_prefix(matches) {
419 Ok(prefix_mappings) => prefix_mappings,
420 Err(err) => {
421 early_dcx.early_fatal(err);
422 }
423 };
424 let remap_path_scope =
425 rustc_session::config::parse_remap_path_scope(early_dcx, matches, &unstable_opts);
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 show_coverage = matches.opt_present("show-coverage");
468 let output_format_s = matches.opt_str("output-format");
469 let output_format = match output_format_s.as_deref() {
470 None | Some("html") => OutputFormat::Html,
471 Some("json") => {
472 if show_coverage {
473 OutputFormat::CoverageJson
474 } else {
475 OutputFormat::IrJson
476 }
477 }
478 Some("doctest") => OutputFormat::Doctest,
479 Some(other) => dcx.fatal(format!("unknown output format `{other}`")),
480 };
481
482 match (
484 output_format_s.as_ref().map(|_| output_format),
485 show_coverage,
486 nightly_options::is_unstable_enabled(matches),
487 ) {
488 (None | Some(OutputFormat::CoverageJson), true, _) => {}
489 (_, true, _) => {
490 dcx.fatal(format!(
491 "`--output-format={}` is not supported for the `--show-coverage` option",
492 output_format_s.expect("checked for none above"),
493 ));
494 }
495 (_, false, true) => {}
497 (None | Some(OutputFormat::Html), false, _) => {}
498 (Some(OutputFormat::IrJson), false, false) => {
499 dcx.fatal(
500 "the -Z unstable-options flag must be passed to enable --output-format=json for documentation generation (see https://github.com/rust-lang/rust/issues/76578)",
501 );
502 }
503 (Some(OutputFormat::Doctest), false, false) => {
504 dcx.fatal(
505 "the -Z unstable-options flag must be passed to enable --output-format=doctest (see https://github.com/rust-lang/rust/issues/134529)",
506 );
507 }
508 (Some(OutputFormat::CoverageJson), false, _) => {
509 unreachable!("CoverageJson is only possible when show_coverage is true")
510 }
511 }
512
513 let mut emit = FxIndexMap::default();
514 for list in matches.opt_strs("emit") {
515 if should_test {
516 dcx.fatal("the `--test` flag and the `--emit` flag are not supported together");
517 }
518 if let OutputFormat::Doctest = output_format {
519 dcx.fatal("the `--emit` flag is not supported with `--output-format=doctest`");
520 }
521
522 for typ in list.split(',') {
523 let Ok(typ) = typ.parse::<EmitType>() else {
524 dcx.fatal(format!("unrecognized emission type: {typ}"))
525 };
526
527 match typ {
528 EmitType::DepInfo(_) => match output_format {
529 OutputFormat::Html | OutputFormat::IrJson | OutputFormat::CoverageJson => {}
530 OutputFormat::Doctest => unreachable!(),
531 },
532 EmitType::HtmlStaticFiles | EmitType::HtmlNonStaticFiles => match output_format
533 {
534 OutputFormat::Html => {}
535 OutputFormat::IrJson | OutputFormat::CoverageJson => dcx.fatal(format!(
536 "the `--emit={typ}` flag is not supported with `--output-format=json`",
537 )),
538 OutputFormat::Doctest => unreachable!(),
539 },
540 EmitType::IrJsonFiles | EmitType::CoverageJsonFiles => unreachable!(),
541 }
542
543 emit.insert(std::mem::discriminant(&typ), typ);
548 }
549 }
550 let mut emit: SmallVec<[_; 2]> = emit.into_values().collect();
551 if emit.is_empty() {
555 match output_format {
556 OutputFormat::IrJson => emit.push(EmitType::IrJsonFiles),
557 OutputFormat::CoverageJson => emit.push(EmitType::CoverageJsonFiles),
558 OutputFormat::Html => {
559 emit.push(EmitType::HtmlStaticFiles);
560 emit.push(EmitType::HtmlNonStaticFiles);
561 }
562 OutputFormat::Doctest => {}
563 }
564 }
565
566 let to_check = matches.opt_strs("check-theme");
567 if !to_check.is_empty() {
568 let mut content =
569 std::str::from_utf8(static_files::STATIC_FILES.rustdoc_css.src_bytes).unwrap();
570 if let Some((_, inside)) = content.split_once("/* Begin theme: light */") {
571 content = inside;
572 }
573 if let Some((inside, _)) = content.split_once("/* End theme: light */") {
574 content = inside;
575 }
576 let paths = match theme::load_css_paths(content) {
577 Ok(p) => p,
578 Err(e) => dcx.fatal(e),
579 };
580 let mut errors = 0;
581
582 println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
583 for theme_file in to_check.iter() {
584 print!(" - Checking \"{theme_file}\"...");
585 let (success, differences) = theme::test_theme_against(theme_file, &paths, dcx);
586 if !differences.is_empty() || !success {
587 println!(" FAILED");
588 errors += 1;
589 if !differences.is_empty() {
590 println!("{}", differences.join("\n"));
591 }
592 } else {
593 println!(" OK");
594 }
595 }
596 if errors != 0 {
597 dcx.fatal("[check-theme] one or more tests failed");
598 }
599 return None;
600 }
601
602 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(early_dcx, matches);
603
604 let input = if describe_lints {
605 InputMode::HasFile(make_input(early_dcx, ""))
606 } else {
607 match matches.free.as_slice() {
608 [] if matches.opt_str("merge").as_deref() == Some("finalize") => {
609 InputMode::NoInputMergeFinalize
610 }
611 [] => dcx.fatal("missing file operand"),
612 [input] => InputMode::HasFile(make_input(early_dcx, input)),
613 _ => dcx.fatal("too many file operands"),
614 }
615 };
616
617 let externs = parse_externs(early_dcx, matches, &unstable_opts);
618 let extern_html_root_urls = match parse_extern_html_roots(matches) {
619 Ok(ex) => ex,
620 Err(err) => dcx.fatal(err),
621 };
622
623 let parts_out_dir =
624 match matches.opt_str("parts-out-dir").map(PathToParts::from_flag).transpose() {
625 Ok(parts_out_dir) => parts_out_dir,
626 Err(e) => dcx.fatal(e),
627 };
628 let include_parts_dir = match parse_include_parts_dir(matches) {
629 Ok(include_parts_dir) => include_parts_dir,
630 Err(e) => dcx.fatal(e),
631 };
632
633 let default_settings: Vec<Vec<(String, String)>> = vec![
634 matches
635 .opt_str("default-theme")
636 .iter()
637 .flat_map(|theme| {
638 vec![
639 ("use-system-theme".to_string(), "false".to_string()),
640 ("theme".to_string(), theme.to_string()),
641 ]
642 })
643 .collect(),
644 matches
645 .opt_strs("default-setting")
646 .iter()
647 .map(|s| match s.split_once('=') {
648 None => (s.clone(), "true".to_string()),
649 Some((k, v)) => (k.to_string(), v.to_string()),
650 })
651 .collect(),
652 ];
653 let default_settings = default_settings
654 .into_iter()
655 .flatten()
656 .map(
657 |(k, v)| (k.replace('-', "_"), v),
676 )
677 .collect();
678
679 let test_args = matches.opt_strs("test-args");
680 let test_args: Vec<String> =
681 test_args.iter().flat_map(|s| s.split_whitespace()).map(|s| s.to_string()).collect();
682
683 let no_run = matches.opt_present("no-run");
684
685 if !should_test && no_run {
686 dcx.fatal("the `--test` flag must be passed to enable `--no-run`");
687 }
688
689 let mut output_to_stdout = false;
690 let test_builder_wrappers =
691 matches.opt_strs("test-builder-wrapper").iter().map(PathBuf::from).collect();
692 let output = match (matches.opt_str("out-dir"), matches.opt_str("output")) {
693 (Some(_), Some(_)) => {
694 dcx.fatal("cannot use both 'out-dir' and 'output' at once");
695 }
696 (Some(out_dir), None) | (None, Some(out_dir)) => {
697 output_to_stdout = out_dir == "-";
698 PathBuf::from(out_dir)
699 }
700 (None, None) => PathBuf::from("doc"),
701 };
702
703 let cfgs = matches.opt_strs("cfg");
704 let check_cfgs = matches.opt_strs("check-cfg");
705
706 let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
707
708 let mut loaded_paths = Vec::new();
709
710 if let Some(ref p) = extension_css {
711 loaded_paths.push(p.clone());
712 if !p.is_file() {
713 dcx.fatal("option --extend-css argument must be a file");
714 }
715 }
716
717 let mut themes = Vec::new();
718 if matches.opt_present("theme") {
719 let mut content =
720 std::str::from_utf8(static_files::STATIC_FILES.rustdoc_css.src_bytes).unwrap();
721 if let Some((_, inside)) = content.split_once("/* Begin theme: light */") {
722 content = inside;
723 }
724 if let Some((inside, _)) = content.split_once("/* End theme: light */") {
725 content = inside;
726 }
727 let paths = match theme::load_css_paths(content) {
728 Ok(p) => p,
729 Err(e) => dcx.fatal(e),
730 };
731
732 for (theme_file, theme_s) in
733 matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
734 {
735 if !theme_file.is_file() {
736 dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
737 .with_help("arguments to --theme must be files")
738 .emit();
739 }
740 if theme_file.extension() != Some(OsStr::new("css")) {
741 dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
742 .with_help("arguments to --theme must have a .css extension")
743 .emit();
744 }
745 let (success, ret) = theme::test_theme_against(&theme_file, &paths, dcx);
746 if !success {
747 dcx.fatal(format!("error loading theme file: \"{theme_s}\""));
748 } else if !ret.is_empty() {
749 dcx.struct_warn(format!(
750 "theme file \"{theme_s}\" is missing CSS rules from the default theme",
751 ))
752 .with_warn("the theme may appear incorrect when loaded")
753 .with_help(format!(
754 "to see what rules are missing, call `rustdoc --check-theme \"{theme_s}\"`",
755 ))
756 .emit();
757 }
758 loaded_paths.push(theme_file.clone());
759 themes.push(StylePath { path: theme_file });
760 }
761 }
762
763 let edition = config::parse_crate_edition(early_dcx, matches);
764
765 let mut id_map = html::markdown::IdMap::new();
766 let Some(external_html) = ExternalHtml::load(
767 &matches.opt_strs("html-in-header"),
768 &matches.opt_strs("html-before-content"),
769 &matches.opt_strs("html-after-content"),
770 &matches.opt_strs("markdown-before-content"),
771 &matches.opt_strs("markdown-after-content"),
772 nightly_options::match_is_nightly_build(matches),
773 dcx,
774 &mut id_map,
775 edition,
776 &None,
777 &mut loaded_paths,
778 ) else {
779 dcx.fatal("`ExternalHtml::load` failed");
780 };
781
782 match matches.opt_str("r").as_deref() {
783 Some("rust") | None => {}
784 Some(s) => dcx.fatal(format!("unknown input format: {s}")),
785 }
786
787 let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
788 if let Some(ref index_page) = index_page {
789 if index_page.is_file() {
790 loaded_paths.push(index_page.clone());
791 } else {
792 dcx.fatal("option `--index-page` argument must be a file");
793 }
794 }
795
796 let target = parse_target_triple(early_dcx, matches);
797 let sysroot = Sysroot::new(matches.opt_str("sysroot").map(PathBuf::from));
798
799 let libs = matches
800 .opt_strs("L")
801 .iter()
802 .map(|s| {
803 SearchPath::from_cli_opt(
804 sysroot.path(),
805 &target,
806 early_dcx,
807 s,
808 #[allow(rustc::bad_opt_access)] unstable_opts.unstable_options,
810 )
811 })
812 .collect();
813
814 let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
815 Ok(types) => types,
816 Err(e) => {
817 dcx.fatal(format!("unknown crate type: {e}"));
818 }
819 };
820
821 let bin_crate = crate_types.contains(&CrateType::Executable);
822 let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
823 let playground_url = matches.opt_str("playground-url");
824 let module_sorting = if matches.opt_present("sort-modules-by-appearance") {
825 ModuleSorting::DeclarationOrder
826 } else {
827 ModuleSorting::Alphabetical
828 };
829 let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
830 let markdown_no_toc = matches.opt_present("markdown-no-toc");
831 let markdown_css = matches.opt_strs("markdown-css");
832 let markdown_playground_url = matches.opt_str("markdown-playground-url");
833 let crate_version = matches.opt_str("crate-version");
834 let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
835 let static_root_path = matches.opt_str("static-root-path");
836 let test_run_directory = matches.opt_str("test-run-directory").map(PathBuf::from);
837 let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
838 let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
839 let codegen_options_strs = matches.opt_strs("C");
840 let unstable_opts_strs = matches.opt_strs("Z");
841 let lib_strs = matches.opt_strs("L");
842 let extern_strs = matches.opt_strs("extern");
843 let test_runtool = matches.opt_str("test-runtool");
844 let test_runtool_args = matches.opt_strs("test-runtool-arg");
845 let document_private = matches.opt_present("document-private-items");
846 let document_hidden = matches.opt_present("document-hidden-items");
847 let run_check = matches.opt_present("check");
848 let generate_redirect_map = matches.opt_present("generate-redirect-map");
849 let show_type_layout = matches.opt_present("show-type-layout");
850 let no_capture = matches.opt_present("no-capture");
851 let generate_link_to_definition = matches.opt_present("generate-link-to-definition");
852 let generate_macro_expansion = matches.opt_present("generate-macro-expansion");
853 let extern_html_root_takes_precedence =
854 matches.opt_present("extern-html-root-takes-precedence");
855 let html_no_source = matches.opt_present("html-no-source");
856 let should_merge = match parse_merge(matches) {
857 Ok(result) => result,
858 Err(e) => dcx.fatal(format!("--merge option error: {e}")),
859 };
860 let merge_doctests = parse_merge_doctests(matches, edition, dcx);
861 tracing::debug!("merge_doctests: {merge_doctests:?}");
862
863 if generate_link_to_definition && (show_coverage || output_format != OutputFormat::Html) {
864 dcx.struct_warn(
865 "`--generate-link-to-definition` option can only be used with HTML output format",
866 )
867 .with_note("`--generate-link-to-definition` option will be ignored")
868 .emit();
869 }
870 if generate_macro_expansion && (show_coverage || output_format != OutputFormat::Html) {
871 dcx.struct_warn(
872 "`--generate-macro-expansion` option can only be used with HTML output format",
873 )
874 .with_note("`--generate-macro-expansion` option will be ignored")
875 .emit();
876 }
877
878 let scrape_examples_options = ScrapeExamplesOptions::new(matches, dcx);
879 let with_examples = matches.opt_strs("with-examples");
880 let call_locations =
881 crate::scrape_examples::load_call_locations(with_examples, dcx, &mut loaded_paths);
882 let doctest_build_args = matches.opt_strs("doctest-build-arg");
883
884 let disable_minification = matches.opt_present("disable-minification");
885
886 let options = Options {
887 bin_crate,
888 proc_macro_crate,
889 error_format,
890 diagnostic_width,
891 libs,
892 lib_strs,
893 externs,
894 extern_strs,
895 cfgs,
896 check_cfgs,
897 codegen_options,
898 codegen_options_strs,
899 unstable_opts,
900 unstable_opts_strs,
901 target,
902 edition,
903 sysroot,
904 lint_opts,
905 describe_lints,
906 lint_cap,
907 should_test,
908 test_args,
909 show_coverage,
910 crate_version,
911 test_run_directory,
912 persist_doctests,
913 merge_doctests,
914 test_runtool,
915 test_runtool_args,
916 test_builder,
917 run_check,
918 no_run,
919 test_builder_wrappers,
920 remap_path_prefix,
921 remap_path_scope,
922 no_capture,
923 crate_name,
924 output_format,
925 json_unused_externs,
926 scrape_examples_options,
927 unstable_features,
928 doctest_build_args,
929 target_modifiers: collected_options.target_modifiers,
930 };
931 let render_options = RenderOptions {
932 output,
933 external_html,
934 id_map,
935 playground_url,
936 module_sorting,
937 themes,
938 extension_css,
939 extern_html_root_urls,
940 extern_html_root_takes_precedence,
941 default_settings,
942 resource_suffix,
943 enable_index_page,
944 index_page,
945 static_root_path,
946 markdown_no_toc,
947 markdown_css,
948 markdown_playground_url,
949 document_private,
950 document_hidden,
951 generate_redirect_map,
952 show_type_layout,
953 unstable_features,
954 emit,
955 generate_link_to_definition,
956 generate_macro_expansion,
957 call_locations,
958 no_emit_shared: false,
959 html_no_source,
960 output_to_stdout,
961 should_merge,
962 include_parts_dir,
963 parts_out_dir,
964 disable_minification,
965 };
966 Some((input, options, render_options, loaded_paths))
967 }
968}
969
970pub(crate) fn markdown_input(input: &Input) -> Option<&Path> {
972 input.opt_path().filter(|p| matches!(p.extension(), Some(e) if e == "md" || e == "markdown"))
973}
974
975fn parse_remap_path_prefix(
976 matches: &getopts::Matches,
977) -> Result<Vec<(PathBuf, PathBuf)>, &'static str> {
978 matches
979 .opt_strs("remap-path-prefix")
980 .into_iter()
981 .map(|remap| {
982 remap
983 .rsplit_once('=')
984 .ok_or("--remap-path-prefix must contain '=' between FROM and TO")
985 .map(|(from, to)| (PathBuf::from(from), PathBuf::from(to)))
986 })
987 .collect()
988}
989
990fn check_deprecated_options(matches: &getopts::Matches, dcx: DiagCtxtHandle<'_>) {
992 let deprecated_flags = [];
993
994 for &flag in deprecated_flags.iter() {
995 if matches.opt_present(flag) {
996 dcx.struct_warn(format!("the `{flag}` flag is deprecated"))
997 .with_note(
998 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
999 for more information",
1000 )
1001 .emit();
1002 }
1003 }
1004
1005 let removed_flags = ["plugins", "plugin-path", "no-defaults", "passes", "input-format"];
1006
1007 for &flag in removed_flags.iter() {
1008 if matches.opt_present(flag) {
1009 let mut err = dcx.struct_warn(format!("the `{flag}` flag no longer functions"));
1010 err.note(
1011 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
1012 for more information",
1013 );
1014
1015 if flag == "no-defaults" || flag == "passes" {
1016 err.help("you may want to use --document-private-items");
1017 } else if flag == "plugins" || flag == "plugin-path" {
1018 err.warn("see CVE-2018-1000622");
1019 }
1020
1021 err.emit();
1022 }
1023 }
1024}
1025
1026fn parse_extern_html_roots(
1030 matches: &getopts::Matches,
1031) -> Result<BTreeMap<String, String>, &'static str> {
1032 let mut externs = BTreeMap::new();
1033 for arg in &matches.opt_strs("extern-html-root-url") {
1034 let (name, url) =
1035 arg.split_once('=').ok_or("--extern-html-root-url must be of the form name=url")?;
1036 externs.insert(name.to_string(), url.to_string());
1037 }
1038 Ok(externs)
1039}
1040
1041#[derive(Clone, Debug)]
1046pub(crate) struct PathToParts(pub(crate) PathBuf);
1047
1048impl PathToParts {
1049 fn from_flag(path: String) -> Result<PathToParts, String> {
1050 let path = PathBuf::from(path);
1051 if path.exists() && !path.is_dir() {
1053 Err(format!(
1054 "--parts-out-dir and --include-parts-dir expect directories, found: {}",
1055 path.display(),
1056 ))
1057 } else {
1058 Ok(PathToParts(path))
1060 }
1061 }
1062}
1063
1064fn parse_include_parts_dir(m: &getopts::Matches) -> Result<Vec<PathToParts>, String> {
1066 let mut ret = Vec::new();
1067 for p in m.opt_strs("include-parts-dir") {
1068 let p = PathToParts::from_flag(p)?;
1069 if !p.0.is_dir() {
1071 return Err(format!(
1072 "--include-parts-dir expected {} to be a directory",
1073 p.0.display()
1074 ));
1075 }
1076 ret.push(p);
1077 }
1078 Ok(ret)
1079}
1080
1081#[derive(Debug, Clone)]
1083pub(crate) struct ShouldMerge {
1084 pub(crate) read_rendered_cci: bool,
1086 pub(crate) write_rendered_cci: bool,
1088}
1089
1090fn parse_merge(m: &getopts::Matches) -> Result<ShouldMerge, &'static str> {
1093 match m.opt_str("merge").as_deref() {
1094 None => Ok(ShouldMerge { read_rendered_cci: true, write_rendered_cci: true }),
1096 Some("none") if m.opt_present("include-parts-dir") => {
1097 Err("--include-parts-dir not allowed if --merge=none")
1098 }
1099 Some("none") => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: false }),
1100 Some("shared") if m.opt_present("parts-out-dir") || m.opt_present("include-parts-dir") => {
1101 Err("--parts-out-dir and --include-parts-dir not allowed if --merge=shared")
1102 }
1103 Some("shared") => Ok(ShouldMerge { read_rendered_cci: true, write_rendered_cci: true }),
1104 Some("finalize") if m.opt_present("parts-out-dir") => {
1105 Err("--parts-out-dir not allowed if --merge=finalize")
1106 }
1107 Some("finalize") => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: true }),
1108 Some(_) => Err("argument to --merge must be `none`, `shared`, or `finalize`"),
1109 }
1110}
1111
1112fn parse_merge_doctests(
1113 m: &getopts::Matches,
1114 edition: Edition,
1115 dcx: DiagCtxtHandle<'_>,
1116) -> MergeDoctests {
1117 match m.opt_str("merge-doctests").as_deref() {
1118 Some("y") | Some("yes") | Some("on") | Some("true") => MergeDoctests::Always,
1119 Some("n") | Some("no") | Some("off") | Some("false") => MergeDoctests::Never,
1120 Some("auto") => MergeDoctests::Auto,
1121 None if edition < Edition::Edition2024 => MergeDoctests::Never,
1122 None => MergeDoctests::Auto,
1123 Some(_) => {
1124 dcx.fatal("argument to --merge-doctests must be a boolean (true/false) or 'auto'")
1125 }
1126 }
1127}