rustdoc/
config.rs

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::FileName;
19use rustc_span::edition::Edition;
20use rustc_target::spec::TargetTuple;
21
22use crate::core::new_dcx;
23use crate::externalfiles::ExternalHtml;
24use crate::html::markdown::IdMap;
25use crate::html::render::StylePath;
26use crate::html::static_files;
27use crate::passes::{self, Condition};
28use crate::scrape_examples::{AllCallLocations, ScrapeExamplesOptions};
29use crate::{html, opts, theme};
30
31#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
32pub(crate) enum OutputFormat {
33    Json,
34    #[default]
35    Html,
36    Doctest,
37}
38
39impl OutputFormat {
40    pub(crate) fn is_json(&self) -> bool {
41        matches!(self, OutputFormat::Json)
42    }
43}
44
45impl TryFrom<&str> for OutputFormat {
46    type Error = String;
47
48    fn try_from(value: &str) -> Result<Self, Self::Error> {
49        match value {
50            "json" => Ok(OutputFormat::Json),
51            "html" => Ok(OutputFormat::Html),
52            "doctest" => Ok(OutputFormat::Doctest),
53            _ => Err(format!("unknown output format `{value}`")),
54        }
55    }
56}
57
58/// Either an input crate, markdown file, or nothing (--merge=finalize).
59pub(crate) enum InputMode {
60    /// The `--merge=finalize` step does not need an input crate to rustdoc.
61    NoInputMergeFinalize,
62    /// A crate or markdown file.
63    HasFile(Input),
64}
65
66/// Whether to run multiple doctests in the same binary.
67#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
68pub(crate) enum MergeDoctests {
69    #[default]
70    Never,
71    Always,
72    Auto,
73}
74
75/// Configuration options for rustdoc.
76#[derive(Clone)]
77pub(crate) struct Options {
78    // Basic options / Options passed directly to rustc
79    /// The name of the crate being documented.
80    pub(crate) crate_name: Option<String>,
81    /// Whether or not this is a bin crate
82    pub(crate) bin_crate: bool,
83    /// Whether or not this is a proc-macro crate
84    pub(crate) proc_macro_crate: bool,
85    /// How to format errors and warnings.
86    pub(crate) error_format: ErrorOutputType,
87    /// Width of output buffer to truncate errors appropriately.
88    pub(crate) diagnostic_width: Option<usize>,
89    /// Library search paths to hand to the compiler.
90    pub(crate) libs: Vec<SearchPath>,
91    /// Library search paths strings to hand to the compiler.
92    pub(crate) lib_strs: Vec<String>,
93    /// The list of external crates to link against.
94    pub(crate) externs: Externs,
95    /// The list of external crates strings to link against.
96    pub(crate) extern_strs: Vec<String>,
97    /// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`.
98    pub(crate) cfgs: Vec<String>,
99    /// List of check cfg flags to hand to the compiler.
100    pub(crate) check_cfgs: Vec<String>,
101    /// Codegen options to hand to the compiler.
102    pub(crate) codegen_options: CodegenOptions,
103    /// Codegen options strings to hand to the compiler.
104    pub(crate) codegen_options_strs: Vec<String>,
105    /// Unstable (`-Z`) options to pass to the compiler.
106    pub(crate) unstable_opts: UnstableOptions,
107    /// Unstable (`-Z`) options strings to pass to the compiler.
108    pub(crate) unstable_opts_strs: Vec<String>,
109    /// The target used to compile the crate against.
110    pub(crate) target: TargetTuple,
111    /// Edition used when reading the crate. Defaults to "2015". Also used by default when
112    /// compiling doctests from the crate.
113    pub(crate) edition: Edition,
114    /// The path to the sysroot. Used during the compilation process.
115    pub(crate) sysroot: Sysroot,
116    /// Lint information passed over the command-line.
117    pub(crate) lint_opts: Vec<(String, Level)>,
118    /// Whether to ask rustc to describe the lints it knows.
119    pub(crate) describe_lints: bool,
120    /// What level to cap lints at.
121    pub(crate) lint_cap: Option<Level>,
122
123    // Options specific to running doctests
124    /// Whether we should run doctests instead of generating docs.
125    pub(crate) should_test: bool,
126    /// List of arguments to pass to the test harness, if running tests.
127    pub(crate) test_args: Vec<String>,
128    /// The working directory in which to run tests.
129    pub(crate) test_run_directory: Option<PathBuf>,
130    /// Optional path to persist the doctest executables to, defaults to a
131    /// temporary directory if not set.
132    pub(crate) persist_doctests: Option<PathBuf>,
133    /// Whether to merge
134    pub(crate) merge_doctests: MergeDoctests,
135    /// Runtool to run doctests with
136    pub(crate) test_runtool: Option<String>,
137    /// Arguments to pass to the runtool
138    pub(crate) test_runtool_args: Vec<String>,
139    /// Do not run doctests, compile them if should_test is active.
140    pub(crate) no_run: bool,
141    /// What sources are being mapped.
142    pub(crate) remap_path_prefix: Vec<(PathBuf, PathBuf)>,
143
144    /// The path to a rustc-like binary to build tests with. If not set, we
145    /// default to loading from `$sysroot/bin/rustc`.
146    pub(crate) test_builder: Option<PathBuf>,
147
148    /// Run these wrapper instead of rustc directly
149    pub(crate) test_builder_wrappers: Vec<PathBuf>,
150
151    // Options that affect the documentation process
152    /// Whether to run the `calculate-doc-coverage` pass, which counts the number of public items
153    /// with and without documentation.
154    pub(crate) show_coverage: bool,
155
156    // Options that alter generated documentation pages
157    /// Crate version to note on the sidebar of generated docs.
158    pub(crate) crate_version: Option<String>,
159    /// The format that we output when rendering.
160    ///
161    /// Currently used only for the `--show-coverage` option.
162    pub(crate) output_format: OutputFormat,
163    /// If this option is set to `true`, rustdoc will only run checks and not generate
164    /// documentation.
165    pub(crate) run_check: bool,
166    /// Whether doctests should emit unused externs
167    pub(crate) json_unused_externs: JsonUnusedExterns,
168    /// Whether to skip capturing stdout and stderr of tests.
169    pub(crate) no_capture: bool,
170
171    /// Configuration for scraping examples from the current crate. If this option is Some(..) then
172    /// the compiler will scrape examples and not generate documentation.
173    pub(crate) scrape_examples_options: Option<ScrapeExamplesOptions>,
174
175    /// Note: this field is duplicated in `RenderOptions` because it's useful
176    /// to have it in both places.
177    pub(crate) unstable_features: rustc_feature::UnstableFeatures,
178
179    /// Arguments to be used when compiling doctests.
180    pub(crate) doctest_build_args: Vec<String>,
181
182    /// Target modifiers.
183    pub(crate) target_modifiers: BTreeMap<OptionsTargetModifiers, String>,
184}
185
186impl fmt::Debug for Options {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        struct FmtExterns<'a>(&'a Externs);
189
190        impl fmt::Debug for FmtExterns<'_> {
191            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192                f.debug_map().entries(self.0.iter()).finish()
193            }
194        }
195
196        f.debug_struct("Options")
197            .field("crate_name", &self.crate_name)
198            .field("bin_crate", &self.bin_crate)
199            .field("proc_macro_crate", &self.proc_macro_crate)
200            .field("error_format", &self.error_format)
201            .field("libs", &self.libs)
202            .field("externs", &FmtExterns(&self.externs))
203            .field("cfgs", &self.cfgs)
204            .field("check-cfgs", &self.check_cfgs)
205            .field("codegen_options", &"...")
206            .field("unstable_options", &"...")
207            .field("target", &self.target)
208            .field("edition", &self.edition)
209            .field("sysroot", &self.sysroot)
210            .field("lint_opts", &self.lint_opts)
211            .field("describe_lints", &self.describe_lints)
212            .field("lint_cap", &self.lint_cap)
213            .field("should_test", &self.should_test)
214            .field("test_args", &self.test_args)
215            .field("test_run_directory", &self.test_run_directory)
216            .field("persist_doctests", &self.persist_doctests)
217            .field("show_coverage", &self.show_coverage)
218            .field("crate_version", &self.crate_version)
219            .field("test_runtool", &self.test_runtool)
220            .field("test_runtool_args", &self.test_runtool_args)
221            .field("run_check", &self.run_check)
222            .field("no_run", &self.no_run)
223            .field("test_builder_wrappers", &self.test_builder_wrappers)
224            .field("remap-file-prefix", &self.remap_path_prefix)
225            .field("no_capture", &self.no_capture)
226            .field("scrape_examples_options", &self.scrape_examples_options)
227            .field("unstable_features", &self.unstable_features)
228            .finish()
229    }
230}
231
232/// Configuration options for the HTML page-creation process.
233#[derive(Clone, Debug)]
234pub(crate) struct RenderOptions {
235    /// Output directory to generate docs into. Defaults to `doc`.
236    pub(crate) output: PathBuf,
237    /// External files to insert into generated pages.
238    pub(crate) external_html: ExternalHtml,
239    /// A pre-populated `IdMap` with the default headings and any headings added by Markdown files
240    /// processed by `external_html`.
241    pub(crate) id_map: IdMap,
242    /// If present, playground URL to use in the "Run" button added to code samples.
243    ///
244    /// Be aware: This option can come both from the CLI and from crate attributes!
245    pub(crate) playground_url: Option<String>,
246    /// What sorting mode to use for module pages.
247    /// `ModuleSorting::Alphabetical` by default.
248    pub(crate) module_sorting: ModuleSorting,
249    /// List of themes to extend the docs with. Original argument name is included to assist in
250    /// displaying errors if it fails a theme check.
251    pub(crate) themes: Vec<StylePath>,
252    /// If present, CSS file that contains rules to add to the default CSS.
253    pub(crate) extension_css: Option<PathBuf>,
254    /// A map of crate names to the URL to use instead of querying the crate's `html_root_url`.
255    pub(crate) extern_html_root_urls: BTreeMap<String, String>,
256    /// Whether to give precedence to `html_root_url` or `--extern-html-root-url`.
257    pub(crate) extern_html_root_takes_precedence: bool,
258    /// A map of the default settings (values are as for DOM storage API). Keys should lack the
259    /// `rustdoc-` prefix.
260    pub(crate) default_settings: FxIndexMap<String, String>,
261    /// If present, suffix added to CSS/JavaScript files when referencing them in generated pages.
262    pub(crate) resource_suffix: String,
263    /// Whether to create an index page in the root of the output directory. If this is true but
264    /// `enable_index_page` is None, generate a static listing of crates instead.
265    pub(crate) enable_index_page: bool,
266    /// A file to use as the index page at the root of the output directory. Overrides
267    /// `enable_index_page` to be true if set.
268    pub(crate) index_page: Option<PathBuf>,
269    /// An optional path to use as the location of static files. If not set, uses combinations of
270    /// `../` to reach the documentation root.
271    pub(crate) static_root_path: Option<String>,
272
273    // Options specific to reading standalone Markdown files
274    /// Whether to generate a table of contents on the output file when reading a standalone
275    /// Markdown file.
276    pub(crate) markdown_no_toc: bool,
277    /// Additional CSS files to link in pages generated from standalone Markdown files.
278    pub(crate) markdown_css: Vec<String>,
279    /// If present, playground URL to use in the "Run" button added to code samples generated from
280    /// standalone Markdown files. If not present, `playground_url` is used.
281    pub(crate) markdown_playground_url: Option<String>,
282    /// Document items that have lower than `pub` visibility.
283    pub(crate) document_private: bool,
284    /// Document items that have `doc(hidden)`.
285    pub(crate) document_hidden: bool,
286    /// If `true`, generate a JSON file in the crate folder instead of HTML redirection files.
287    pub(crate) generate_redirect_map: bool,
288    /// Show the memory layout of types in the docs.
289    pub(crate) show_type_layout: bool,
290    /// Note: this field is duplicated in `Options` because it's useful to have
291    /// it in both places.
292    pub(crate) unstable_features: rustc_feature::UnstableFeatures,
293    pub(crate) emit: Vec<EmitType>,
294    /// If `true`, HTML source pages will generate links for items to their definition.
295    pub(crate) generate_link_to_definition: bool,
296    /// Set of function-call locations to include as examples
297    pub(crate) call_locations: AllCallLocations,
298    /// If `true`, Context::init will not emit shared files.
299    pub(crate) no_emit_shared: bool,
300    /// If `true`, HTML source code pages won't be generated.
301    pub(crate) html_no_source: bool,
302    /// This field is only used for the JSON output. If it's set to true, no file will be created
303    /// and content will be displayed in stdout directly.
304    pub(crate) output_to_stdout: bool,
305    /// Whether we should read or write rendered cross-crate info in the doc root.
306    pub(crate) should_merge: ShouldMerge,
307    /// Path to crate-info for external crates.
308    pub(crate) include_parts_dir: Vec<PathToParts>,
309    /// Where to write crate-info
310    pub(crate) parts_out_dir: Option<PathToParts>,
311    /// disable minification of CSS/JS
312    pub(crate) disable_minification: bool,
313    /// If `true`, HTML source pages will generate the possibility to expand macros.
314    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    Toolchain,
326    InvocationSpecific,
327    DepInfo(Option<OutFileName>),
328}
329
330impl FromStr for EmitType {
331    type Err = ();
332
333    fn from_str(s: &str) -> Result<Self, Self::Err> {
334        match s {
335            "toolchain-shared-resources" => Ok(Self::Toolchain),
336            "invocation-specific" => Ok(Self::InvocationSpecific),
337            "dep-info" => Ok(Self::DepInfo(None)),
338            option => match option.strip_prefix("dep-info=") {
339                Some("-") => Ok(Self::DepInfo(Some(OutFileName::Stdout))),
340                Some(f) => Ok(Self::DepInfo(Some(OutFileName::Real(f.into())))),
341                None => Err(()),
342            },
343        }
344    }
345}
346
347impl RenderOptions {
348    pub(crate) fn should_emit_crate(&self) -> bool {
349        self.emit.is_empty() || self.emit.contains(&EmitType::InvocationSpecific)
350    }
351
352    pub(crate) fn dep_info(&self) -> Option<Option<&OutFileName>> {
353        for emit in &self.emit {
354            if let EmitType::DepInfo(file) = emit {
355                return Some(file.as_ref());
356            }
357        }
358        None
359    }
360}
361
362/// Create the input (string or file path)
363///
364/// Warning: Return an unrecoverable error in case of error!
365fn make_input(early_dcx: &EarlyDiagCtxt, input: &str) -> Input {
366    if input == "-" {
367        let mut src = String::new();
368        if io::stdin().read_to_string(&mut src).is_err() {
369            // Immediately stop compilation if there was an issue reading
370            // the input (for example if the input stream is not UTF-8).
371            early_dcx.early_fatal("couldn't read from stdin, as it did not contain valid UTF-8");
372        }
373        Input::Str { name: FileName::anon_source_code(&src), input: src }
374    } else {
375        Input::File(PathBuf::from(input))
376    }
377}
378
379impl Options {
380    /// Parses the given command-line for options. If an error message or other early-return has
381    /// been printed, returns `Err` with the exit code.
382    pub(crate) fn from_matches(
383        early_dcx: &mut EarlyDiagCtxt,
384        matches: &getopts::Matches,
385        args: Vec<String>,
386    ) -> Option<(InputMode, Options, RenderOptions, Vec<PathBuf>)> {
387        // Check for unstable options.
388        nightly_options::check_nightly_options(early_dcx, matches, &opts());
389
390        if args.is_empty() || matches.opt_present("h") || matches.opt_present("help") {
391            crate::usage("rustdoc");
392            return None;
393        } else if matches.opt_present("version") {
394            rustc_driver::version!(&early_dcx, "rustdoc", matches);
395            return None;
396        }
397
398        if rustc_driver::describe_flag_categories(early_dcx, matches) {
399            return None;
400        }
401
402        let color = config::parse_color(early_dcx, matches);
403        let crate_name = matches.opt_str("crate-name");
404        let unstable_features =
405            rustc_feature::UnstableFeatures::from_environment(crate_name.as_deref());
406        let config::JsonConfig { json_rendered, json_unused_externs, json_color, .. } =
407            config::parse_json(early_dcx, matches, unstable_features.is_nightly_build());
408        let error_format = config::parse_error_format(
409            early_dcx,
410            matches,
411            color,
412            json_color,
413            json_rendered,
414            unstable_features.is_nightly_build(),
415        );
416        let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_default();
417
418        let mut target_modifiers = BTreeMap::<OptionsTargetModifiers, String>::new();
419        let codegen_options = CodegenOptions::build(early_dcx, matches, &mut target_modifiers);
420        let unstable_opts = UnstableOptions::build(early_dcx, matches, &mut target_modifiers);
421
422        let remap_path_prefix = match parse_remap_path_prefix(matches) {
423            Ok(prefix_mappings) => prefix_mappings,
424            Err(err) => {
425                early_dcx.early_fatal(err);
426            }
427        };
428
429        let dcx = new_dcx(error_format, None, diagnostic_width, &unstable_opts);
430        let dcx = dcx.handle();
431
432        // check for deprecated options
433        check_deprecated_options(matches, dcx);
434
435        if matches.opt_strs("passes") == ["list"] {
436            println!("Available passes for running rustdoc:");
437            for pass in passes::PASSES {
438                println!("{:>20} - {}", pass.name, pass.description);
439            }
440            println!("\nDefault passes for rustdoc:");
441            for p in passes::DEFAULT_PASSES {
442                print!("{:>20}", p.pass.name);
443                println_condition(p.condition);
444            }
445
446            if nightly_options::match_is_nightly_build(matches) {
447                println!("\nPasses run with `--show-coverage`:");
448                for p in passes::COVERAGE_PASSES {
449                    print!("{:>20}", p.pass.name);
450                    println_condition(p.condition);
451                }
452            }
453
454            fn println_condition(condition: Condition) {
455                use Condition::*;
456                match condition {
457                    Always => println!(),
458                    WhenDocumentPrivate => println!("  (when --document-private-items)"),
459                    WhenNotDocumentPrivate => println!("  (when not --document-private-items)"),
460                    WhenNotDocumentHidden => println!("  (when not --document-hidden-items)"),
461                }
462            }
463
464            return None;
465        }
466
467        let mut emit = FxIndexMap::<_, EmitType>::default();
468        for list in matches.opt_strs("emit") {
469            for kind in list.split(',') {
470                match kind.parse() {
471                    Ok(kind) => {
472                        // De-duplicate emit types and the last wins.
473                        // Only one instance for each type is allowed
474                        // regardless the actual data it carries.
475                        // This matches rustc's `--emit` behavior.
476                        emit.insert(std::mem::discriminant(&kind), kind);
477                    }
478                    Err(()) => dcx.fatal(format!("unrecognized emission type: {kind}")),
479                }
480            }
481        }
482        let emit = emit.into_values().collect::<Vec<_>>();
483
484        let show_coverage = matches.opt_present("show-coverage");
485        let output_format_s = matches.opt_str("output-format");
486        let output_format = match output_format_s {
487            Some(ref s) => match OutputFormat::try_from(s.as_str()) {
488                Ok(out_fmt) => out_fmt,
489                Err(e) => dcx.fatal(e),
490            },
491            None => OutputFormat::default(),
492        };
493
494        // check for `--output-format=json`
495        match (
496            output_format_s.as_ref().map(|_| output_format),
497            show_coverage,
498            nightly_options::is_unstable_enabled(matches),
499        ) {
500            (None | Some(OutputFormat::Json), true, _) => {}
501            (_, true, _) => {
502                dcx.fatal(format!(
503                    "`--output-format={}` is not supported for the `--show-coverage` option",
504                    output_format_s.unwrap_or_default(),
505                ));
506            }
507            // If `-Zunstable-options` is used, nothing to check after this point.
508            (_, false, true) => {}
509            (None | Some(OutputFormat::Html), false, _) => {}
510            (Some(OutputFormat::Json), false, false) => {
511                dcx.fatal(
512                    "the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/76578)",
513                );
514            }
515            (Some(OutputFormat::Doctest), false, false) => {
516                dcx.fatal(
517                    "the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/134529)",
518                );
519            }
520        }
521
522        let to_check = matches.opt_strs("check-theme");
523        if !to_check.is_empty() {
524            let mut content =
525                std::str::from_utf8(static_files::STATIC_FILES.rustdoc_css.src_bytes).unwrap();
526            if let Some((_, inside)) = content.split_once("/* Begin theme: light */") {
527                content = inside;
528            }
529            if let Some((inside, _)) = content.split_once("/* End theme: light */") {
530                content = inside;
531            }
532            let paths = match theme::load_css_paths(content) {
533                Ok(p) => p,
534                Err(e) => dcx.fatal(e),
535            };
536            let mut errors = 0;
537
538            println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
539            for theme_file in to_check.iter() {
540                print!(" - Checking \"{theme_file}\"...");
541                let (success, differences) = theme::test_theme_against(theme_file, &paths, dcx);
542                if !differences.is_empty() || !success {
543                    println!(" FAILED");
544                    errors += 1;
545                    if !differences.is_empty() {
546                        println!("{}", differences.join("\n"));
547                    }
548                } else {
549                    println!(" OK");
550                }
551            }
552            if errors != 0 {
553                dcx.fatal("[check-theme] one or more tests failed");
554            }
555            return None;
556        }
557
558        let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(early_dcx, matches);
559
560        let input = if describe_lints {
561            InputMode::HasFile(make_input(early_dcx, ""))
562        } else {
563            match matches.free.as_slice() {
564                [] if matches.opt_str("merge").as_deref() == Some("finalize") => {
565                    InputMode::NoInputMergeFinalize
566                }
567                [] => dcx.fatal("missing file operand"),
568                [input] => InputMode::HasFile(make_input(early_dcx, input)),
569                _ => dcx.fatal("too many file operands"),
570            }
571        };
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 parts_out_dir =
580            match matches.opt_str("parts-out-dir").map(PathToParts::from_flag).transpose() {
581                Ok(parts_out_dir) => parts_out_dir,
582                Err(e) => dcx.fatal(e),
583            };
584        let include_parts_dir = match parse_include_parts_dir(matches) {
585            Ok(include_parts_dir) => include_parts_dir,
586            Err(e) => dcx.fatal(e),
587        };
588
589        let default_settings: Vec<Vec<(String, String)>> = vec![
590            matches
591                .opt_str("default-theme")
592                .iter()
593                .flat_map(|theme| {
594                    vec![
595                        ("use-system-theme".to_string(), "false".to_string()),
596                        ("theme".to_string(), theme.to_string()),
597                    ]
598                })
599                .collect(),
600            matches
601                .opt_strs("default-setting")
602                .iter()
603                .map(|s| match s.split_once('=') {
604                    None => (s.clone(), "true".to_string()),
605                    Some((k, v)) => (k.to_string(), v.to_string()),
606                })
607                .collect(),
608        ];
609        let default_settings = default_settings
610            .into_iter()
611            .flatten()
612            .map(
613                // The keys here become part of `data-` attribute names in the generated HTML.  The
614                // browser does a strange mapping when converting them into attributes on the
615                // `dataset` property on the DOM HTML Node:
616                //   https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
617                //
618                // The original key values we have are the same as the DOM storage API keys and the
619                // command line options, so contain `-`.  Our JavaScript needs to be able to look
620                // these values up both in `dataset` and in the storage API, so it needs to be able
621                // to convert the names back and forth.  Despite doing this kebab-case to
622                // StudlyCaps transformation automatically, the JS DOM API does not provide a
623                // mechanism for doing just the transformation on a string.  So we want to avoid
624                // the StudlyCaps representation in the `dataset` property.
625                //
626                // We solve this by replacing all the `-`s with `_`s.  We do that here, when we
627                // generate the `data-` attributes, and in the JS, when we look them up.  (See
628                // `getSettingValue` in `storage.js.`) Converting `-` to `_` is simple in JS.
629                //
630                // The values will be HTML-escaped by the default Tera escaping.
631                |(k, v)| (k.replace('-', "_"), v),
632            )
633            .collect();
634
635        let test_args = matches.opt_strs("test-args");
636        let test_args: Vec<String> =
637            test_args.iter().flat_map(|s| s.split_whitespace()).map(|s| s.to_string()).collect();
638
639        let should_test = matches.opt_present("test");
640        let no_run = matches.opt_present("no-run");
641
642        if !should_test && no_run {
643            dcx.fatal("the `--test` flag must be passed to enable `--no-run`");
644        }
645
646        let mut output_to_stdout = false;
647        let test_builder_wrappers =
648            matches.opt_strs("test-builder-wrapper").iter().map(PathBuf::from).collect();
649        let output = match (matches.opt_str("out-dir"), matches.opt_str("output")) {
650            (Some(_), Some(_)) => {
651                dcx.fatal("cannot use both 'out-dir' and 'output' at once");
652            }
653            (Some(out_dir), None) | (None, Some(out_dir)) => {
654                output_to_stdout = out_dir == "-";
655                PathBuf::from(out_dir)
656            }
657            (None, None) => PathBuf::from("doc"),
658        };
659
660        let cfgs = matches.opt_strs("cfg");
661        let check_cfgs = matches.opt_strs("check-cfg");
662
663        let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
664
665        let mut loaded_paths = Vec::new();
666
667        if let Some(ref p) = extension_css {
668            loaded_paths.push(p.clone());
669            if !p.is_file() {
670                dcx.fatal("option --extend-css argument must be a file");
671            }
672        }
673
674        let mut themes = Vec::new();
675        if matches.opt_present("theme") {
676            let mut content =
677                std::str::from_utf8(static_files::STATIC_FILES.rustdoc_css.src_bytes).unwrap();
678            if let Some((_, inside)) = content.split_once("/* Begin theme: light */") {
679                content = inside;
680            }
681            if let Some((inside, _)) = content.split_once("/* End theme: light */") {
682                content = inside;
683            }
684            let paths = match theme::load_css_paths(content) {
685                Ok(p) => p,
686                Err(e) => dcx.fatal(e),
687            };
688
689            for (theme_file, theme_s) in
690                matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
691            {
692                if !theme_file.is_file() {
693                    dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
694                        .with_help("arguments to --theme must be files")
695                        .emit();
696                }
697                if theme_file.extension() != Some(OsStr::new("css")) {
698                    dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
699                        .with_help("arguments to --theme must have a .css extension")
700                        .emit();
701                }
702                let (success, ret) = theme::test_theme_against(&theme_file, &paths, dcx);
703                if !success {
704                    dcx.fatal(format!("error loading theme file: \"{theme_s}\""));
705                } else if !ret.is_empty() {
706                    dcx.struct_warn(format!(
707                        "theme file \"{theme_s}\" is missing CSS rules from the default theme",
708                    ))
709                    .with_warn("the theme may appear incorrect when loaded")
710                    .with_help(format!(
711                        "to see what rules are missing, call `rustdoc --check-theme \"{theme_s}\"`",
712                    ))
713                    .emit();
714                }
715                loaded_paths.push(theme_file.clone());
716                themes.push(StylePath { path: theme_file });
717            }
718        }
719
720        let edition = config::parse_crate_edition(early_dcx, matches);
721
722        let mut id_map = html::markdown::IdMap::new();
723        let Some(external_html) = ExternalHtml::load(
724            &matches.opt_strs("html-in-header"),
725            &matches.opt_strs("html-before-content"),
726            &matches.opt_strs("html-after-content"),
727            &matches.opt_strs("markdown-before-content"),
728            &matches.opt_strs("markdown-after-content"),
729            nightly_options::match_is_nightly_build(matches),
730            dcx,
731            &mut id_map,
732            edition,
733            &None,
734            &mut loaded_paths,
735        ) else {
736            dcx.fatal("`ExternalHtml::load` failed");
737        };
738
739        match matches.opt_str("r").as_deref() {
740            Some("rust") | None => {}
741            Some(s) => dcx.fatal(format!("unknown input format: {s}")),
742        }
743
744        let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
745        if let Some(ref index_page) = index_page
746            && !index_page.is_file()
747        {
748            dcx.fatal("option `--index-page` argument must be a file");
749        }
750
751        let target = parse_target_triple(early_dcx, matches);
752        let sysroot = Sysroot::new(matches.opt_str("sysroot").map(PathBuf::from));
753
754        let libs = matches
755            .opt_strs("L")
756            .iter()
757            .map(|s| {
758                SearchPath::from_cli_opt(
759                    sysroot.path(),
760                    &target,
761                    early_dcx,
762                    s,
763                    #[allow(rustc::bad_opt_access)] // we have no `Session` here
764                    unstable_opts.unstable_options,
765                )
766            })
767            .collect();
768
769        let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
770            Ok(types) => types,
771            Err(e) => {
772                dcx.fatal(format!("unknown crate type: {e}"));
773            }
774        };
775
776        let bin_crate = crate_types.contains(&CrateType::Executable);
777        let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
778        let playground_url = matches.opt_str("playground-url");
779        let module_sorting = if matches.opt_present("sort-modules-by-appearance") {
780            ModuleSorting::DeclarationOrder
781        } else {
782            ModuleSorting::Alphabetical
783        };
784        let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
785        let markdown_no_toc = matches.opt_present("markdown-no-toc");
786        let markdown_css = matches.opt_strs("markdown-css");
787        let markdown_playground_url = matches.opt_str("markdown-playground-url");
788        let crate_version = matches.opt_str("crate-version");
789        let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
790        let static_root_path = matches.opt_str("static-root-path");
791        let test_run_directory = matches.opt_str("test-run-directory").map(PathBuf::from);
792        let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
793        let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
794        let codegen_options_strs = matches.opt_strs("C");
795        let unstable_opts_strs = matches.opt_strs("Z");
796        let lib_strs = matches.opt_strs("L");
797        let extern_strs = matches.opt_strs("extern");
798        let test_runtool = matches.opt_str("test-runtool");
799        let test_runtool_args = matches.opt_strs("test-runtool-arg");
800        let document_private = matches.opt_present("document-private-items");
801        let document_hidden = matches.opt_present("document-hidden-items");
802        let run_check = matches.opt_present("check");
803        let generate_redirect_map = matches.opt_present("generate-redirect-map");
804        let show_type_layout = matches.opt_present("show-type-layout");
805        let no_capture = matches.opt_present("no-capture");
806        let generate_link_to_definition = matches.opt_present("generate-link-to-definition");
807        let generate_macro_expansion = matches.opt_present("generate-macro-expansion");
808        let extern_html_root_takes_precedence =
809            matches.opt_present("extern-html-root-takes-precedence");
810        let html_no_source = matches.opt_present("html-no-source");
811        let should_merge = match parse_merge(matches) {
812            Ok(result) => result,
813            Err(e) => dcx.fatal(format!("--merge option error: {e}")),
814        };
815        let merge_doctests = parse_merge_doctests(matches, edition, dcx);
816        tracing::debug!("merge_doctests: {merge_doctests:?}");
817
818        if generate_link_to_definition && (show_coverage || output_format != OutputFormat::Html) {
819            dcx.struct_warn(
820                "`--generate-link-to-definition` option can only be used with HTML output format",
821            )
822            .with_note("`--generate-link-to-definition` option will be ignored")
823            .emit();
824        }
825        if generate_macro_expansion && (show_coverage || output_format != OutputFormat::Html) {
826            dcx.struct_warn(
827                "`--generate-macro-expansion` option can only be used with HTML output format",
828            )
829            .with_note("`--generate-macro-expansion` option will be ignored")
830            .emit();
831        }
832
833        let scrape_examples_options = ScrapeExamplesOptions::new(matches, dcx);
834        let with_examples = matches.opt_strs("with-examples");
835        let call_locations =
836            crate::scrape_examples::load_call_locations(with_examples, dcx, &mut loaded_paths);
837        let doctest_build_args = matches.opt_strs("doctest-build-arg");
838
839        let disable_minification = matches.opt_present("disable-minification");
840
841        let options = Options {
842            bin_crate,
843            proc_macro_crate,
844            error_format,
845            diagnostic_width,
846            libs,
847            lib_strs,
848            externs,
849            extern_strs,
850            cfgs,
851            check_cfgs,
852            codegen_options,
853            codegen_options_strs,
854            unstable_opts,
855            unstable_opts_strs,
856            target,
857            edition,
858            sysroot,
859            lint_opts,
860            describe_lints,
861            lint_cap,
862            should_test,
863            test_args,
864            show_coverage,
865            crate_version,
866            test_run_directory,
867            persist_doctests,
868            merge_doctests,
869            test_runtool,
870            test_runtool_args,
871            test_builder,
872            run_check,
873            no_run,
874            test_builder_wrappers,
875            remap_path_prefix,
876            no_capture,
877            crate_name,
878            output_format,
879            json_unused_externs,
880            scrape_examples_options,
881            unstable_features,
882            doctest_build_args,
883            target_modifiers,
884        };
885        let render_options = RenderOptions {
886            output,
887            external_html,
888            id_map,
889            playground_url,
890            module_sorting,
891            themes,
892            extension_css,
893            extern_html_root_urls,
894            extern_html_root_takes_precedence,
895            default_settings,
896            resource_suffix,
897            enable_index_page,
898            index_page,
899            static_root_path,
900            markdown_no_toc,
901            markdown_css,
902            markdown_playground_url,
903            document_private,
904            document_hidden,
905            generate_redirect_map,
906            show_type_layout,
907            unstable_features,
908            emit,
909            generate_link_to_definition,
910            generate_macro_expansion,
911            call_locations,
912            no_emit_shared: false,
913            html_no_source,
914            output_to_stdout,
915            should_merge,
916            include_parts_dir,
917            parts_out_dir,
918            disable_minification,
919        };
920        Some((input, options, render_options, loaded_paths))
921    }
922}
923
924/// Returns `true` if the file given as `self.input` is a Markdown file.
925pub(crate) fn markdown_input(input: &Input) -> Option<&Path> {
926    input.opt_path().filter(|p| matches!(p.extension(), Some(e) if e == "md" || e == "markdown"))
927}
928
929fn parse_remap_path_prefix(
930    matches: &getopts::Matches,
931) -> Result<Vec<(PathBuf, PathBuf)>, &'static str> {
932    matches
933        .opt_strs("remap-path-prefix")
934        .into_iter()
935        .map(|remap| {
936            remap
937                .rsplit_once('=')
938                .ok_or("--remap-path-prefix must contain '=' between FROM and TO")
939                .map(|(from, to)| (PathBuf::from(from), PathBuf::from(to)))
940        })
941        .collect()
942}
943
944/// Prints deprecation warnings for deprecated options
945fn check_deprecated_options(matches: &getopts::Matches, dcx: DiagCtxtHandle<'_>) {
946    let deprecated_flags = [];
947
948    for &flag in deprecated_flags.iter() {
949        if matches.opt_present(flag) {
950            dcx.struct_warn(format!("the `{flag}` flag is deprecated"))
951                .with_note(
952                    "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
953                    for more information",
954                )
955                .emit();
956        }
957    }
958
959    let removed_flags = ["plugins", "plugin-path", "no-defaults", "passes", "input-format"];
960
961    for &flag in removed_flags.iter() {
962        if matches.opt_present(flag) {
963            let mut err = dcx.struct_warn(format!("the `{flag}` flag no longer functions"));
964            err.note(
965                "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
966                for more information",
967            );
968
969            if flag == "no-defaults" || flag == "passes" {
970                err.help("you may want to use --document-private-items");
971            } else if flag == "plugins" || flag == "plugin-path" {
972                err.warn("see CVE-2018-1000622");
973            }
974
975            err.emit();
976        }
977    }
978}
979
980/// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
981/// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
982/// describing the issue.
983fn parse_extern_html_roots(
984    matches: &getopts::Matches,
985) -> Result<BTreeMap<String, String>, &'static str> {
986    let mut externs = BTreeMap::new();
987    for arg in &matches.opt_strs("extern-html-root-url") {
988        let (name, url) =
989            arg.split_once('=').ok_or("--extern-html-root-url must be of the form name=url")?;
990        externs.insert(name.to_string(), url.to_string());
991    }
992    Ok(externs)
993}
994
995/// Path directly to crate-info directory.
996///
997/// For example, `/home/user/project/target/doc.parts`.
998/// Each crate has its info stored in a file called `CRATENAME.json`.
999#[derive(Clone, Debug)]
1000pub(crate) struct PathToParts(pub(crate) PathBuf);
1001
1002impl PathToParts {
1003    fn from_flag(path: String) -> Result<PathToParts, String> {
1004        let path = PathBuf::from(path);
1005        // check here is for diagnostics
1006        if path.exists() && !path.is_dir() {
1007            Err(format!(
1008                "--parts-out-dir and --include-parts-dir expect directories, found: {}",
1009                path.display(),
1010            ))
1011        } else {
1012            // if it doesn't exist, we'll create it. worry about that in write_shared
1013            Ok(PathToParts(path))
1014        }
1015    }
1016}
1017
1018/// Reports error if --include-parts-dir is not a directory
1019fn parse_include_parts_dir(m: &getopts::Matches) -> Result<Vec<PathToParts>, String> {
1020    let mut ret = Vec::new();
1021    for p in m.opt_strs("include-parts-dir") {
1022        let p = PathToParts::from_flag(p)?;
1023        // this is just for diagnostic
1024        if !p.0.is_dir() {
1025            return Err(format!(
1026                "--include-parts-dir expected {} to be a directory",
1027                p.0.display()
1028            ));
1029        }
1030        ret.push(p);
1031    }
1032    Ok(ret)
1033}
1034
1035/// Controls merging of cross-crate information
1036#[derive(Debug, Clone)]
1037pub(crate) struct ShouldMerge {
1038    /// Should we append to existing cci in the doc root
1039    pub(crate) read_rendered_cci: bool,
1040    /// Should we write cci to the doc root
1041    pub(crate) write_rendered_cci: bool,
1042}
1043
1044/// Extracts read_rendered_cci and write_rendered_cci from command line arguments, or
1045/// reports an error if an invalid option was provided
1046fn parse_merge(m: &getopts::Matches) -> Result<ShouldMerge, &'static str> {
1047    match m.opt_str("merge").as_deref() {
1048        // default = read-write
1049        None => Ok(ShouldMerge { read_rendered_cci: true, write_rendered_cci: true }),
1050        Some("none") if m.opt_present("include-parts-dir") => {
1051            Err("--include-parts-dir not allowed if --merge=none")
1052        }
1053        Some("none") => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: false }),
1054        Some("shared") if m.opt_present("parts-out-dir") || m.opt_present("include-parts-dir") => {
1055            Err("--parts-out-dir and --include-parts-dir not allowed if --merge=shared")
1056        }
1057        Some("shared") => Ok(ShouldMerge { read_rendered_cci: true, write_rendered_cci: true }),
1058        Some("finalize") if m.opt_present("parts-out-dir") => {
1059            Err("--parts-out-dir not allowed if --merge=finalize")
1060        }
1061        Some("finalize") => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: true }),
1062        Some(_) => Err("argument to --merge must be `none`, `shared`, or `finalize`"),
1063    }
1064}
1065
1066fn parse_merge_doctests(
1067    m: &getopts::Matches,
1068    edition: Edition,
1069    dcx: DiagCtxtHandle<'_>,
1070) -> MergeDoctests {
1071    match m.opt_str("merge-doctests").as_deref() {
1072        Some("y") | Some("yes") | Some("on") | Some("true") => MergeDoctests::Always,
1073        Some("n") | Some("no") | Some("off") | Some("false") => MergeDoctests::Never,
1074        Some("auto") => MergeDoctests::Auto,
1075        None if edition < Edition::Edition2024 => MergeDoctests::Never,
1076        None => MergeDoctests::Auto,
1077        Some(_) => {
1078            dcx.fatal("argument to --merge-doctests must be a boolean (true/false) or 'auto'")
1079        }
1080    }
1081}