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::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    /// Arguments to be used when compiling doctests.
169    pub(crate) doctest_build_args: Vec<String>,
170
171    /// Target modifiers.
172    pub(crate) target_modifiers: BTreeMap<OptionsTargetModifiers, String>,
173}
174
175impl fmt::Debug for Options {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        struct FmtExterns<'a>(&'a Externs);
178
179        impl fmt::Debug for FmtExterns<'_> {
180            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181                f.debug_map().entries(self.0.iter()).finish()
182            }
183        }
184
185        f.debug_struct("Options")
186            .field("crate_name", &self.crate_name)
187            .field("bin_crate", &self.bin_crate)
188            .field("proc_macro_crate", &self.proc_macro_crate)
189            .field("error_format", &self.error_format)
190            .field("libs", &self.libs)
191            .field("externs", &FmtExterns(&self.externs))
192            .field("cfgs", &self.cfgs)
193            .field("check-cfgs", &self.check_cfgs)
194            .field("codegen_options", &"...")
195            .field("unstable_options", &"...")
196            .field("target", &self.target)
197            .field("edition", &self.edition)
198            .field("sysroot", &self.sysroot)
199            .field("lint_opts", &self.lint_opts)
200            .field("describe_lints", &self.describe_lints)
201            .field("lint_cap", &self.lint_cap)
202            .field("should_test", &self.should_test)
203            .field("test_args", &self.test_args)
204            .field("test_run_directory", &self.test_run_directory)
205            .field("persist_doctests", &self.persist_doctests)
206            .field("show_coverage", &self.show_coverage)
207            .field("crate_version", &self.crate_version)
208            .field("test_runtool", &self.test_runtool)
209            .field("test_runtool_args", &self.test_runtool_args)
210            .field("run_check", &self.run_check)
211            .field("no_run", &self.no_run)
212            .field("test_builder_wrappers", &self.test_builder_wrappers)
213            .field("remap-file-prefix", &self.remap_path_prefix)
214            .field("nocapture", &self.nocapture)
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: Vec<EmitType>,
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    Unversioned,
315    Toolchain,
316    InvocationSpecific,
317    DepInfo(Option<OutFileName>),
318}
319
320impl FromStr for EmitType {
321    type Err = ();
322
323    fn from_str(s: &str) -> Result<Self, Self::Err> {
324        match s {
325            "unversioned-shared-resources" => Ok(Self::Unversioned),
326            "toolchain-shared-resources" => Ok(Self::Toolchain),
327            "invocation-specific" => Ok(Self::InvocationSpecific),
328            "dep-info" => Ok(Self::DepInfo(None)),
329            option => match option.strip_prefix("dep-info=") {
330                Some("-") => Ok(Self::DepInfo(Some(OutFileName::Stdout))),
331                Some(f) => Ok(Self::DepInfo(Some(OutFileName::Real(f.into())))),
332                None => Err(()),
333            },
334        }
335    }
336}
337
338impl RenderOptions {
339    pub(crate) fn should_emit_crate(&self) -> bool {
340        self.emit.is_empty() || self.emit.contains(&EmitType::InvocationSpecific)
341    }
342
343    pub(crate) fn dep_info(&self) -> Option<Option<&OutFileName>> {
344        for emit in &self.emit {
345            if let EmitType::DepInfo(file) = emit {
346                return Some(file.as_ref());
347            }
348        }
349        None
350    }
351}
352
353/// Create the input (string or file path)
354///
355/// Warning: Return an unrecoverable error in case of error!
356fn make_input(early_dcx: &EarlyDiagCtxt, input: &str) -> Input {
357    if input == "-" {
358        let mut src = String::new();
359        if io::stdin().read_to_string(&mut src).is_err() {
360            // Immediately stop compilation if there was an issue reading
361            // the input (for example if the input stream is not UTF-8).
362            early_dcx.early_fatal("couldn't read from stdin, as it did not contain valid UTF-8");
363        }
364        Input::Str { name: FileName::anon_source_code(&src), input: src }
365    } else {
366        Input::File(PathBuf::from(input))
367    }
368}
369
370impl Options {
371    /// Parses the given command-line for options. If an error message or other early-return has
372    /// been printed, returns `Err` with the exit code.
373    pub(crate) fn from_matches(
374        early_dcx: &mut EarlyDiagCtxt,
375        matches: &getopts::Matches,
376        args: Vec<String>,
377    ) -> Option<(InputMode, Options, RenderOptions, Vec<PathBuf>)> {
378        // Check for unstable options.
379        nightly_options::check_nightly_options(early_dcx, matches, &opts());
380
381        if args.is_empty() || matches.opt_present("h") || matches.opt_present("help") {
382            crate::usage("rustdoc");
383            return None;
384        } else if matches.opt_present("version") {
385            rustc_driver::version!(&early_dcx, "rustdoc", matches);
386            return None;
387        }
388
389        if rustc_driver::describe_flag_categories(early_dcx, matches) {
390            return None;
391        }
392
393        let color = config::parse_color(early_dcx, matches);
394        let config::JsonConfig { json_rendered, json_unused_externs, json_color, .. } =
395            config::parse_json(early_dcx, matches);
396        let error_format =
397            config::parse_error_format(early_dcx, matches, color, json_color, json_rendered);
398        let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_default();
399
400        let mut target_modifiers = BTreeMap::<OptionsTargetModifiers, String>::new();
401        let codegen_options = CodegenOptions::build(early_dcx, matches, &mut target_modifiers);
402        let unstable_opts = UnstableOptions::build(early_dcx, matches, &mut target_modifiers);
403
404        let remap_path_prefix = match parse_remap_path_prefix(matches) {
405            Ok(prefix_mappings) => prefix_mappings,
406            Err(err) => {
407                early_dcx.early_fatal(err);
408            }
409        };
410
411        let dcx = new_dcx(error_format, None, diagnostic_width, &unstable_opts);
412        let dcx = dcx.handle();
413
414        // check for deprecated options
415        check_deprecated_options(matches, dcx);
416
417        if matches.opt_strs("passes") == ["list"] {
418            println!("Available passes for running rustdoc:");
419            for pass in passes::PASSES {
420                println!("{:>20} - {}", pass.name, pass.description);
421            }
422            println!("\nDefault passes for rustdoc:");
423            for p in passes::DEFAULT_PASSES {
424                print!("{:>20}", p.pass.name);
425                println_condition(p.condition);
426            }
427
428            if nightly_options::match_is_nightly_build(matches) {
429                println!("\nPasses run with `--show-coverage`:");
430                for p in passes::COVERAGE_PASSES {
431                    print!("{:>20}", p.pass.name);
432                    println_condition(p.condition);
433                }
434            }
435
436            fn println_condition(condition: Condition) {
437                use Condition::*;
438                match condition {
439                    Always => println!(),
440                    WhenDocumentPrivate => println!("  (when --document-private-items)"),
441                    WhenNotDocumentPrivate => println!("  (when not --document-private-items)"),
442                    WhenNotDocumentHidden => println!("  (when not --document-hidden-items)"),
443                }
444            }
445
446            return None;
447        }
448
449        let mut emit = FxIndexMap::<_, EmitType>::default();
450        for list in matches.opt_strs("emit") {
451            for kind in list.split(',') {
452                match kind.parse() {
453                    Ok(kind) => {
454                        // De-duplicate emit types and the last wins.
455                        // Only one instance for each type is allowed
456                        // regardless the actual data it carries.
457                        // This matches rustc's `--emit` behavior.
458                        emit.insert(std::mem::discriminant(&kind), kind);
459                    }
460                    Err(()) => dcx.fatal(format!("unrecognized emission type: {kind}")),
461                }
462            }
463        }
464        let emit = emit.into_values().collect::<Vec<_>>();
465
466        let show_coverage = matches.opt_present("show-coverage");
467        let output_format_s = matches.opt_str("output-format");
468        let output_format = match output_format_s {
469            Some(ref s) => match OutputFormat::try_from(s.as_str()) {
470                Ok(out_fmt) => out_fmt,
471                Err(e) => dcx.fatal(e),
472            },
473            None => OutputFormat::default(),
474        };
475
476        // check for `--output-format=json`
477        match (
478            output_format_s.as_ref().map(|_| output_format),
479            show_coverage,
480            nightly_options::is_unstable_enabled(matches),
481        ) {
482            (None | Some(OutputFormat::Json), true, _) => {}
483            (_, true, _) => {
484                dcx.fatal(format!(
485                    "`--output-format={}` is not supported for the `--show-coverage` option",
486                    output_format_s.unwrap_or_default(),
487                ));
488            }
489            // If `-Zunstable-options` is used, nothing to check after this point.
490            (_, false, true) => {}
491            (None | Some(OutputFormat::Html), false, _) => {}
492            (Some(OutputFormat::Json), false, false) => {
493                dcx.fatal(
494                    "the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/76578)",
495                );
496            }
497            (Some(OutputFormat::Doctest), false, false) => {
498                dcx.fatal(
499                    "the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/134529)",
500                );
501            }
502        }
503
504        let to_check = matches.opt_strs("check-theme");
505        if !to_check.is_empty() {
506            let mut content =
507                std::str::from_utf8(static_files::STATIC_FILES.rustdoc_css.src_bytes).unwrap();
508            if let Some((_, inside)) = content.split_once("/* Begin theme: light */") {
509                content = inside;
510            }
511            if let Some((inside, _)) = content.split_once("/* End theme: light */") {
512                content = inside;
513            }
514            let paths = match theme::load_css_paths(content) {
515                Ok(p) => p,
516                Err(e) => dcx.fatal(e),
517            };
518            let mut errors = 0;
519
520            println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
521            for theme_file in to_check.iter() {
522                print!(" - Checking \"{theme_file}\"...");
523                let (success, differences) = theme::test_theme_against(theme_file, &paths, dcx);
524                if !differences.is_empty() || !success {
525                    println!(" FAILED");
526                    errors += 1;
527                    if !differences.is_empty() {
528                        println!("{}", differences.join("\n"));
529                    }
530                } else {
531                    println!(" OK");
532                }
533            }
534            if errors != 0 {
535                dcx.fatal("[check-theme] one or more tests failed");
536            }
537            return None;
538        }
539
540        let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(early_dcx, matches);
541
542        let input = if describe_lints {
543            InputMode::HasFile(make_input(early_dcx, ""))
544        } else {
545            match matches.free.as_slice() {
546                [] if matches.opt_str("merge").as_deref() == Some("finalize") => {
547                    InputMode::NoInputMergeFinalize
548                }
549                [] => dcx.fatal("missing file operand"),
550                [input] => InputMode::HasFile(make_input(early_dcx, input)),
551                _ => dcx.fatal("too many file operands"),
552            }
553        };
554
555        let externs = parse_externs(early_dcx, matches, &unstable_opts);
556        let extern_html_root_urls = match parse_extern_html_roots(matches) {
557            Ok(ex) => ex,
558            Err(err) => dcx.fatal(err),
559        };
560
561        let parts_out_dir =
562            match matches.opt_str("parts-out-dir").map(PathToParts::from_flag).transpose() {
563                Ok(parts_out_dir) => parts_out_dir,
564                Err(e) => dcx.fatal(e),
565            };
566        let include_parts_dir = match parse_include_parts_dir(matches) {
567            Ok(include_parts_dir) => include_parts_dir,
568            Err(e) => dcx.fatal(e),
569        };
570
571        let default_settings: Vec<Vec<(String, String)>> = vec![
572            matches
573                .opt_str("default-theme")
574                .iter()
575                .flat_map(|theme| {
576                    vec![
577                        ("use-system-theme".to_string(), "false".to_string()),
578                        ("theme".to_string(), theme.to_string()),
579                    ]
580                })
581                .collect(),
582            matches
583                .opt_strs("default-setting")
584                .iter()
585                .map(|s| match s.split_once('=') {
586                    None => (s.clone(), "true".to_string()),
587                    Some((k, v)) => (k.to_string(), v.to_string()),
588                })
589                .collect(),
590        ];
591        let default_settings = default_settings
592            .into_iter()
593            .flatten()
594            .map(
595                // The keys here become part of `data-` attribute names in the generated HTML.  The
596                // browser does a strange mapping when converting them into attributes on the
597                // `dataset` property on the DOM HTML Node:
598                //   https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
599                //
600                // The original key values we have are the same as the DOM storage API keys and the
601                // command line options, so contain `-`.  Our JavaScript needs to be able to look
602                // these values up both in `dataset` and in the storage API, so it needs to be able
603                // to convert the names back and forth.  Despite doing this kebab-case to
604                // StudlyCaps transformation automatically, the JS DOM API does not provide a
605                // mechanism for doing just the transformation on a string.  So we want to avoid
606                // the StudlyCaps representation in the `dataset` property.
607                //
608                // We solve this by replacing all the `-`s with `_`s.  We do that here, when we
609                // generate the `data-` attributes, and in the JS, when we look them up.  (See
610                // `getSettingValue` in `storage.js.`) Converting `-` to `_` is simple in JS.
611                //
612                // The values will be HTML-escaped by the default Tera escaping.
613                |(k, v)| (k.replace('-', "_"), v),
614            )
615            .collect();
616
617        let test_args = matches.opt_strs("test-args");
618        let test_args: Vec<String> =
619            test_args.iter().flat_map(|s| s.split_whitespace()).map(|s| s.to_string()).collect();
620
621        let should_test = matches.opt_present("test");
622        let no_run = matches.opt_present("no-run");
623
624        if !should_test && no_run {
625            dcx.fatal("the `--test` flag must be passed to enable `--no-run`");
626        }
627
628        let mut output_to_stdout = false;
629        let test_builder_wrappers =
630            matches.opt_strs("test-builder-wrapper").iter().map(PathBuf::from).collect();
631        let output = match (matches.opt_str("out-dir"), matches.opt_str("output")) {
632            (Some(_), Some(_)) => {
633                dcx.fatal("cannot use both 'out-dir' and 'output' at once");
634            }
635            (Some(out_dir), None) | (None, Some(out_dir)) => {
636                output_to_stdout = out_dir == "-";
637                PathBuf::from(out_dir)
638            }
639            (None, None) => PathBuf::from("doc"),
640        };
641
642        let cfgs = matches.opt_strs("cfg");
643        let check_cfgs = matches.opt_strs("check-cfg");
644
645        let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
646
647        let mut loaded_paths = Vec::new();
648
649        if let Some(ref p) = extension_css {
650            loaded_paths.push(p.clone());
651            if !p.is_file() {
652                dcx.fatal("option --extend-css argument must be a file");
653            }
654        }
655
656        let mut themes = Vec::new();
657        if matches.opt_present("theme") {
658            let mut content =
659                std::str::from_utf8(static_files::STATIC_FILES.rustdoc_css.src_bytes).unwrap();
660            if let Some((_, inside)) = content.split_once("/* Begin theme: light */") {
661                content = inside;
662            }
663            if let Some((inside, _)) = content.split_once("/* End theme: light */") {
664                content = inside;
665            }
666            let paths = match theme::load_css_paths(content) {
667                Ok(p) => p,
668                Err(e) => dcx.fatal(e),
669            };
670
671            for (theme_file, theme_s) in
672                matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
673            {
674                if !theme_file.is_file() {
675                    dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
676                        .with_help("arguments to --theme must be files")
677                        .emit();
678                }
679                if theme_file.extension() != Some(OsStr::new("css")) {
680                    dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
681                        .with_help("arguments to --theme must have a .css extension")
682                        .emit();
683                }
684                let (success, ret) = theme::test_theme_against(&theme_file, &paths, dcx);
685                if !success {
686                    dcx.fatal(format!("error loading theme file: \"{theme_s}\""));
687                } else if !ret.is_empty() {
688                    dcx.struct_warn(format!(
689                        "theme file \"{theme_s}\" is missing CSS rules from the default theme",
690                    ))
691                    .with_warn("the theme may appear incorrect when loaded")
692                    .with_help(format!(
693                        "to see what rules are missing, call `rustdoc --check-theme \"{theme_s}\"`",
694                    ))
695                    .emit();
696                }
697                loaded_paths.push(theme_file.clone());
698                themes.push(StylePath { path: theme_file });
699            }
700        }
701
702        let edition = config::parse_crate_edition(early_dcx, matches);
703
704        let mut id_map = html::markdown::IdMap::new();
705        let Some(external_html) = ExternalHtml::load(
706            &matches.opt_strs("html-in-header"),
707            &matches.opt_strs("html-before-content"),
708            &matches.opt_strs("html-after-content"),
709            &matches.opt_strs("markdown-before-content"),
710            &matches.opt_strs("markdown-after-content"),
711            nightly_options::match_is_nightly_build(matches),
712            dcx,
713            &mut id_map,
714            edition,
715            &None,
716            &mut loaded_paths,
717        ) else {
718            dcx.fatal("`ExternalHtml::load` failed");
719        };
720
721        match matches.opt_str("r").as_deref() {
722            Some("rust") | None => {}
723            Some(s) => dcx.fatal(format!("unknown input format: {s}")),
724        }
725
726        let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
727        if let Some(ref index_page) = index_page
728            && !index_page.is_file()
729        {
730            dcx.fatal("option `--index-page` argument must be a file");
731        }
732
733        let target = parse_target_triple(early_dcx, matches);
734        let sysroot = Sysroot::new(matches.opt_str("sysroot").map(PathBuf::from));
735
736        let libs = matches
737            .opt_strs("L")
738            .iter()
739            .map(|s| {
740                SearchPath::from_cli_opt(
741                    sysroot.path(),
742                    &target,
743                    early_dcx,
744                    s,
745                    #[allow(rustc::bad_opt_access)] // we have no `Session` here
746                    unstable_opts.unstable_options,
747                )
748            })
749            .collect();
750
751        let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
752            Ok(types) => types,
753            Err(e) => {
754                dcx.fatal(format!("unknown crate type: {e}"));
755            }
756        };
757
758        let crate_name = matches.opt_str("crate-name");
759        let bin_crate = crate_types.contains(&CrateType::Executable);
760        let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
761        let playground_url = matches.opt_str("playground-url");
762        let module_sorting = if matches.opt_present("sort-modules-by-appearance") {
763            ModuleSorting::DeclarationOrder
764        } else {
765            ModuleSorting::Alphabetical
766        };
767        let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
768        let markdown_no_toc = matches.opt_present("markdown-no-toc");
769        let markdown_css = matches.opt_strs("markdown-css");
770        let markdown_playground_url = matches.opt_str("markdown-playground-url");
771        let crate_version = matches.opt_str("crate-version");
772        let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
773        let static_root_path = matches.opt_str("static-root-path");
774        let test_run_directory = matches.opt_str("test-run-directory").map(PathBuf::from);
775        let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
776        let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
777        let codegen_options_strs = matches.opt_strs("C");
778        let unstable_opts_strs = matches.opt_strs("Z");
779        let lib_strs = matches.opt_strs("L");
780        let extern_strs = matches.opt_strs("extern");
781        let test_runtool = matches.opt_str("test-runtool");
782        let test_runtool_args = matches.opt_strs("test-runtool-arg");
783        let document_private = matches.opt_present("document-private-items");
784        let document_hidden = matches.opt_present("document-hidden-items");
785        let run_check = matches.opt_present("check");
786        let generate_redirect_map = matches.opt_present("generate-redirect-map");
787        let show_type_layout = matches.opt_present("show-type-layout");
788        let nocapture = matches.opt_present("nocapture");
789        let generate_link_to_definition = matches.opt_present("generate-link-to-definition");
790        let generate_macro_expansion = matches.opt_present("generate-macro-expansion");
791        let extern_html_root_takes_precedence =
792            matches.opt_present("extern-html-root-takes-precedence");
793        let html_no_source = matches.opt_present("html-no-source");
794        let should_merge = match parse_merge(matches) {
795            Ok(result) => result,
796            Err(e) => dcx.fatal(format!("--merge option error: {e}")),
797        };
798
799        if generate_link_to_definition && (show_coverage || output_format != OutputFormat::Html) {
800            dcx.struct_warn(
801                "`--generate-link-to-definition` option can only be used with HTML output format",
802            )
803            .with_note("`--generate-link-to-definition` option will be ignored")
804            .emit();
805        }
806        if generate_macro_expansion && (show_coverage || output_format != OutputFormat::Html) {
807            dcx.struct_warn(
808                "`--generate-macro-expansion` option can only be used with HTML output format",
809            )
810            .with_note("`--generate-macro-expansion` option will be ignored")
811            .emit();
812        }
813
814        let scrape_examples_options = ScrapeExamplesOptions::new(matches, dcx);
815        let with_examples = matches.opt_strs("with-examples");
816        let call_locations =
817            crate::scrape_examples::load_call_locations(with_examples, dcx, &mut loaded_paths);
818        let doctest_build_args = matches.opt_strs("doctest-build-arg");
819
820        let unstable_features =
821            rustc_feature::UnstableFeatures::from_environment(crate_name.as_deref());
822
823        let disable_minification = matches.opt_present("disable-minification");
824
825        let options = Options {
826            bin_crate,
827            proc_macro_crate,
828            error_format,
829            diagnostic_width,
830            libs,
831            lib_strs,
832            externs,
833            extern_strs,
834            cfgs,
835            check_cfgs,
836            codegen_options,
837            codegen_options_strs,
838            unstable_opts,
839            unstable_opts_strs,
840            target,
841            edition,
842            sysroot,
843            lint_opts,
844            describe_lints,
845            lint_cap,
846            should_test,
847            test_args,
848            show_coverage,
849            crate_version,
850            test_run_directory,
851            persist_doctests,
852            test_runtool,
853            test_runtool_args,
854            test_builder,
855            run_check,
856            no_run,
857            test_builder_wrappers,
858            remap_path_prefix,
859            nocapture,
860            crate_name,
861            output_format,
862            json_unused_externs,
863            scrape_examples_options,
864            unstable_features,
865            doctest_build_args,
866            target_modifiers,
867        };
868        let render_options = RenderOptions {
869            output,
870            external_html,
871            id_map,
872            playground_url,
873            module_sorting,
874            themes,
875            extension_css,
876            extern_html_root_urls,
877            extern_html_root_takes_precedence,
878            default_settings,
879            resource_suffix,
880            enable_index_page,
881            index_page,
882            static_root_path,
883            markdown_no_toc,
884            markdown_css,
885            markdown_playground_url,
886            document_private,
887            document_hidden,
888            generate_redirect_map,
889            show_type_layout,
890            unstable_features,
891            emit,
892            generate_link_to_definition,
893            generate_macro_expansion,
894            call_locations,
895            no_emit_shared: false,
896            html_no_source,
897            output_to_stdout,
898            should_merge,
899            include_parts_dir,
900            parts_out_dir,
901            disable_minification,
902        };
903        Some((input, options, render_options, loaded_paths))
904    }
905}
906
907/// Returns `true` if the file given as `self.input` is a Markdown file.
908pub(crate) fn markdown_input(input: &Input) -> Option<&Path> {
909    input.opt_path().filter(|p| matches!(p.extension(), Some(e) if e == "md" || e == "markdown"))
910}
911
912fn parse_remap_path_prefix(
913    matches: &getopts::Matches,
914) -> Result<Vec<(PathBuf, PathBuf)>, &'static str> {
915    matches
916        .opt_strs("remap-path-prefix")
917        .into_iter()
918        .map(|remap| {
919            remap
920                .rsplit_once('=')
921                .ok_or("--remap-path-prefix must contain '=' between FROM and TO")
922                .map(|(from, to)| (PathBuf::from(from), PathBuf::from(to)))
923        })
924        .collect()
925}
926
927/// Prints deprecation warnings for deprecated options
928fn check_deprecated_options(matches: &getopts::Matches, dcx: DiagCtxtHandle<'_>) {
929    let deprecated_flags = [];
930
931    for &flag in deprecated_flags.iter() {
932        if matches.opt_present(flag) {
933            dcx.struct_warn(format!("the `{flag}` flag is deprecated"))
934                .with_note(
935                    "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
936                    for more information",
937                )
938                .emit();
939        }
940    }
941
942    let removed_flags = ["plugins", "plugin-path", "no-defaults", "passes", "input-format"];
943
944    for &flag in removed_flags.iter() {
945        if matches.opt_present(flag) {
946            let mut err = dcx.struct_warn(format!("the `{flag}` flag no longer functions"));
947            err.note(
948                "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
949                for more information",
950            );
951
952            if flag == "no-defaults" || flag == "passes" {
953                err.help("you may want to use --document-private-items");
954            } else if flag == "plugins" || flag == "plugin-path" {
955                err.warn("see CVE-2018-1000622");
956            }
957
958            err.emit();
959        }
960    }
961}
962
963/// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
964/// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
965/// describing the issue.
966fn parse_extern_html_roots(
967    matches: &getopts::Matches,
968) -> Result<BTreeMap<String, String>, &'static str> {
969    let mut externs = BTreeMap::new();
970    for arg in &matches.opt_strs("extern-html-root-url") {
971        let (name, url) =
972            arg.split_once('=').ok_or("--extern-html-root-url must be of the form name=url")?;
973        externs.insert(name.to_string(), url.to_string());
974    }
975    Ok(externs)
976}
977
978/// Path directly to crate-info file.
979///
980/// For example, `/home/user/project/target/doc.parts/<crate>/crate-info`.
981#[derive(Clone, Debug)]
982pub(crate) struct PathToParts(pub(crate) PathBuf);
983
984impl PathToParts {
985    fn from_flag(path: String) -> Result<PathToParts, String> {
986        let mut path = PathBuf::from(path);
987        // check here is for diagnostics
988        if path.exists() && !path.is_dir() {
989            Err(format!(
990                "--parts-out-dir and --include-parts-dir expect directories, found: {}",
991                path.display(),
992            ))
993        } else {
994            // if it doesn't exist, we'll create it. worry about that in write_shared
995            path.push("crate-info");
996            Ok(PathToParts(path))
997        }
998    }
999}
1000
1001/// Reports error if --include-parts-dir / crate-info is not a file
1002fn parse_include_parts_dir(m: &getopts::Matches) -> Result<Vec<PathToParts>, String> {
1003    let mut ret = Vec::new();
1004    for p in m.opt_strs("include-parts-dir") {
1005        let p = PathToParts::from_flag(p)?;
1006        // this is just for diagnostic
1007        if !p.0.is_file() {
1008            return Err(format!("--include-parts-dir expected {} to be a file", p.0.display()));
1009        }
1010        ret.push(p);
1011    }
1012    Ok(ret)
1013}
1014
1015/// Controls merging of cross-crate information
1016#[derive(Debug, Clone)]
1017pub(crate) struct ShouldMerge {
1018    /// Should we append to existing cci in the doc root
1019    pub(crate) read_rendered_cci: bool,
1020    /// Should we write cci to the doc root
1021    pub(crate) write_rendered_cci: bool,
1022}
1023
1024/// Extracts read_rendered_cci and write_rendered_cci from command line arguments, or
1025/// reports an error if an invalid option was provided
1026fn parse_merge(m: &getopts::Matches) -> Result<ShouldMerge, &'static str> {
1027    match m.opt_str("merge").as_deref() {
1028        // default = read-write
1029        None => Ok(ShouldMerge { read_rendered_cci: true, write_rendered_cci: true }),
1030        Some("none") if m.opt_present("include-parts-dir") => {
1031            Err("--include-parts-dir not allowed if --merge=none")
1032        }
1033        Some("none") => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: false }),
1034        Some("shared") if m.opt_present("parts-out-dir") || m.opt_present("include-parts-dir") => {
1035            Err("--parts-out-dir and --include-parts-dir not allowed if --merge=shared")
1036        }
1037        Some("shared") => Ok(ShouldMerge { read_rendered_cci: true, write_rendered_cci: true }),
1038        Some("finalize") if m.opt_present("parts-out-dir") => {
1039            Err("--parts-out-dir not allowed if --merge=finalize")
1040        }
1041        Some("finalize") => Ok(ShouldMerge { read_rendered_cci: false, write_rendered_cci: true }),
1042        Some(_) => Err("argument to --merge must be `none`, `shared`, or `finalize`"),
1043    }
1044}