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