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