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_lint::Level;
11use rustc_session::config::{
12 self, CodegenOptions, Externs, Input, JsonUnusedExterns, OptionsTargetModifiers, OutFileName,
13 PrintCategory, PrintRequest, Sysroot, UnstableOptions, collect_print_requests,
14 get_cmd_lint_options, nightly_options, parse_crate_types_from_list, parse_externs,
15 parse_target_triple,
16};
17use rustc_session::output::ErrorOutputType;
18use rustc_session::search_paths::SearchPath;
19use rustc_session::{EarlyDiagCtxt, getopts};
20use rustc_span::edition::Edition;
21use rustc_span::{FileName, RemapPathScopeComponents};
22use rustc_structures::CrateType;
23use rustc_target::spec::TargetTuple;
24use smallvec::SmallVec;
25
26use crate::core::new_dcx;
27use crate::externalfiles::ExternalHtml;
28use crate::html::markdown::IdMap;
29use crate::html::render::StylePath;
30use crate::html::static_files;
31use crate::scrape_examples::{AllCallLocations, ScrapeExamplesOptions};
32use crate::{html, opts, theme};
33
34#[derive(Clone, Copy, PartialEq, Eq, Debug)]
35pub(crate) enum OutputFormat {
36 IrJson,
40 CoverageJson,
42 Html,
43 Doctest,
44}
45
46pub(crate) enum InputMode {
48 NoInputMergeFinalize,
50 HasFile(Input),
52}
53
54#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
56pub(crate) enum MergeDoctests {
57 #[default]
58 Never,
59 Always,
60 Auto,
61}
62
63#[derive(Clone)]
65pub(crate) struct Options {
66 pub(crate) crate_name: Option<String>,
69 pub(crate) bin_crate: bool,
71 pub(crate) proc_macro_crate: bool,
73 pub(crate) error_format: ErrorOutputType,
75 pub(crate) diagnostic_width: Option<usize>,
77 pub(crate) libs: Vec<SearchPath>,
79 pub(crate) lib_strs: Vec<String>,
81 pub(crate) externs: Externs,
83 pub(crate) extern_strs: Vec<String>,
85 pub(crate) cfgs: Vec<String>,
87 pub(crate) check_cfgs: Vec<String>,
89 pub(crate) codegen_options: CodegenOptions,
91 pub(crate) codegen_options_strs: Vec<String>,
93 pub(crate) unstable_opts: UnstableOptions,
95 pub(crate) unstable_opts_strs: Vec<String>,
97 pub(crate) target: TargetTuple,
99 pub(crate) edition: Edition,
102 pub(crate) sysroot: Sysroot,
104 pub(crate) lint_opts: Vec<(String, Level)>,
106 pub(crate) describe_lints: bool,
108 pub(crate) lint_cap: Option<Level>,
110 pub(crate) prints: Vec<PrintRequest>,
112
113 pub(crate) should_test: bool,
116 pub(crate) test_args: Vec<String>,
118 pub(crate) test_run_directory: Option<PathBuf>,
120 pub(crate) persist_doctests: Option<PathBuf>,
123 pub(crate) merge_doctests: MergeDoctests,
125 pub(crate) test_runtool: Option<String>,
127 pub(crate) test_runtool_args: Vec<String>,
129 pub(crate) no_run: bool,
131 pub(crate) remap_path_prefix: Vec<(PathBuf, PathBuf)>,
133 pub(crate) remap_path_prefix_strs: Vec<String>,
134 pub(crate) remap_path_scope: RemapPathScopeComponents,
136 pub(crate) remap_path_scope_str: Option<String>,
137
138 pub(crate) test_builder: Option<PathBuf>,
141
142 pub(crate) test_builder_wrappers: Vec<PathBuf>,
144
145 pub(crate) show_coverage: bool,
149
150 pub(crate) crate_version: Option<String>,
153 pub(crate) output_format: OutputFormat,
157 pub(crate) run_check: bool,
160 pub(crate) json_unused_externs: JsonUnusedExterns,
162 pub(crate) no_capture: bool,
164
165 pub(crate) scrape_examples_options: Option<ScrapeExamplesOptions>,
168
169 pub(crate) unstable_features: rustc_feature::UnstableFeatures,
172
173 pub(crate) doctest_build_args: Vec<String>,
175
176 pub(crate) target_modifiers: BTreeMap<OptionsTargetModifiers, String>,
178}
179
180impl fmt::Debug for Options {
181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182 struct FmtExterns<'a>(&'a Externs);
183
184 impl fmt::Debug for FmtExterns<'_> {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 f.debug_map().entries(self.0.iter()).finish()
187 }
188 }
189
190 f.debug_struct("Options")
191 .field("crate_name", &self.crate_name)
192 .field("bin_crate", &self.bin_crate)
193 .field("proc_macro_crate", &self.proc_macro_crate)
194 .field("error_format", &self.error_format)
195 .field("libs", &self.libs)
196 .field("externs", &FmtExterns(&self.externs))
197 .field("cfgs", &self.cfgs)
198 .field("check-cfgs", &self.check_cfgs)
199 .field("codegen_options", &"...")
200 .field("unstable_options", &"...")
201 .field("target", &self.target)
202 .field("edition", &self.edition)
203 .field("sysroot", &self.sysroot)
204 .field("lint_opts", &self.lint_opts)
205 .field("describe_lints", &self.describe_lints)
206 .field("lint_cap", &self.lint_cap)
207 .field("prints", &self.prints)
208 .field("should_test", &self.should_test)
209 .field("test_args", &self.test_args)
210 .field("test_run_directory", &self.test_run_directory)
211 .field("persist_doctests", &self.persist_doctests)
212 .field("show_coverage", &self.show_coverage)
213 .field("crate_version", &self.crate_version)
214 .field("test_runtool", &self.test_runtool)
215 .field("test_runtool_args", &self.test_runtool_args)
216 .field("run_check", &self.run_check)
217 .field("no_run", &self.no_run)
218 .field("test_builder_wrappers", &self.test_builder_wrappers)
219 .field("remap-file-prefix", &self.remap_path_prefix)
220 .field("remap-file-scope", &self.remap_path_scope)
221 .field("no_capture", &self.no_capture)
222 .field("scrape_examples_options", &self.scrape_examples_options)
223 .field("unstable_features", &self.unstable_features)
224 .finish()
225 }
226}
227
228#[derive(Clone, Debug)]
230pub(crate) struct RenderOptions {
231 pub(crate) output: PathBuf,
233 pub(crate) external_html: ExternalHtml,
235 pub(crate) id_map: IdMap,
238 pub(crate) playground_url: Option<String>,
242 pub(crate) module_sorting: ModuleSorting,
245 pub(crate) crate_list_heading: String,
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: SmallVec<[EmitType; 2]>,
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 IrJsonFiles,
329 CoverageJsonFiles,
330 DepInfo(Option<OutFileName>),
331}
332
333impl fmt::Display for EmitType {
334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335 f.write_str(match self {
336 Self::HtmlStaticFiles => "html-static-files",
337 Self::HtmlNonStaticFiles => "html-non-static-files",
338 Self::IrJsonFiles => "ir-json-files",
339 Self::CoverageJsonFiles => "coverage-json-files",
340 Self::DepInfo(_) => "dep-info",
341 })
342 }
343}
344
345impl FromStr for EmitType {
346 type Err = ();
347
348 fn from_str(s: &str) -> Result<Self, Self::Err> {
349 match s {
350 "html-static-files" => Ok(Self::HtmlStaticFiles),
351 "html-non-static-files" => Ok(Self::HtmlNonStaticFiles),
352 "dep-info" => Ok(Self::DepInfo(None)),
353 option => match option.strip_prefix("dep-info=") {
354 Some("-") => Ok(Self::DepInfo(Some(OutFileName::Stdout))),
355 Some(f) => Ok(Self::DepInfo(Some(OutFileName::Real(f.into())))),
356 None => Err(()),
357 },
358 }
359 }
360}
361
362impl RenderOptions {
363 pub(crate) fn dep_info(&self) -> Option<Option<&OutFileName>> {
364 self.emit.iter().find_map(|emit| match emit {
365 EmitType::DepInfo(file) => Some(file.as_ref()),
366 _ => None,
367 })
368 }
369}
370
371fn make_input(early_dcx: &EarlyDiagCtxt, input: &str) -> Input {
375 if input == "-" {
376 let mut src = String::new();
377 if io::stdin().read_to_string(&mut src).is_err() {
378 early_dcx.early_fatal("couldn't read from stdin, as it did not contain valid UTF-8");
381 }
382 Input::Str { name: FileName::anon_source_code(&src), input: src }
383 } else {
384 Input::File(PathBuf::from(input))
385 }
386}
387
388impl Options {
389 pub(crate) fn from_matches(
392 early_dcx: &mut EarlyDiagCtxt,
393 matches: &getopts::Matches,
394 args: Vec<String>,
395 ) -> Option<(InputMode, Options, RenderOptions, Vec<PathBuf>)> {
396 nightly_options::check_nightly_options(early_dcx, matches, &opts());
398
399 if args.is_empty() || matches.opt_present("h") || matches.opt_present("help") {
400 crate::usage("rustdoc");
401 return None;
402 } else if matches.opt_present("version") {
403 rustc_driver::version!(&early_dcx, "rustdoc", matches);
404 return None;
405 }
406
407 if rustc_driver::describe_flag_categories(early_dcx, matches) {
408 return None;
409 }
410
411 let color = config::parse_color(early_dcx, matches);
412 let crate_name = matches.opt_str("crate-name");
413 let unstable_features =
414 rustc_feature::UnstableFeatures::from_environment(crate_name.as_deref());
415 let config::JsonConfig { json_rendered, json_unused_externs, json_color, .. } =
416 config::parse_json(early_dcx, matches);
417 let error_format =
418 config::parse_error_format(early_dcx, matches, color, json_color, json_rendered);
419 let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_default();
420
421 let mut collected_options = Default::default();
422 let mut codegen_options = CodegenOptions::build(early_dcx, matches, &mut collected_options);
423 let unstable_opts = UnstableOptions::build(early_dcx, matches, &mut collected_options);
424
425 let remap_path_prefix = match parse_remap_path_prefix(matches) {
426 Ok(prefix_mappings) => prefix_mappings,
427 Err(err) => {
428 early_dcx.early_fatal(err);
429 }
430 };
431 let remap_path_scope =
432 rustc_session::config::parse_remap_path_scope(early_dcx, matches, &unstable_opts);
433
434 let dcx = new_dcx(error_format, None, diagnostic_width, &unstable_opts);
435 let dcx = dcx.handle();
436
437 check_deprecated_options(matches, dcx);
439
440 let should_test = matches.opt_present("test");
441 let show_coverage = matches.opt_present("coverage");
442 let output_format_s = matches.opt_str("output-format");
443 let output_format = match output_format_s.as_deref() {
444 None | Some("html") => OutputFormat::Html,
445 Some("json") => {
446 if show_coverage {
447 OutputFormat::CoverageJson
448 } else {
449 OutputFormat::IrJson
450 }
451 }
452 Some("doctest") => OutputFormat::Doctest,
453 Some(other) => dcx.fatal(format!("unknown output format `{other}`")),
454 };
455
456 match (
458 output_format_s.as_ref().map(|_| output_format),
459 show_coverage,
460 nightly_options::unstable_options_enabled(matches),
461 ) {
462 (None | Some(OutputFormat::CoverageJson), true, _) => {}
463 (_, true, _) => {
464 dcx.fatal(format!(
465 "`--output-format={}` is not supported for the `--coverage` option",
466 output_format_s.expect("checked for none above"),
467 ));
468 }
469 (_, false, true) => {}
471 (None | Some(OutputFormat::Html), false, _) => {}
472 (Some(OutputFormat::IrJson), false, false) => {
473 dcx.fatal(
474 "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)",
475 );
476 }
477 (Some(OutputFormat::Doctest), false, false) => {
478 dcx.fatal(
479 "the -Z unstable-options flag must be passed to enable --output-format=doctest (see https://github.com/rust-lang/rust/issues/134529)",
480 );
481 }
482 (Some(OutputFormat::CoverageJson), false, _) => {
483 unreachable!("CoverageJson is only possible when show_coverage is true")
484 }
485 }
486
487 let mut emit = FxIndexMap::default();
488 for list in matches.opt_strs("emit") {
489 if should_test {
490 dcx.fatal("the `--test` flag and the `--emit` flag are not supported together");
491 }
492 if let OutputFormat::Doctest = output_format {
493 dcx.fatal("the `--emit` flag is not supported with `--output-format=doctest`");
494 }
495
496 for typ in list.split(',') {
497 let Ok(typ) = typ.parse::<EmitType>() else {
498 dcx.fatal(format!("unrecognized emission type: {typ}"))
499 };
500
501 match typ {
502 EmitType::DepInfo(_) => match output_format {
503 OutputFormat::Html | OutputFormat::IrJson | OutputFormat::CoverageJson => {}
504 OutputFormat::Doctest => unreachable!(),
505 },
506 EmitType::HtmlStaticFiles | EmitType::HtmlNonStaticFiles => match output_format
507 {
508 OutputFormat::Html => {}
509 OutputFormat::IrJson | OutputFormat::CoverageJson => dcx.fatal(format!(
510 "the `--emit={typ}` flag is not supported with `--output-format=json`",
511 )),
512 OutputFormat::Doctest => unreachable!(),
513 },
514 EmitType::IrJsonFiles | EmitType::CoverageJsonFiles => unreachable!(),
515 }
516
517 emit.insert(std::mem::discriminant(&typ), typ);
522 }
523 }
524 let mut emit: SmallVec<[_; 2]> = emit.into_values().collect();
525 if emit.is_empty() {
529 match output_format {
530 OutputFormat::IrJson => emit.push(EmitType::IrJsonFiles),
531 OutputFormat::CoverageJson => emit.push(EmitType::CoverageJsonFiles),
532 OutputFormat::Html => {
533 emit.push(EmitType::HtmlStaticFiles);
534 emit.push(EmitType::HtmlNonStaticFiles);
535 }
536 OutputFormat::Doctest => {}
537 }
538 }
539
540 let to_check = matches.opt_strs("check-theme");
541 if !to_check.is_empty() {
542 let mut content =
543 std::str::from_utf8(static_files::STATIC_FILES.rustdoc_css.src_bytes).unwrap();
544 if let Some((_, inside)) = content.split_once("/* Begin theme: light */") {
545 content = inside;
546 }
547 if let Some((inside, _)) = content.split_once("/* End theme: light */") {
548 content = inside;
549 }
550 let paths = match theme::load_css_paths(content) {
551 Ok(p) => p,
552 Err(e) => dcx.fatal(e),
553 };
554 let mut errors = 0;
555
556 println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
557 for theme_file in to_check.iter() {
558 print!(" - Checking \"{theme_file}\"...");
559 let (success, differences) = theme::test_theme_against(theme_file, &paths, dcx);
560 if !differences.is_empty() || !success {
561 println!(" FAILED");
562 errors += 1;
563 if !differences.is_empty() {
564 println!("{}", differences.join("\n"));
565 }
566 } else {
567 println!(" OK");
568 }
569 }
570 if errors != 0 {
571 dcx.fatal("[check-theme] one or more tests failed");
572 }
573 return None;
574 }
575
576 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(early_dcx, matches);
577
578 let externs = parse_externs(early_dcx, matches, &unstable_opts);
579 let extern_html_root_urls = match parse_extern_html_roots(matches) {
580 Ok(ex) => ex,
581 Err(err) => dcx.fatal(err),
582 };
583
584 let prints = collect_print_requests(
585 early_dcx,
586 &mut codegen_options,
587 &unstable_opts,
588 matches,
589 &[PrintCategory::Target, PrintCategory::Crate],
590 );
591
592 let mut parts_out_dir =
593 match matches.opt_str("write-doc-meta-dir").map(PathToParts::from_flag).transpose() {
594 Ok(parts_out_dir) => parts_out_dir,
595 Err(e) => dcx.fatal(e),
596 };
597 let mut include_parts_dir = match parse_read_doc_meta(matches, "read-doc-meta-dir") {
598 Ok(include_parts_dir) => include_parts_dir,
599 Err(e) => dcx.fatal(e),
600 };
601 let mut should_merge = match compute_should_merge(matches) {
602 Ok(should_merge) => should_merge,
603 Err(e) => dcx.fatal(e),
604 };
605 if parts_out_dir.is_none() && include_parts_dir.is_empty() {
606 parts_out_dir =
608 match matches.opt_str("parts-out-dir").map(PathToParts::from_flag).transpose() {
609 Ok(parts_out_dir) => parts_out_dir,
610 Err(e) => dcx.fatal(e),
611 };
612 include_parts_dir = match parse_read_doc_meta(matches, "include-parts-dir") {
613 Ok(include_parts_dir) => include_parts_dir,
614 Err(e) => dcx.fatal(e),
615 };
616 should_merge = match matches.opt_str("merge").as_deref() {
617 None => ShouldMerge { read_rendered_cci: true, write_rendered_cci: true },
618 Some("none") => ShouldMerge { read_rendered_cci: false, write_rendered_cci: false },
619 Some("shared") => ShouldMerge { read_rendered_cci: true, write_rendered_cci: true },
620 Some("finalize") => {
621 ShouldMerge { read_rendered_cci: false, write_rendered_cci: true }
622 }
623 Some(_) => dcx.fatal("argument to --merge must be `none`, `shared`, or `finalize`"),
624 };
625 } else if matches.opt_str("parts-out-dir").is_some() {
626 dcx.fatal(
627 "deprecated version of write-doc-meta-dir is used with new doc-meta-dir stuff",
628 );
629 } else if matches.opt_str("include-parts-dir").is_some() {
630 dcx.fatal(
631 "deprecated version of read-doc-meta-dir is used with new doc-meta-dir stuff",
632 );
633 } else if matches.opt_str("merge").is_some() {
634 dcx.fatal("deprecated parameter merge is used with new doc-meta-dir stuff");
635 }
636
637 let input = if describe_lints {
638 InputMode::HasFile(make_input(early_dcx, ""))
639 } else {
640 match matches.free.as_slice() {
641 [] if !include_parts_dir.is_empty() && should_merge.write_rendered_cci => {
642 InputMode::NoInputMergeFinalize
643 }
644 [] => dcx.fatal("missing file operand"),
645 [input] => InputMode::HasFile(make_input(early_dcx, input)),
646 _ => dcx.fatal("too many file operands"),
647 }
648 };
649
650 let default_settings: Vec<Vec<(String, String)>> = vec![
651 matches
652 .opt_str("default-theme")
653 .iter()
654 .flat_map(|theme| {
655 vec![
656 ("use-system-theme".to_string(), "false".to_string()),
657 ("theme".to_string(), theme.to_string()),
658 ]
659 })
660 .collect(),
661 matches
662 .opt_strs("default-setting")
663 .iter()
664 .map(|s| match s.split_once('=') {
665 None => (s.clone(), "true".to_string()),
666 Some((k, v)) => (k.to_string(), v.to_string()),
667 })
668 .collect(),
669 ];
670 let default_settings = default_settings
671 .into_iter()
672 .flatten()
673 .map(
674 |(k, v)| (k.replace('-', "_"), v),
693 )
694 .collect();
695
696 let test_args = matches.opt_strs("test-args");
697 let test_args: Vec<String> =
698 test_args.iter().flat_map(|s| s.split_whitespace()).map(|s| s.to_string()).collect();
699
700 let no_run = matches.opt_present("no-run");
701
702 if !should_test && no_run {
703 dcx.fatal("the `--test` flag must be passed to enable `--no-run`");
704 }
705
706 let mut output_to_stdout = false;
707 let test_builder_wrappers =
708 matches.opt_strs("test-builder-wrapper").iter().map(PathBuf::from).collect();
709 let output = match (matches.opt_str("out-dir"), matches.opt_str("output")) {
710 (Some(_), Some(_)) => {
711 dcx.fatal("cannot use both 'out-dir' and 'output' at once");
712 }
713 (Some(out_dir), None) | (None, Some(out_dir)) => {
714 output_to_stdout = out_dir == "-";
715 PathBuf::from(out_dir)
716 }
717 (None, None) => {
718 if show_coverage {
719 output_to_stdout = true;
722 }
723 PathBuf::from("doc")
724 }
725 };
726
727 let cfgs = matches.opt_strs("cfg");
728 let check_cfgs = matches.opt_strs("check-cfg");
729
730 let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
731
732 let mut loaded_paths = Vec::new();
733
734 if let Some(ref p) = extension_css {
735 loaded_paths.push(p.clone());
736 if !p.is_file() {
737 dcx.fatal("option --extend-css argument must be a file");
738 }
739 }
740
741 let mut themes = Vec::new();
742 if matches.opt_present("theme") {
743 let mut content =
744 std::str::from_utf8(static_files::STATIC_FILES.rustdoc_css.src_bytes).unwrap();
745 if let Some((_, inside)) = content.split_once("/* Begin theme: light */") {
746 content = inside;
747 }
748 if let Some((inside, _)) = content.split_once("/* End theme: light */") {
749 content = inside;
750 }
751 let paths = match theme::load_css_paths(content) {
752 Ok(p) => p,
753 Err(e) => dcx.fatal(e),
754 };
755
756 for (theme_file, theme_s) in
757 matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
758 {
759 if !theme_file.is_file() {
760 dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
761 .with_help("arguments to --theme must be files")
762 .emit_fatal();
763 }
764 if theme_file.extension() != Some(OsStr::new("css")) {
765 dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
766 .with_help("arguments to --theme must have a .css extension")
767 .emit_fatal();
768 }
769 let (success, ret) = theme::test_theme_against(&theme_file, &paths, dcx);
770 if !success {
771 dcx.fatal(format!("error loading theme file: \"{theme_s}\""));
772 } else if !ret.is_empty() {
773 dcx.struct_warn(format!(
774 "theme file \"{theme_s}\" is missing CSS rules from the default theme",
775 ))
776 .with_warn("the theme may appear incorrect when loaded")
777 .with_help(format!(
778 "to see what rules are missing, call `rustdoc --check-theme \"{theme_s}\"`",
779 ))
780 .emit();
781 }
782 loaded_paths.push(theme_file.clone());
783 themes.push(StylePath { path: theme_file });
784 }
785 }
786
787 let edition = config::parse_crate_edition(early_dcx, matches, true);
788
789 let mut id_map = html::markdown::IdMap::new();
790 let Some(external_html) = ExternalHtml::load(
791 &matches.opt_strs("html-in-header"),
792 &matches.opt_strs("html-before-content"),
793 &matches.opt_strs("html-after-content"),
794 &matches.opt_strs("markdown-before-content"),
795 &matches.opt_strs("markdown-after-content"),
796 nightly_options::match_is_nightly_build(matches),
797 dcx,
798 &mut id_map,
799 edition,
800 &None,
801 &mut loaded_paths,
802 ) else {
803 dcx.fatal("`ExternalHtml::load` failed");
804 };
805
806 match matches.opt_str("r").as_deref() {
807 Some("rust") | None => {}
808 Some(s) => dcx.fatal(format!("unknown input format: {s}")),
809 }
810
811 let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
812 if let Some(ref index_page) = index_page {
813 if index_page.is_file() {
814 loaded_paths.push(index_page.clone());
815 } else {
816 dcx.fatal("option `--index-page` argument must be a file");
817 }
818 }
819
820 let target = parse_target_triple(early_dcx, matches);
821 let sysroot = Sysroot::new(matches.opt_str("sysroot").map(PathBuf::from));
822
823 let libs = matches
824 .opt_strs("L")
825 .iter()
826 .map(|s| {
827 SearchPath::from_cli_opt(
828 sysroot.path(),
829 &target,
830 early_dcx,
831 s,
832 #[allow(rustc::bad_opt_access)] unstable_opts.unstable_options,
834 )
835 })
836 .collect();
837
838 let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
839 Ok(types) => types,
840 Err(e) => {
841 dcx.fatal(format!("unknown crate type: {e}"));
842 }
843 };
844
845 let bin_crate = crate_types.contains(&CrateType::Executable);
846 let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
847 let playground_url = matches.opt_str("playground-url");
848 let module_sorting = if matches.opt_present("sort-modules-by-appearance") {
849 ModuleSorting::DeclarationOrder
850 } else {
851 ModuleSorting::Alphabetical
852 };
853 let crate_list_heading = matches.opt_str("crate-list-heading").unwrap_or_default();
854 let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
855 let markdown_no_toc = matches.opt_present("markdown-no-toc");
856 let markdown_css = matches.opt_strs("markdown-css");
857 let markdown_playground_url = matches.opt_str("markdown-playground-url");
858 let crate_version = matches.opt_str("crate-version");
859 let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
860 let static_root_path = matches.opt_str("static-root-path");
861 let test_run_directory = matches.opt_str("test-run-directory").map(PathBuf::from);
862 let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
863 let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
864 let codegen_options_strs = matches.opt_strs("C");
865 let unstable_opts_strs = matches.opt_strs("Z");
866 let lib_strs = matches.opt_strs("L");
867 let extern_strs = matches.opt_strs("extern");
868 let remap_path_prefix_strs = matches.opt_strs("remap-path-prefix");
869 let remap_path_scope_str = matches.opt_str("remap-path-scope");
870 let test_runtool = matches.opt_str("test-runtool");
871 let test_runtool_args = matches.opt_strs("test-runtool-arg");
872 let document_private = matches.opt_present("document-private-items");
873 let document_hidden = matches.opt_present("document-hidden-items");
874 let run_check = matches.opt_present("check");
875 let generate_redirect_map = matches.opt_present("generate-redirect-map");
876 let show_type_layout = matches.opt_present("show-type-layout");
877 let no_capture = matches.opt_present("no-capture");
878 let generate_link_to_definition = matches.opt_present("generate-link-to-definition");
879 let generate_macro_expansion = matches.opt_present("generate-macro-expansion");
880 let extern_html_root_takes_precedence =
881 matches.opt_present("extern-html-root-takes-precedence");
882 let html_no_source = matches.opt_present("html-no-source");
883 let merge_doctests = parse_merge_doctests(matches, edition, dcx);
884 tracing::debug!("merge_doctests: {merge_doctests:?}");
885
886 if generate_link_to_definition && (show_coverage || output_format != OutputFormat::Html) {
887 dcx.struct_warn(
888 "`--generate-link-to-definition` option can only be used with HTML output format",
889 )
890 .with_note("`--generate-link-to-definition` option will be ignored")
891 .emit();
892 }
893 if generate_macro_expansion && (show_coverage || output_format != OutputFormat::Html) {
894 dcx.struct_warn(
895 "`--generate-macro-expansion` option can only be used with HTML output format",
896 )
897 .with_note("`--generate-macro-expansion` option will be ignored")
898 .emit();
899 }
900
901 let scrape_examples_options = ScrapeExamplesOptions::new(matches, dcx);
902 let with_examples = matches.opt_strs("with-examples");
903 let call_locations =
904 crate::scrape_examples::load_call_locations(with_examples, dcx, &mut loaded_paths);
905 let doctest_build_args = matches.opt_strs("doctest-build-arg");
906
907 let disable_minification = matches.opt_present("disable-minification");
908
909 let options = Options {
910 bin_crate,
911 proc_macro_crate,
912 error_format,
913 diagnostic_width,
914 libs,
915 lib_strs,
916 externs,
917 extern_strs,
918 cfgs,
919 check_cfgs,
920 codegen_options,
921 codegen_options_strs,
922 unstable_opts,
923 unstable_opts_strs,
924 target,
925 edition,
926 sysroot,
927 lint_opts,
928 describe_lints,
929 lint_cap,
930 prints,
931 should_test,
932 test_args,
933 show_coverage,
934 crate_version,
935 test_run_directory,
936 persist_doctests,
937 merge_doctests,
938 test_runtool,
939 test_runtool_args,
940 test_builder,
941 run_check,
942 no_run,
943 test_builder_wrappers,
944 remap_path_prefix,
945 remap_path_prefix_strs,
946 remap_path_scope,
947 remap_path_scope_str,
948 no_capture,
949 crate_name,
950 output_format,
951 json_unused_externs,
952 scrape_examples_options,
953 unstable_features: unstable_features.clone(),
954 doctest_build_args,
955 target_modifiers: collected_options.target_modifiers,
956 };
957 let render_options = RenderOptions {
958 output,
959 external_html,
960 id_map,
961 playground_url,
962 module_sorting,
963 crate_list_heading,
964 themes,
965 extension_css,
966 extern_html_root_urls,
967 extern_html_root_takes_precedence,
968 default_settings,
969 resource_suffix,
970 enable_index_page,
971 index_page,
972 static_root_path,
973 markdown_no_toc,
974 markdown_css,
975 markdown_playground_url,
976 document_private,
977 document_hidden,
978 generate_redirect_map,
979 show_type_layout,
980 unstable_features,
981 emit,
982 generate_link_to_definition,
983 generate_macro_expansion,
984 call_locations,
985 no_emit_shared: false,
986 html_no_source,
987 output_to_stdout,
988 should_merge,
989 include_parts_dir,
990 parts_out_dir,
991 disable_minification,
992 };
993 Some((input, options, render_options, loaded_paths))
994 }
995}
996
997pub(crate) fn markdown_input(input: &Input) -> Option<&Path> {
999 input.opt_path().filter(|p| matches!(p.extension(), Some(e) if e == "md" || e == "markdown"))
1000}
1001
1002fn parse_remap_path_prefix(
1003 matches: &getopts::Matches,
1004) -> Result<Vec<(PathBuf, PathBuf)>, &'static str> {
1005 matches
1006 .opt_strs("remap-path-prefix")
1007 .into_iter()
1008 .map(|remap| {
1009 remap
1010 .rsplit_once('=')
1011 .ok_or("--remap-path-prefix must contain '=' between FROM and TO")
1012 .map(|(from, to)| (PathBuf::from(from), PathBuf::from(to)))
1013 })
1014 .collect()
1015}
1016
1017fn check_deprecated_options(matches: &getopts::Matches, dcx: DiagCtxtHandle<'_>) {
1019 let deprecated_flags = [];
1020
1021 for &flag in deprecated_flags.iter() {
1022 if matches.opt_present(flag) {
1023 dcx.struct_warn(format!("the `{flag}` flag is deprecated"))
1024 .with_note(
1025 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
1026 for more information",
1027 )
1028 .emit();
1029 }
1030 }
1031
1032 let removed_flags = ["plugins", "plugin-path", "no-defaults", "passes", "input-format"];
1033
1034 for &flag in removed_flags.iter() {
1035 if matches.opt_present(flag) {
1036 let mut err = dcx.struct_warn(format!("the `{flag}` flag no longer functions"));
1037 err.note(
1038 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
1039 for more information",
1040 );
1041
1042 if flag == "no-defaults" || flag == "passes" {
1043 err.help("you may want to use --document-private-items");
1044 } else if flag == "plugins" || flag == "plugin-path" {
1045 err.warn("see CVE-2018-1000622");
1046 }
1047
1048 err.emit();
1049 }
1050 }
1051}
1052
1053fn parse_extern_html_roots(
1057 matches: &getopts::Matches,
1058) -> Result<BTreeMap<String, String>, &'static str> {
1059 let mut externs = BTreeMap::new();
1060 for arg in &matches.opt_strs("extern-html-root-url") {
1061 let (name, url) =
1062 arg.split_once('=').ok_or("--extern-html-root-url must be of the form name=url")?;
1063 externs.insert(name.to_string(), url.to_string());
1064 }
1065 Ok(externs)
1066}
1067
1068#[derive(Clone, Debug)]
1073pub(crate) struct PathToParts(pub(crate) PathBuf);
1074
1075impl PathToParts {
1076 fn from_flag(path: String) -> Result<PathToParts, String> {
1077 let path = PathBuf::from(path);
1078 if path.exists() && !path.is_dir() {
1080 Err(format!(
1081 "--write-doc-meta-dir and --read-doc-meta-dir expect directories, found: {}",
1082 path.display(),
1083 ))
1084 } else {
1085 Ok(PathToParts(path))
1087 }
1088 }
1089}
1090
1091fn parse_read_doc_meta(m: &getopts::Matches, name: &str) -> Result<Vec<PathToParts>, String> {
1093 let mut ret = Vec::new();
1094 for p in m.opt_strs(name) {
1095 let p = PathToParts::from_flag(p)?;
1096 if !p.0.is_dir() {
1098 return Err(format!(
1099 "--read-doc-meta-dir expected {} to be a directory",
1100 p.0.display()
1101 ));
1102 }
1103 ret.push(p);
1104 }
1105 Ok(ret)
1106}
1107
1108#[derive(Debug, Clone)]
1110pub(crate) struct ShouldMerge {
1111 pub(crate) read_rendered_cci: bool,
1113 pub(crate) write_rendered_cci: bool,
1115}
1116
1117fn compute_should_merge(m: &getopts::Matches) -> Result<ShouldMerge, &'static str> {
1120 match (m.opt_present("read-doc-meta-dir"), m.opt_present("write-doc-meta-dir")) {
1121 (false, false) => Ok(ShouldMerge { read_rendered_cci: true, write_rendered_cci: true }),
1123 (false, true) => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: false }),
1125 (true, false) => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: true }),
1127 (true, true) => Err("cannot pass both --read-doc-meta-dir and --write-doc-meta-dir"),
1129 }
1130}
1131
1132fn parse_merge_doctests(
1133 m: &getopts::Matches,
1134 edition: Edition,
1135 dcx: DiagCtxtHandle<'_>,
1136) -> MergeDoctests {
1137 match m.opt_str("merge-doctests").as_deref() {
1138 Some("y") | Some("yes") | Some("on") | Some("true") => MergeDoctests::Always,
1139 Some("n") | Some("no") | Some("off") | Some("false") => MergeDoctests::Never,
1140 Some("auto") => MergeDoctests::Auto,
1141 None if edition < Edition::Edition2024 => MergeDoctests::Never,
1142 None => MergeDoctests::Auto,
1143 Some(_) => {
1144 dcx.fatal("argument to --merge-doctests must be a boolean (true/false) or 'auto'")
1145 }
1146 }
1147}