Skip to main content

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_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    /// `--output-format=json` without `--show-coverage`.
36    ///
37    /// JSON description of crate API.
38    IrJson,
39    /// `--output-format=json` with `--show-coverage`.
40    CoverageJson,
41    Html,
42    Doctest,
43}
44
45/// Either an input crate, markdown file, or nothing (--merge=finalize).
46pub(crate) enum InputMode {
47    /// The `--merge=finalize` step does not need an input crate to rustdoc.
48    NoInputMergeFinalize,
49    /// A crate or markdown file.
50    HasFile(Input),
51}
52
53/// Whether to run multiple doctests in the same binary.
54#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
55pub(crate) enum MergeDoctests {
56    #[default]
57    Never,
58    Always,
59    Auto,
60}
61
62/// Configuration options for rustdoc.
63#[derive(Clone)]
64pub(crate) struct Options {
65    // Basic options / Options passed directly to rustc
66    /// The name of the crate being documented.
67    pub(crate) crate_name: Option<String>,
68    /// Whether or not this is a bin crate
69    pub(crate) bin_crate: bool,
70    /// Whether or not this is a proc-macro crate
71    pub(crate) proc_macro_crate: bool,
72    /// How to format errors and warnings.
73    pub(crate) error_format: ErrorOutputType,
74    /// Width of output buffer to truncate errors appropriately.
75    pub(crate) diagnostic_width: Option<usize>,
76    /// Library search paths to hand to the compiler.
77    pub(crate) libs: Vec<SearchPath>,
78    /// Library search paths strings to hand to the compiler.
79    pub(crate) lib_strs: Vec<String>,
80    /// The list of external crates to link against.
81    pub(crate) externs: Externs,
82    /// The list of external crates strings to link against.
83    pub(crate) extern_strs: Vec<String>,
84    /// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`.
85    pub(crate) cfgs: Vec<String>,
86    /// List of check cfg flags to hand to the compiler.
87    pub(crate) check_cfgs: Vec<String>,
88    /// Codegen options to hand to the compiler.
89    pub(crate) codegen_options: CodegenOptions,
90    /// Codegen options strings to hand to the compiler.
91    pub(crate) codegen_options_strs: Vec<String>,
92    /// Unstable (`-Z`) options to pass to the compiler.
93    pub(crate) unstable_opts: UnstableOptions,
94    /// Unstable (`-Z`) options strings to pass to the compiler.
95    pub(crate) unstable_opts_strs: Vec<String>,
96    /// The target used to compile the crate against.
97    pub(crate) target: TargetTuple,
98    /// Edition used when reading the crate. Defaults to "2015". Also used by default when
99    /// compiling doctests from the crate.
100    pub(crate) edition: Edition,
101    /// The path to the sysroot. Used during the compilation process.
102    pub(crate) sysroot: Sysroot,
103    /// Lint information passed over the command-line.
104    pub(crate) lint_opts: Vec<(String, Level)>,
105    /// Whether to ask rustc to describe the lints it knows.
106    pub(crate) describe_lints: bool,
107    /// What level to cap lints at.
108    pub(crate) lint_cap: Option<Level>,
109    /// Print requests to hand to the compiler.
110    pub(crate) prints: Vec<PrintRequest>,
111
112    // Options specific to running doctests
113    /// Whether we should run doctests instead of generating docs.
114    pub(crate) should_test: bool,
115    /// List of arguments to pass to the test harness, if running tests.
116    pub(crate) test_args: Vec<String>,
117    /// The working directory in which to run tests.
118    pub(crate) test_run_directory: Option<PathBuf>,
119    /// Optional path to persist the doctest executables to, defaults to a
120    /// temporary directory if not set.
121    pub(crate) persist_doctests: Option<PathBuf>,
122    /// Whether to merge
123    pub(crate) merge_doctests: MergeDoctests,
124    /// Runtool to run doctests with
125    pub(crate) test_runtool: Option<String>,
126    /// Arguments to pass to the runtool
127    pub(crate) test_runtool_args: Vec<String>,
128    /// Do not run doctests, compile them if should_test is active.
129    pub(crate) no_run: bool,
130    /// What sources are being mapped.
131    pub(crate) remap_path_prefix: Vec<(PathBuf, PathBuf)>,
132    pub(crate) remap_path_prefix_strs: Vec<String>,
133    /// Which scope(s) to use with `--remap-path-prefix`
134    pub(crate) remap_path_scope: RemapPathScopeComponents,
135    pub(crate) remap_path_scope_str: Option<String>,
136
137    /// The path to a rustc-like binary to build tests with. If not set, we
138    /// default to loading from `$sysroot/bin/rustc`.
139    pub(crate) test_builder: Option<PathBuf>,
140
141    /// Run these wrapper instead of rustc directly
142    pub(crate) test_builder_wrappers: Vec<PathBuf>,
143
144    // Options that affect the documentation process
145    /// Whether to run the `calculate-doc-coverage` pass, which counts the number of public items
146    /// with and without documentation.
147    pub(crate) show_coverage: bool,
148
149    // Options that alter generated documentation pages
150    /// Crate version to note on the sidebar of generated docs.
151    pub(crate) crate_version: Option<String>,
152    /// The format that we output when rendering.
153    ///
154    /// Currently used only for the `--show-coverage` option.
155    pub(crate) output_format: OutputFormat,
156    /// If this option is set to `true`, rustdoc will only run checks and not generate
157    /// documentation.
158    pub(crate) run_check: bool,
159    /// Whether doctests should emit unused externs
160    pub(crate) json_unused_externs: JsonUnusedExterns,
161    /// Whether to skip capturing stdout and stderr of tests.
162    pub(crate) no_capture: bool,
163
164    /// Configuration for scraping examples from the current crate. If this option is Some(..) then
165    /// the compiler will scrape examples and not generate documentation.
166    pub(crate) scrape_examples_options: Option<ScrapeExamplesOptions>,
167
168    /// Note: this field is duplicated in `RenderOptions` because it's useful
169    /// to have it in both places.
170    pub(crate) unstable_features: rustc_feature::UnstableFeatures,
171
172    /// Arguments to be used when compiling doctests.
173    pub(crate) doctest_build_args: Vec<String>,
174
175    /// Target modifiers.
176    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/// Configuration options for the HTML page-creation process.
228#[derive(Clone, Debug)]
229pub(crate) struct RenderOptions {
230    /// Output directory to generate docs into. Defaults to `doc`.
231    pub(crate) output: PathBuf,
232    /// External files to insert into generated pages.
233    pub(crate) external_html: ExternalHtml,
234    /// A pre-populated `IdMap` with the default headings and any headings added by Markdown files
235    /// processed by `external_html`.
236    pub(crate) id_map: IdMap,
237    /// If present, playground URL to use in the "Run" button added to code samples.
238    ///
239    /// Be aware: This option can come both from the CLI and from crate attributes!
240    pub(crate) playground_url: Option<String>,
241    /// What sorting mode to use for module pages.
242    /// `ModuleSorting::Alphabetical` by default.
243    pub(crate) module_sorting: ModuleSorting,
244    /// List of themes to extend the docs with. Original argument name is included to assist in
245    /// displaying errors if it fails a theme check.
246    pub(crate) themes: Vec<StylePath>,
247    /// If present, CSS file that contains rules to add to the default CSS.
248    pub(crate) extension_css: Option<PathBuf>,
249    /// A map of crate names to the URL to use instead of querying the crate's `html_root_url`.
250    pub(crate) extern_html_root_urls: BTreeMap<String, String>,
251    /// Whether to give precedence to `html_root_url` or `--extern-html-root-url`.
252    pub(crate) extern_html_root_takes_precedence: bool,
253    /// A map of the default settings (values are as for DOM storage API). Keys should lack the
254    /// `rustdoc-` prefix.
255    pub(crate) default_settings: FxIndexMap<String, String>,
256    /// If present, suffix added to CSS/JavaScript files when referencing them in generated pages.
257    pub(crate) resource_suffix: String,
258    /// Whether to create an index page in the root of the output directory. If this is true but
259    /// `enable_index_page` is None, generate a static listing of crates instead.
260    pub(crate) enable_index_page: bool,
261    /// A file to use as the index page at the root of the output directory. Overrides
262    /// `enable_index_page` to be true if set.
263    pub(crate) index_page: Option<PathBuf>,
264    /// An optional path to use as the location of static files. If not set, uses combinations of
265    /// `../` to reach the documentation root.
266    pub(crate) static_root_path: Option<String>,
267
268    // Options specific to reading standalone Markdown files
269    /// Whether to generate a table of contents on the output file when reading a standalone
270    /// Markdown file.
271    pub(crate) markdown_no_toc: bool,
272    /// Additional CSS files to link in pages generated from standalone Markdown files.
273    pub(crate) markdown_css: Vec<String>,
274    /// If present, playground URL to use in the "Run" button added to code samples generated from
275    /// standalone Markdown files. If not present, `playground_url` is used.
276    pub(crate) markdown_playground_url: Option<String>,
277    /// Document items that have lower than `pub` visibility.
278    pub(crate) document_private: bool,
279    /// Document items that have `doc(hidden)`.
280    pub(crate) document_hidden: bool,
281    /// If `true`, generate a JSON file in the crate folder instead of HTML redirection files.
282    pub(crate) generate_redirect_map: bool,
283    /// Show the memory layout of types in the docs.
284    pub(crate) show_type_layout: bool,
285    /// Note: this field is duplicated in `Options` because it's useful to have
286    /// it in both places.
287    pub(crate) unstable_features: rustc_feature::UnstableFeatures,
288    pub(crate) emit: SmallVec<[EmitType; 2]>,
289    /// If `true`, HTML source pages will generate links for items to their definition.
290    pub(crate) generate_link_to_definition: bool,
291    /// Set of function-call locations to include as examples
292    pub(crate) call_locations: AllCallLocations,
293    /// If `true`, Context::init will not emit shared files.
294    pub(crate) no_emit_shared: bool,
295    /// If `true`, HTML source code pages won't be generated.
296    pub(crate) html_no_source: bool,
297    /// This field is only used for the JSON output. If it's set to true, no file will be created
298    /// and content will be displayed in stdout directly.
299    pub(crate) output_to_stdout: bool,
300    /// Whether we should read or write rendered cross-crate info in the doc root.
301    pub(crate) should_merge: ShouldMerge,
302    /// Path to crate-info for external crates.
303    pub(crate) include_parts_dir: Vec<PathToParts>,
304    /// Where to write crate-info
305    pub(crate) parts_out_dir: Option<PathToParts>,
306    /// disable minification of CSS/JS
307    pub(crate) disable_minification: bool,
308    /// If `true`, HTML source pages will generate the possibility to expand macros.
309    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    // not explicitly nameable by the user for now
323    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
366/// Create the input (string or file path)
367///
368/// Warning: Return an unrecoverable error in case of error!
369fn 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            // Immediately stop compilation if there was an issue reading
374            // the input (for example if the input stream is not UTF-8).
375            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    /// Parses the given command-line for options. If an error message or other early-return has
385    /// been printed, returns `Err` with the exit code.
386    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        // Check for unstable options.
392        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 for deprecated options
433        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        // check for `--output-format` stability, and compatibility with `--show-coverage`
452        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            // If `-Zunstable-options` is used, nothing to check after this point.
465            (_, 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                // De-duplicate emit types and the last wins.
513                // Only one instance for each type is allowed
514                // regardless the actual data it carries.
515                // This matches rustc's `--emit` behavior.
516                emit.insert(std::mem::discriminant(&typ), typ);
517            }
518        }
519        let mut emit: SmallVec<[_; 2]> = emit.into_values().collect();
520        // If `--emit` is absent we'll register default emission types depending on the requested
521        // output format. We can safely use `is_empty` for this since `--emit=` ("truly empty")
522        // will have already been rejected above.
523        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            // we'll need to get rid of this stuff once Cargo stops using them
602            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                // The keys here become part of `data-` attribute names in the generated HTML.  The
670                // browser does a strange mapping when converting them into attributes on the
671                // `dataset` property on the DOM HTML Node:
672                //   https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
673                //
674                // The original key values we have are the same as the DOM storage API keys and the
675                // command line options, so contain `-`.  Our JavaScript needs to be able to look
676                // these values up both in `dataset` and in the storage API, so it needs to be able
677                // to convert the names back and forth.  Despite doing this kebab-case to
678                // StudlyCaps transformation automatically, the JS DOM API does not provide a
679                // mechanism for doing just the transformation on a string.  So we want to avoid
680                // the StudlyCaps representation in the `dataset` property.
681                //
682                // We solve this by replacing all the `-`s with `_`s.  We do that here, when we
683                // generate the `data-` attributes, and in the JS, when we look them up.  (See
684                // `getSettingValue` in `storage.js.`) Converting `-` to `_` is simple in JS.
685                //
686                // The values will be HTML-escaped by the default Tera escaping.
687                |(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                    // If no `-o` option is given and we're in the `--show-coverage` mode, by
715                    // default we print on the stdout.
716                    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)] // we have no `Session` here
828                    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
990/// Returns `true` if the file given as `self.input` is a Markdown file.
991pub(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
1010/// Prints deprecation warnings for deprecated options
1011fn 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
1046/// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
1047/// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
1048/// describing the issue.
1049fn 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/// Path directly to crate-info directory.
1062///
1063/// For example, `/home/user/project/target/doc.parts`.
1064/// Each crate has its info stored in a file called `CRATENAME.json`.
1065#[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        // check here is for diagnostics
1072        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            // if it doesn't exist, we'll create it. worry about that in write_shared
1079            Ok(PathToParts(path))
1080        }
1081    }
1082}
1083
1084/// Reports error if --read-doc-meta-dir is not a directory
1085fn 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        // this is just for diagnostic
1090        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/// Controls merging of cross-crate information
1102#[derive(Debug, Clone)]
1103pub(crate) struct ShouldMerge {
1104    /// Should we append to existing cci in the doc root
1105    pub(crate) read_rendered_cci: bool,
1106    /// Should we write cci to the doc root
1107    pub(crate) write_rendered_cci: bool,
1108}
1109
1110/// Extracts read_rendered_cci and write_rendered_cci from command line arguments, or
1111/// reports an error if an invalid option was provided
1112fn 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        // shared mode
1115        (false, false) => Ok(ShouldMerge { read_rendered_cci: true, write_rendered_cci: true }),
1116        // intermediate mode
1117        (false, true) => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: false }),
1118        // finalize mode
1119        (true, false) => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: true }),
1120        // not valid
1121        (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}