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 = compute_should_merge(matches);
617        if parts_out_dir.is_none() && include_parts_dir.is_empty() {
618            // we'll need to get rid of this stuff once Cargo stops using them
619            parts_out_dir =
620                match matches.opt_str("parts-out-dir").map(PathToParts::from_flag).transpose() {
621                    Ok(parts_out_dir) => parts_out_dir,
622                    Err(e) => dcx.fatal(e),
623                };
624            include_parts_dir = match parse_read_doc_meta(matches, "include-parts-dir") {
625                Ok(include_parts_dir) => include_parts_dir,
626                Err(e) => dcx.fatal(e),
627            };
628            should_merge = match matches.opt_str("merge").as_deref() {
629                None => ShouldMerge { read_rendered_cci: true, write_rendered_cci: true },
630                Some("none") => ShouldMerge { read_rendered_cci: false, write_rendered_cci: false },
631                Some("shared") => ShouldMerge { read_rendered_cci: true, write_rendered_cci: true },
632                Some("finalize") => {
633                    ShouldMerge { read_rendered_cci: false, write_rendered_cci: true }
634                }
635                Some(_) => dcx.fatal("argument to --merge must be `none`, `shared`, or `finalize`"),
636            };
637        } else if matches.opt_str("parts-out-dir").is_some() {
638            dcx.fatal(
639                "deprecated version of write-doc-meta-dir is used with new doc-meta-dir stuff",
640            );
641        } else if matches.opt_str("include-parts-dir").is_some() {
642            dcx.fatal(
643                "deprecated version of read-doc-meta-dir is used with new doc-meta-dir stuff",
644            );
645        } else if matches.opt_str("merge").is_some() {
646            dcx.fatal("deprecated parameter merge is used with new doc-meta-dir stuff");
647        }
648
649        let input = if describe_lints {
650            InputMode::HasFile(make_input(early_dcx, ""))
651        } else {
652            match matches.free.as_slice() {
653                [] if !include_parts_dir.is_empty() && should_merge.write_rendered_cci => {
654                    InputMode::NoInputMergeFinalize
655                }
656                [] => dcx.fatal("missing file operand"),
657                [input] => InputMode::HasFile(make_input(early_dcx, input)),
658                _ => dcx.fatal("too many file operands"),
659            }
660        };
661
662        let default_settings: Vec<Vec<(String, String)>> = vec![
663            matches
664                .opt_str("default-theme")
665                .iter()
666                .flat_map(|theme| {
667                    vec![
668                        ("use-system-theme".to_string(), "false".to_string()),
669                        ("theme".to_string(), theme.to_string()),
670                    ]
671                })
672                .collect(),
673            matches
674                .opt_strs("default-setting")
675                .iter()
676                .map(|s| match s.split_once('=') {
677                    None => (s.clone(), "true".to_string()),
678                    Some((k, v)) => (k.to_string(), v.to_string()),
679                })
680                .collect(),
681        ];
682        let default_settings = default_settings
683            .into_iter()
684            .flatten()
685            .map(
686                // The keys here become part of `data-` attribute names in the generated HTML.  The
687                // browser does a strange mapping when converting them into attributes on the
688                // `dataset` property on the DOM HTML Node:
689                //   https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
690                //
691                // The original key values we have are the same as the DOM storage API keys and the
692                // command line options, so contain `-`.  Our JavaScript needs to be able to look
693                // these values up both in `dataset` and in the storage API, so it needs to be able
694                // to convert the names back and forth.  Despite doing this kebab-case to
695                // StudlyCaps transformation automatically, the JS DOM API does not provide a
696                // mechanism for doing just the transformation on a string.  So we want to avoid
697                // the StudlyCaps representation in the `dataset` property.
698                //
699                // We solve this by replacing all the `-`s with `_`s.  We do that here, when we
700                // generate the `data-` attributes, and in the JS, when we look them up.  (See
701                // `getSettingValue` in `storage.js.`) Converting `-` to `_` is simple in JS.
702                //
703                // The values will be HTML-escaped by the default Tera escaping.
704                |(k, v)| (k.replace('-', "_"), v),
705            )
706            .collect();
707
708        let test_args = matches.opt_strs("test-args");
709        let test_args: Vec<String> =
710            test_args.iter().flat_map(|s| s.split_whitespace()).map(|s| s.to_string()).collect();
711
712        let no_run = matches.opt_present("no-run");
713
714        if !should_test && no_run {
715            dcx.fatal("the `--test` flag must be passed to enable `--no-run`");
716        }
717
718        let mut output_to_stdout = false;
719        let test_builder_wrappers =
720            matches.opt_strs("test-builder-wrapper").iter().map(PathBuf::from).collect();
721        let output = match (matches.opt_str("out-dir"), matches.opt_str("output")) {
722            (Some(_), Some(_)) => {
723                dcx.fatal("cannot use both 'out-dir' and 'output' at once");
724            }
725            (Some(out_dir), None) | (None, Some(out_dir)) => {
726                output_to_stdout = out_dir == "-";
727                PathBuf::from(out_dir)
728            }
729            (None, None) => PathBuf::from("doc"),
730        };
731
732        let cfgs = matches.opt_strs("cfg");
733        let check_cfgs = matches.opt_strs("check-cfg");
734
735        let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
736
737        let mut loaded_paths = Vec::new();
738
739        if let Some(ref p) = extension_css {
740            loaded_paths.push(p.clone());
741            if !p.is_file() {
742                dcx.fatal("option --extend-css argument must be a file");
743            }
744        }
745
746        let mut themes = Vec::new();
747        if matches.opt_present("theme") {
748            let mut content =
749                std::str::from_utf8(static_files::STATIC_FILES.rustdoc_css.src_bytes).unwrap();
750            if let Some((_, inside)) = content.split_once("/* Begin theme: light */") {
751                content = inside;
752            }
753            if let Some((inside, _)) = content.split_once("/* End theme: light */") {
754                content = inside;
755            }
756            let paths = match theme::load_css_paths(content) {
757                Ok(p) => p,
758                Err(e) => dcx.fatal(e),
759            };
760
761            for (theme_file, theme_s) in
762                matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
763            {
764                if !theme_file.is_file() {
765                    dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
766                        .with_help("arguments to --theme must be files")
767                        .emit();
768                }
769                if theme_file.extension() != Some(OsStr::new("css")) {
770                    dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
771                        .with_help("arguments to --theme must have a .css extension")
772                        .emit();
773                }
774                let (success, ret) = theme::test_theme_against(&theme_file, &paths, dcx);
775                if !success {
776                    dcx.fatal(format!("error loading theme file: \"{theme_s}\""));
777                } else if !ret.is_empty() {
778                    dcx.struct_warn(format!(
779                        "theme file \"{theme_s}\" is missing CSS rules from the default theme",
780                    ))
781                    .with_warn("the theme may appear incorrect when loaded")
782                    .with_help(format!(
783                        "to see what rules are missing, call `rustdoc --check-theme \"{theme_s}\"`",
784                    ))
785                    .emit();
786                }
787                loaded_paths.push(theme_file.clone());
788                themes.push(StylePath { path: theme_file });
789            }
790        }
791
792        let edition = config::parse_crate_edition(early_dcx, matches);
793
794        let mut id_map = html::markdown::IdMap::new();
795        let Some(external_html) = ExternalHtml::load(
796            &matches.opt_strs("html-in-header"),
797            &matches.opt_strs("html-before-content"),
798            &matches.opt_strs("html-after-content"),
799            &matches.opt_strs("markdown-before-content"),
800            &matches.opt_strs("markdown-after-content"),
801            nightly_options::match_is_nightly_build(matches),
802            dcx,
803            &mut id_map,
804            edition,
805            &None,
806            &mut loaded_paths,
807        ) else {
808            dcx.fatal("`ExternalHtml::load` failed");
809        };
810
811        match matches.opt_str("r").as_deref() {
812            Some("rust") | None => {}
813            Some(s) => dcx.fatal(format!("unknown input format: {s}")),
814        }
815
816        let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
817        if let Some(ref index_page) = index_page {
818            if index_page.is_file() {
819                loaded_paths.push(index_page.clone());
820            } else {
821                dcx.fatal("option `--index-page` argument must be a file");
822            }
823        }
824
825        let target = parse_target_triple(early_dcx, matches);
826        let sysroot = Sysroot::new(matches.opt_str("sysroot").map(PathBuf::from));
827
828        let libs = matches
829            .opt_strs("L")
830            .iter()
831            .map(|s| {
832                SearchPath::from_cli_opt(
833                    sysroot.path(),
834                    &target,
835                    early_dcx,
836                    s,
837                    #[allow(rustc::bad_opt_access)] // we have no `Session` here
838                    unstable_opts.unstable_options,
839                )
840            })
841            .collect();
842
843        let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
844            Ok(types) => types,
845            Err(e) => {
846                dcx.fatal(format!("unknown crate type: {e}"));
847            }
848        };
849
850        let bin_crate = crate_types.contains(&CrateType::Executable);
851        let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
852        let playground_url = matches.opt_str("playground-url");
853        let module_sorting = if matches.opt_present("sort-modules-by-appearance") {
854            ModuleSorting::DeclarationOrder
855        } else {
856            ModuleSorting::Alphabetical
857        };
858        let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
859        let markdown_no_toc = matches.opt_present("markdown-no-toc");
860        let markdown_css = matches.opt_strs("markdown-css");
861        let markdown_playground_url = matches.opt_str("markdown-playground-url");
862        let crate_version = matches.opt_str("crate-version");
863        let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
864        let static_root_path = matches.opt_str("static-root-path");
865        let test_run_directory = matches.opt_str("test-run-directory").map(PathBuf::from);
866        let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
867        let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
868        let codegen_options_strs = matches.opt_strs("C");
869        let unstable_opts_strs = matches.opt_strs("Z");
870        let lib_strs = matches.opt_strs("L");
871        let extern_strs = matches.opt_strs("extern");
872        let test_runtool = matches.opt_str("test-runtool");
873        let test_runtool_args = matches.opt_strs("test-runtool-arg");
874        let document_private = matches.opt_present("document-private-items");
875        let document_hidden = matches.opt_present("document-hidden-items");
876        let run_check = matches.opt_present("check");
877        let generate_redirect_map = matches.opt_present("generate-redirect-map");
878        let show_type_layout = matches.opt_present("show-type-layout");
879        let no_capture = matches.opt_present("no-capture");
880        let generate_link_to_definition = matches.opt_present("generate-link-to-definition");
881        let generate_macro_expansion = matches.opt_present("generate-macro-expansion");
882        let extern_html_root_takes_precedence =
883            matches.opt_present("extern-html-root-takes-precedence");
884        let html_no_source = matches.opt_present("html-no-source");
885        let merge_doctests = parse_merge_doctests(matches, edition, dcx);
886        tracing::debug!("merge_doctests: {merge_doctests:?}");
887
888        if generate_link_to_definition && (show_coverage || output_format != OutputFormat::Html) {
889            dcx.struct_warn(
890                "`--generate-link-to-definition` option can only be used with HTML output format",
891            )
892            .with_note("`--generate-link-to-definition` option will be ignored")
893            .emit();
894        }
895        if generate_macro_expansion && (show_coverage || output_format != OutputFormat::Html) {
896            dcx.struct_warn(
897                "`--generate-macro-expansion` option can only be used with HTML output format",
898            )
899            .with_note("`--generate-macro-expansion` option will be ignored")
900            .emit();
901        }
902
903        let scrape_examples_options = ScrapeExamplesOptions::new(matches, dcx);
904        let with_examples = matches.opt_strs("with-examples");
905        let call_locations =
906            crate::scrape_examples::load_call_locations(with_examples, dcx, &mut loaded_paths);
907        let doctest_build_args = matches.opt_strs("doctest-build-arg");
908
909        let disable_minification = matches.opt_present("disable-minification");
910
911        let options = Options {
912            bin_crate,
913            proc_macro_crate,
914            error_format,
915            diagnostic_width,
916            libs,
917            lib_strs,
918            externs,
919            extern_strs,
920            cfgs,
921            check_cfgs,
922            codegen_options,
923            codegen_options_strs,
924            unstable_opts,
925            unstable_opts_strs,
926            target,
927            edition,
928            sysroot,
929            lint_opts,
930            describe_lints,
931            lint_cap,
932            should_test,
933            test_args,
934            show_coverage,
935            crate_version,
936            test_run_directory,
937            persist_doctests,
938            merge_doctests,
939            test_runtool,
940            test_runtool_args,
941            test_builder,
942            run_check,
943            no_run,
944            test_builder_wrappers,
945            remap_path_prefix,
946            remap_path_scope,
947            no_capture,
948            crate_name,
949            output_format,
950            json_unused_externs,
951            scrape_examples_options,
952            unstable_features,
953            doctest_build_args,
954            target_modifiers: collected_options.target_modifiers,
955        };
956        let render_options = RenderOptions {
957            output,
958            external_html,
959            id_map,
960            playground_url,
961            module_sorting,
962            themes,
963            extension_css,
964            extern_html_root_urls,
965            extern_html_root_takes_precedence,
966            default_settings,
967            resource_suffix,
968            enable_index_page,
969            index_page,
970            static_root_path,
971            markdown_no_toc,
972            markdown_css,
973            markdown_playground_url,
974            document_private,
975            document_hidden,
976            generate_redirect_map,
977            show_type_layout,
978            unstable_features,
979            emit,
980            generate_link_to_definition,
981            generate_macro_expansion,
982            call_locations,
983            no_emit_shared: false,
984            html_no_source,
985            output_to_stdout,
986            should_merge,
987            include_parts_dir,
988            parts_out_dir,
989            disable_minification,
990        };
991        Some((input, options, render_options, loaded_paths))
992    }
993}
994
995/// Returns `true` if the file given as `self.input` is a Markdown file.
996pub(crate) fn markdown_input(input: &Input) -> Option<&Path> {
997    input.opt_path().filter(|p| matches!(p.extension(), Some(e) if e == "md" || e == "markdown"))
998}
999
1000fn parse_remap_path_prefix(
1001    matches: &getopts::Matches,
1002) -> Result<Vec<(PathBuf, PathBuf)>, &'static str> {
1003    matches
1004        .opt_strs("remap-path-prefix")
1005        .into_iter()
1006        .map(|remap| {
1007            remap
1008                .rsplit_once('=')
1009                .ok_or("--remap-path-prefix must contain '=' between FROM and TO")
1010                .map(|(from, to)| (PathBuf::from(from), PathBuf::from(to)))
1011        })
1012        .collect()
1013}
1014
1015/// Prints deprecation warnings for deprecated options
1016fn check_deprecated_options(matches: &getopts::Matches, dcx: DiagCtxtHandle<'_>) {
1017    let deprecated_flags = [];
1018
1019    for &flag in deprecated_flags.iter() {
1020        if matches.opt_present(flag) {
1021            dcx.struct_warn(format!("the `{flag}` flag is deprecated"))
1022                .with_note(
1023                    "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
1024                    for more information",
1025                )
1026                .emit();
1027        }
1028    }
1029
1030    let removed_flags = ["plugins", "plugin-path", "no-defaults", "passes", "input-format"];
1031
1032    for &flag in removed_flags.iter() {
1033        if matches.opt_present(flag) {
1034            let mut err = dcx.struct_warn(format!("the `{flag}` flag no longer functions"));
1035            err.note(
1036                "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
1037                for more information",
1038            );
1039
1040            if flag == "no-defaults" || flag == "passes" {
1041                err.help("you may want to use --document-private-items");
1042            } else if flag == "plugins" || flag == "plugin-path" {
1043                err.warn("see CVE-2018-1000622");
1044            }
1045
1046            err.emit();
1047        }
1048    }
1049}
1050
1051/// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
1052/// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
1053/// describing the issue.
1054fn parse_extern_html_roots(
1055    matches: &getopts::Matches,
1056) -> Result<BTreeMap<String, String>, &'static str> {
1057    let mut externs = BTreeMap::new();
1058    for arg in &matches.opt_strs("extern-html-root-url") {
1059        let (name, url) =
1060            arg.split_once('=').ok_or("--extern-html-root-url must be of the form name=url")?;
1061        externs.insert(name.to_string(), url.to_string());
1062    }
1063    Ok(externs)
1064}
1065
1066/// Path directly to crate-info directory.
1067///
1068/// For example, `/home/user/project/target/doc.parts`.
1069/// Each crate has its info stored in a file called `CRATENAME.json`.
1070#[derive(Clone, Debug)]
1071pub(crate) struct PathToParts(pub(crate) PathBuf);
1072
1073impl PathToParts {
1074    fn from_flag(path: String) -> Result<PathToParts, String> {
1075        let path = PathBuf::from(path);
1076        // check here is for diagnostics
1077        if path.exists() && !path.is_dir() {
1078            Err(format!(
1079                "--write-doc-meta-dir and --read-doc-meta-dir expect directories, found: {}",
1080                path.display(),
1081            ))
1082        } else {
1083            // if it doesn't exist, we'll create it. worry about that in write_shared
1084            Ok(PathToParts(path))
1085        }
1086    }
1087}
1088
1089/// Reports error if --read-doc-meta-dir is not a directory
1090fn parse_read_doc_meta(m: &getopts::Matches, name: &str) -> Result<Vec<PathToParts>, String> {
1091    let mut ret = Vec::new();
1092    for p in m.opt_strs(name) {
1093        let p = PathToParts::from_flag(p)?;
1094        // this is just for diagnostic
1095        if !p.0.is_dir() {
1096            return Err(format!(
1097                "--read-doc-meta-dir expected {} to be a directory",
1098                p.0.display()
1099            ));
1100        }
1101        ret.push(p);
1102    }
1103    Ok(ret)
1104}
1105
1106/// Controls merging of cross-crate information
1107#[derive(Debug, Clone)]
1108pub(crate) struct ShouldMerge {
1109    /// Should we append to existing cci in the doc root
1110    pub(crate) read_rendered_cci: bool,
1111    /// Should we write cci to the doc root
1112    pub(crate) write_rendered_cci: bool,
1113}
1114
1115/// Extracts read_rendered_cci and write_rendered_cci from command line arguments, or
1116/// reports an error if an invalid option was provided
1117fn compute_should_merge(m: &getopts::Matches) -> ShouldMerge {
1118    match (m.opt_present("read-doc-meta-dir"), m.opt_present("write-doc-meta-dir")) {
1119        // shared mode
1120        (false, false) => ShouldMerge { read_rendered_cci: true, write_rendered_cci: true },
1121        // intermediate mode
1122        (false, true) => ShouldMerge { read_rendered_cci: false, write_rendered_cci: false },
1123        // finalize mode
1124        (true, false) => ShouldMerge { read_rendered_cci: false, write_rendered_cci: true },
1125        (true, true) => ShouldMerge { read_rendered_cci: false, write_rendered_cci: true },
1126    }
1127}
1128
1129fn parse_merge_doctests(
1130    m: &getopts::Matches,
1131    edition: Edition,
1132    dcx: DiagCtxtHandle<'_>,
1133) -> MergeDoctests {
1134    match m.opt_str("merge-doctests").as_deref() {
1135        Some("y") | Some("yes") | Some("on") | Some("true") => MergeDoctests::Always,
1136        Some("n") | Some("no") | Some("off") | Some("false") => MergeDoctests::Never,
1137        Some("auto") => MergeDoctests::Auto,
1138        None if edition < Edition::Edition2024 => MergeDoctests::Never,
1139        None => MergeDoctests::Auto,
1140        Some(_) => {
1141            dcx.fatal("argument to --merge-doctests must be a boolean (true/false) or 'auto'")
1142        }
1143    }
1144}