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