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