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