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