]> git.proxmox.com Git - rustc.git/blob - src/librustdoc/config.rs
1ff2c8191e562ef3a79bbd2c3e5dbdaadfe307d1
[rustc.git] / src / librustdoc / config.rs
1 use std::collections::BTreeMap;
2 use std::convert::TryFrom;
3 use std::ffi::OsStr;
4 use std::fmt;
5 use std::path::PathBuf;
6 use std::str::FromStr;
7
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_session::config::{
10 self, parse_crate_types_from_list, parse_externs, parse_target_triple, CrateType,
11 };
12 use rustc_session::config::{get_cmd_lint_options, nightly_options};
13 use rustc_session::config::{
14 CodegenOptions, DebuggingOptions, ErrorOutputType, Externs, JsonUnusedExterns,
15 };
16 use rustc_session::getopts;
17 use rustc_session::lint::Level;
18 use rustc_session::search_paths::SearchPath;
19 use rustc_span::edition::Edition;
20 use rustc_target::spec::TargetTriple;
21
22 use crate::core::new_handler;
23 use crate::externalfiles::ExternalHtml;
24 use crate::html;
25 use crate::html::markdown::IdMap;
26 use crate::html::render::StylePath;
27 use crate::html::static_files;
28 use crate::opts;
29 use crate::passes::{self, Condition};
30 use crate::scrape_examples::{AllCallLocations, ScrapeExamplesOptions};
31 use crate::theme;
32
33 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
34 crate enum OutputFormat {
35 Json,
36 Html,
37 }
38
39 impl Default for OutputFormat {
40 fn default() -> OutputFormat {
41 OutputFormat::Html
42 }
43 }
44
45 impl OutputFormat {
46 crate fn is_json(&self) -> bool {
47 matches!(self, OutputFormat::Json)
48 }
49 }
50
51 impl TryFrom<&str> for OutputFormat {
52 type Error = String;
53
54 fn try_from(value: &str) -> Result<Self, Self::Error> {
55 match value {
56 "json" => Ok(OutputFormat::Json),
57 "html" => Ok(OutputFormat::Html),
58 _ => Err(format!("unknown output format `{}`", value)),
59 }
60 }
61 }
62
63 /// Configuration options for rustdoc.
64 #[derive(Clone)]
65 crate struct Options {
66 // Basic options / Options passed directly to rustc
67 /// The crate root or Markdown file to load.
68 crate input: PathBuf,
69 /// The name of the crate being documented.
70 crate crate_name: Option<String>,
71 /// Whether or not this is a proc-macro crate
72 crate proc_macro_crate: bool,
73 /// How to format errors and warnings.
74 crate error_format: ErrorOutputType,
75 /// Library search paths to hand to the compiler.
76 crate libs: Vec<SearchPath>,
77 /// Library search paths strings to hand to the compiler.
78 crate lib_strs: Vec<String>,
79 /// The list of external crates to link against.
80 crate externs: Externs,
81 /// The list of external crates strings to link against.
82 crate extern_strs: Vec<String>,
83 /// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`.
84 crate cfgs: Vec<String>,
85 /// List of check cfg flags to hand to the compiler.
86 crate check_cfgs: Vec<String>,
87 /// Codegen options to hand to the compiler.
88 crate codegen_options: CodegenOptions,
89 /// Codegen options strings to hand to the compiler.
90 crate codegen_options_strs: Vec<String>,
91 /// Debugging (`-Z`) options to pass to the compiler.
92 crate debugging_opts: DebuggingOptions,
93 /// Debugging (`-Z`) options strings to pass to the compiler.
94 crate debugging_opts_strs: Vec<String>,
95 /// The target used to compile the crate against.
96 crate target: TargetTriple,
97 /// Edition used when reading the crate. Defaults to "2015". Also used by default when
98 /// compiling doctests from the crate.
99 crate edition: Edition,
100 /// The path to the sysroot. Used during the compilation process.
101 crate maybe_sysroot: Option<PathBuf>,
102 /// Lint information passed over the command-line.
103 crate lint_opts: Vec<(String, Level)>,
104 /// Whether to ask rustc to describe the lints it knows.
105 crate describe_lints: bool,
106 /// What level to cap lints at.
107 crate lint_cap: Option<Level>,
108
109 // Options specific to running doctests
110 /// Whether we should run doctests instead of generating docs.
111 crate should_test: bool,
112 /// List of arguments to pass to the test harness, if running tests.
113 crate test_args: Vec<String>,
114 /// The working directory in which to run tests.
115 crate test_run_directory: Option<PathBuf>,
116 /// Optional path to persist the doctest executables to, defaults to a
117 /// temporary directory if not set.
118 crate persist_doctests: Option<PathBuf>,
119 /// Runtool to run doctests with
120 crate runtool: Option<String>,
121 /// Arguments to pass to the runtool
122 crate runtool_args: Vec<String>,
123 /// Whether to allow ignoring doctests on a per-target basis
124 /// For example, using ignore-foo to ignore running the doctest on any target that
125 /// contains "foo" as a substring
126 crate enable_per_target_ignores: bool,
127 /// Do not run doctests, compile them if should_test is active.
128 crate no_run: bool,
129
130 /// The path to a rustc-like binary to build tests with. If not set, we
131 /// default to loading from `$sysroot/bin/rustc`.
132 crate test_builder: Option<PathBuf>,
133
134 // Options that affect the documentation process
135 /// Whether to run the `calculate-doc-coverage` pass, which counts the number of public items
136 /// with and without documentation.
137 crate show_coverage: bool,
138
139 // Options that alter generated documentation pages
140 /// Crate version to note on the sidebar of generated docs.
141 crate crate_version: Option<String>,
142 /// Collected options specific to outputting final pages.
143 crate render_options: RenderOptions,
144 /// The format that we output when rendering.
145 ///
146 /// Currently used only for the `--show-coverage` option.
147 crate output_format: OutputFormat,
148 /// If this option is set to `true`, rustdoc will only run checks and not generate
149 /// documentation.
150 crate run_check: bool,
151 /// Whether doctests should emit unused externs
152 crate json_unused_externs: JsonUnusedExterns,
153 /// Whether to skip capturing stdout and stderr of tests.
154 crate nocapture: bool,
155
156 /// Configuration for scraping examples from the current crate. If this option is Some(..) then
157 /// the compiler will scrape examples and not generate documentation.
158 crate scrape_examples_options: Option<ScrapeExamplesOptions>,
159 }
160
161 impl fmt::Debug for Options {
162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163 struct FmtExterns<'a>(&'a Externs);
164
165 impl<'a> fmt::Debug for FmtExterns<'a> {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 f.debug_map().entries(self.0.iter()).finish()
168 }
169 }
170
171 f.debug_struct("Options")
172 .field("input", &self.input)
173 .field("crate_name", &self.crate_name)
174 .field("proc_macro_crate", &self.proc_macro_crate)
175 .field("error_format", &self.error_format)
176 .field("libs", &self.libs)
177 .field("externs", &FmtExterns(&self.externs))
178 .field("cfgs", &self.cfgs)
179 .field("check-cfgs", &self.check_cfgs)
180 .field("codegen_options", &"...")
181 .field("debugging_options", &"...")
182 .field("target", &self.target)
183 .field("edition", &self.edition)
184 .field("maybe_sysroot", &self.maybe_sysroot)
185 .field("lint_opts", &self.lint_opts)
186 .field("describe_lints", &self.describe_lints)
187 .field("lint_cap", &self.lint_cap)
188 .field("should_test", &self.should_test)
189 .field("test_args", &self.test_args)
190 .field("test_run_directory", &self.test_run_directory)
191 .field("persist_doctests", &self.persist_doctests)
192 .field("show_coverage", &self.show_coverage)
193 .field("crate_version", &self.crate_version)
194 .field("render_options", &self.render_options)
195 .field("runtool", &self.runtool)
196 .field("runtool_args", &self.runtool_args)
197 .field("enable-per-target-ignores", &self.enable_per_target_ignores)
198 .field("run_check", &self.run_check)
199 .field("no_run", &self.no_run)
200 .field("nocapture", &self.nocapture)
201 .field("scrape_examples_options", &self.scrape_examples_options)
202 .finish()
203 }
204 }
205
206 /// Configuration options for the HTML page-creation process.
207 #[derive(Clone, Debug)]
208 crate struct RenderOptions {
209 /// Output directory to generate docs into. Defaults to `doc`.
210 crate output: PathBuf,
211 /// External files to insert into generated pages.
212 crate external_html: ExternalHtml,
213 /// A pre-populated `IdMap` with the default headings and any headings added by Markdown files
214 /// processed by `external_html`.
215 crate id_map: IdMap,
216 /// If present, playground URL to use in the "Run" button added to code samples.
217 ///
218 /// Be aware: This option can come both from the CLI and from crate attributes!
219 crate playground_url: Option<String>,
220 /// Whether to sort modules alphabetically on a module page instead of using declaration order.
221 /// `true` by default.
222 //
223 // FIXME(misdreavus): the flag name is `--sort-modules-by-appearance` but the meaning is
224 // inverted once read.
225 crate sort_modules_alphabetically: bool,
226 /// List of themes to extend the docs with. Original argument name is included to assist in
227 /// displaying errors if it fails a theme check.
228 crate themes: Vec<StylePath>,
229 /// If present, CSS file that contains rules to add to the default CSS.
230 crate extension_css: Option<PathBuf>,
231 /// A map of crate names to the URL to use instead of querying the crate's `html_root_url`.
232 crate extern_html_root_urls: BTreeMap<String, String>,
233 /// Whether to give precedence to `html_root_url` or `--exten-html-root-url`.
234 crate extern_html_root_takes_precedence: bool,
235 /// A map of the default settings (values are as for DOM storage API). Keys should lack the
236 /// `rustdoc-` prefix.
237 crate default_settings: FxHashMap<String, String>,
238 /// If present, suffix added to CSS/JavaScript files when referencing them in generated pages.
239 crate resource_suffix: String,
240 /// Whether to run the static CSS/JavaScript through a minifier when outputting them. `true` by
241 /// default.
242 //
243 // FIXME(misdreavus): the flag name is `--disable-minification` but the meaning is inverted
244 // once read.
245 crate enable_minification: bool,
246 /// Whether to create an index page in the root of the output directory. If this is true but
247 /// `enable_index_page` is None, generate a static listing of crates instead.
248 crate enable_index_page: bool,
249 /// A file to use as the index page at the root of the output directory. Overrides
250 /// `enable_index_page` to be true if set.
251 crate index_page: Option<PathBuf>,
252 /// An optional path to use as the location of static files. If not set, uses combinations of
253 /// `../` to reach the documentation root.
254 crate static_root_path: Option<String>,
255
256 // Options specific to reading standalone Markdown files
257 /// Whether to generate a table of contents on the output file when reading a standalone
258 /// Markdown file.
259 crate markdown_no_toc: bool,
260 /// Additional CSS files to link in pages generated from standalone Markdown files.
261 crate markdown_css: Vec<String>,
262 /// If present, playground URL to use in the "Run" button added to code samples generated from
263 /// standalone Markdown files. If not present, `playground_url` is used.
264 crate markdown_playground_url: Option<String>,
265 /// Document items that have lower than `pub` visibility.
266 crate document_private: bool,
267 /// Document items that have `doc(hidden)`.
268 crate document_hidden: bool,
269 /// If `true`, generate a JSON file in the crate folder instead of HTML redirection files.
270 crate generate_redirect_map: bool,
271 /// Show the memory layout of types in the docs.
272 crate show_type_layout: bool,
273 crate unstable_features: rustc_feature::UnstableFeatures,
274 crate emit: Vec<EmitType>,
275 /// If `true`, HTML source pages will generate links for items to their definition.
276 crate generate_link_to_definition: bool,
277 /// Set of function-call locations to include as examples
278 crate call_locations: AllCallLocations,
279 /// If `true`, Context::init will not emit shared files.
280 crate no_emit_shared: bool,
281 }
282
283 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
284 crate enum EmitType {
285 Unversioned,
286 Toolchain,
287 InvocationSpecific,
288 }
289
290 impl FromStr for EmitType {
291 type Err = ();
292
293 fn from_str(s: &str) -> Result<Self, Self::Err> {
294 use EmitType::*;
295 match s {
296 "unversioned-shared-resources" => Ok(Unversioned),
297 "toolchain-shared-resources" => Ok(Toolchain),
298 "invocation-specific" => Ok(InvocationSpecific),
299 _ => Err(()),
300 }
301 }
302 }
303
304 impl RenderOptions {
305 crate fn should_emit_crate(&self) -> bool {
306 self.emit.is_empty() || self.emit.contains(&EmitType::InvocationSpecific)
307 }
308 }
309
310 impl Options {
311 /// Parses the given command-line for options. If an error message or other early-return has
312 /// been printed, returns `Err` with the exit code.
313 crate fn from_matches(matches: &getopts::Matches) -> Result<Options, i32> {
314 // Check for unstable options.
315 nightly_options::check_nightly_options(matches, &opts());
316
317 if matches.opt_present("h") || matches.opt_present("help") {
318 crate::usage("rustdoc");
319 return Err(0);
320 } else if matches.opt_present("version") {
321 rustc_driver::version("rustdoc", matches);
322 return Err(0);
323 }
324
325 let color = config::parse_color(matches);
326 let config::JsonConfig { json_rendered, json_unused_externs, .. } =
327 config::parse_json(matches);
328 let error_format = config::parse_error_format(matches, color, json_rendered);
329
330 let codegen_options = CodegenOptions::build(matches, error_format);
331 let debugging_opts = DebuggingOptions::build(matches, error_format);
332
333 let diag = new_handler(error_format, None, &debugging_opts);
334
335 // check for deprecated options
336 check_deprecated_options(matches, &diag);
337
338 if matches.opt_strs("passes") == ["list"] {
339 println!("Available passes for running rustdoc:");
340 for pass in passes::PASSES {
341 println!("{:>20} - {}", pass.name, pass.description);
342 }
343 println!("\nDefault passes for rustdoc:");
344 for p in passes::DEFAULT_PASSES {
345 print!("{:>20}", p.pass.name);
346 println_condition(p.condition);
347 }
348
349 if nightly_options::match_is_nightly_build(matches) {
350 println!("\nPasses run with `--show-coverage`:");
351 for p in passes::COVERAGE_PASSES {
352 print!("{:>20}", p.pass.name);
353 println_condition(p.condition);
354 }
355 }
356
357 fn println_condition(condition: Condition) {
358 use Condition::*;
359 match condition {
360 Always => println!(),
361 WhenDocumentPrivate => println!(" (when --document-private-items)"),
362 WhenNotDocumentPrivate => println!(" (when not --document-private-items)"),
363 WhenNotDocumentHidden => println!(" (when not --document-hidden-items)"),
364 }
365 }
366
367 return Err(0);
368 }
369
370 let mut emit = Vec::new();
371 for list in matches.opt_strs("emit") {
372 for kind in list.split(',') {
373 match kind.parse() {
374 Ok(kind) => emit.push(kind),
375 Err(()) => {
376 diag.err(&format!("unrecognized emission type: {}", kind));
377 return Err(1);
378 }
379 }
380 }
381 }
382
383 // check for `--output-format=json`
384 if !matches!(matches.opt_str("output-format").as_deref(), None | Some("html"))
385 && !matches.opt_present("show-coverage")
386 && !nightly_options::is_unstable_enabled(matches)
387 {
388 rustc_session::early_error(
389 error_format,
390 "the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/76578)",
391 );
392 }
393
394 let to_check = matches.opt_strs("check-theme");
395 if !to_check.is_empty() {
396 let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
397 let mut errors = 0;
398
399 println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
400 for theme_file in to_check.iter() {
401 print!(" - Checking \"{}\"...", theme_file);
402 let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag);
403 if !differences.is_empty() || !success {
404 println!(" FAILED");
405 errors += 1;
406 if !differences.is_empty() {
407 println!("{}", differences.join("\n"));
408 }
409 } else {
410 println!(" OK");
411 }
412 }
413 if errors != 0 {
414 return Err(1);
415 }
416 return Err(0);
417 }
418
419 if matches.free.is_empty() {
420 diag.struct_err("missing file operand").emit();
421 return Err(1);
422 }
423 if matches.free.len() > 1 {
424 diag.struct_err("too many file operands").emit();
425 return Err(1);
426 }
427 let input = PathBuf::from(&matches.free[0]);
428
429 let libs = matches
430 .opt_strs("L")
431 .iter()
432 .map(|s| SearchPath::from_cli_opt(s, error_format))
433 .collect();
434 let externs = parse_externs(matches, &debugging_opts, error_format);
435 let extern_html_root_urls = match parse_extern_html_roots(matches) {
436 Ok(ex) => ex,
437 Err(err) => {
438 diag.struct_err(err).emit();
439 return Err(1);
440 }
441 };
442
443 let default_settings: Vec<Vec<(String, String)>> = vec![
444 matches
445 .opt_str("default-theme")
446 .iter()
447 .flat_map(|theme| {
448 vec![
449 ("use-system-theme".to_string(), "false".to_string()),
450 ("theme".to_string(), theme.to_string()),
451 ]
452 })
453 .collect(),
454 matches
455 .opt_strs("default-setting")
456 .iter()
457 .map(|s| match s.split_once('=') {
458 None => (s.clone(), "true".to_string()),
459 Some((k, v)) => (k.to_string(), v.to_string()),
460 })
461 .collect(),
462 ];
463 let default_settings = default_settings
464 .into_iter()
465 .flatten()
466 .map(
467 // The keys here become part of `data-` attribute names in the generated HTML. The
468 // browser does a strange mapping when converting them into attributes on the
469 // `dataset` property on the DOM HTML Node:
470 // https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
471 //
472 // The original key values we have are the same as the DOM storage API keys and the
473 // command line options, so contain `-`. Our Javascript needs to be able to look
474 // these values up both in `dataset` and in the storage API, so it needs to be able
475 // to convert the names back and forth. Despite doing this kebab-case to
476 // StudlyCaps transformation automatically, the JS DOM API does not provide a
477 // mechanism for doing the just transformation on a string. So we want to avoid
478 // the StudlyCaps representation in the `dataset` property.
479 //
480 // We solve this by replacing all the `-`s with `_`s. We do that here, when we
481 // generate the `data-` attributes, and in the JS, when we look them up. (See
482 // `getSettingValue` in `storage.js.`) Converting `-` to `_` is simple in JS.
483 //
484 // The values will be HTML-escaped by the default Tera escaping.
485 |(k, v)| (k.replace('-', "_"), v),
486 )
487 .collect();
488
489 let test_args = matches.opt_strs("test-args");
490 let test_args: Vec<String> =
491 test_args.iter().flat_map(|s| s.split_whitespace()).map(|s| s.to_string()).collect();
492
493 let should_test = matches.opt_present("test");
494 let no_run = matches.opt_present("no-run");
495
496 if !should_test && no_run {
497 diag.err("the `--test` flag must be passed to enable `--no-run`");
498 return Err(1);
499 }
500
501 let out_dir = matches.opt_str("out-dir").map(|s| PathBuf::from(&s));
502 let output = matches.opt_str("output").map(|s| PathBuf::from(&s));
503 let output = match (out_dir, output) {
504 (Some(_), Some(_)) => {
505 diag.struct_err("cannot use both 'out-dir' and 'output' at once").emit();
506 return Err(1);
507 }
508 (Some(out_dir), None) => out_dir,
509 (None, Some(output)) => output,
510 (None, None) => PathBuf::from("doc"),
511 };
512
513 let cfgs = matches.opt_strs("cfg");
514 let check_cfgs = matches.opt_strs("check-cfg");
515
516 let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
517
518 if let Some(ref p) = extension_css {
519 if !p.is_file() {
520 diag.struct_err("option --extend-css argument must be a file").emit();
521 return Err(1);
522 }
523 }
524
525 let mut themes = Vec::new();
526 if matches.opt_present("theme") {
527 let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
528
529 for (theme_file, theme_s) in
530 matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
531 {
532 if !theme_file.is_file() {
533 diag.struct_err(&format!("invalid argument: \"{}\"", theme_s))
534 .help("arguments to --theme must be files")
535 .emit();
536 return Err(1);
537 }
538 if theme_file.extension() != Some(OsStr::new("css")) {
539 diag.struct_err(&format!("invalid argument: \"{}\"", theme_s))
540 .help("arguments to --theme must have a .css extension")
541 .emit();
542 return Err(1);
543 }
544 let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
545 if !success {
546 diag.struct_err(&format!("error loading theme file: \"{}\"", theme_s)).emit();
547 return Err(1);
548 } else if !ret.is_empty() {
549 diag.struct_warn(&format!(
550 "theme file \"{}\" is missing CSS rules from the default theme",
551 theme_s
552 ))
553 .warn("the theme may appear incorrect when loaded")
554 .help(&format!(
555 "to see what rules are missing, call `rustdoc --check-theme \"{}\"`",
556 theme_s
557 ))
558 .emit();
559 }
560 themes.push(StylePath { path: theme_file });
561 }
562 }
563
564 let edition = config::parse_crate_edition(matches);
565
566 let mut id_map = html::markdown::IdMap::new();
567 let Some(external_html) = ExternalHtml::load(
568 &matches.opt_strs("html-in-header"),
569 &matches.opt_strs("html-before-content"),
570 &matches.opt_strs("html-after-content"),
571 &matches.opt_strs("markdown-before-content"),
572 &matches.opt_strs("markdown-after-content"),
573 nightly_options::match_is_nightly_build(matches),
574 &diag,
575 &mut id_map,
576 edition,
577 &None,
578 ) else {
579 return Err(3);
580 };
581
582 match matches.opt_str("r").as_deref() {
583 Some("rust") | None => {}
584 Some(s) => {
585 diag.struct_err(&format!("unknown input format: {}", s)).emit();
586 return Err(1);
587 }
588 }
589
590 let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
591 if let Some(ref index_page) = index_page {
592 if !index_page.is_file() {
593 diag.struct_err("option `--index-page` argument must be a file").emit();
594 return Err(1);
595 }
596 }
597
598 let target = parse_target_triple(matches, error_format);
599
600 let show_coverage = matches.opt_present("show-coverage");
601
602 let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
603 Ok(types) => types,
604 Err(e) => {
605 diag.struct_err(&format!("unknown crate type: {}", e)).emit();
606 return Err(1);
607 }
608 };
609
610 let output_format = match matches.opt_str("output-format") {
611 Some(s) => match OutputFormat::try_from(s.as_str()) {
612 Ok(out_fmt) => {
613 if !out_fmt.is_json() && show_coverage {
614 diag.struct_err(
615 "html output format isn't supported for the --show-coverage option",
616 )
617 .emit();
618 return Err(1);
619 }
620 out_fmt
621 }
622 Err(e) => {
623 diag.struct_err(&e).emit();
624 return Err(1);
625 }
626 },
627 None => OutputFormat::default(),
628 };
629 let crate_name = matches.opt_str("crate-name");
630 let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
631 let playground_url = matches.opt_str("playground-url");
632 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
633 let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
634 let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
635 let enable_minification = !matches.opt_present("disable-minification");
636 let markdown_no_toc = matches.opt_present("markdown-no-toc");
637 let markdown_css = matches.opt_strs("markdown-css");
638 let markdown_playground_url = matches.opt_str("markdown-playground-url");
639 let crate_version = matches.opt_str("crate-version");
640 let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
641 let static_root_path = matches.opt_str("static-root-path");
642 let test_run_directory = matches.opt_str("test-run-directory").map(PathBuf::from);
643 let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
644 let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
645 let codegen_options_strs = matches.opt_strs("C");
646 let debugging_opts_strs = matches.opt_strs("Z");
647 let lib_strs = matches.opt_strs("L");
648 let extern_strs = matches.opt_strs("extern");
649 let runtool = matches.opt_str("runtool");
650 let runtool_args = matches.opt_strs("runtool-arg");
651 let enable_per_target_ignores = matches.opt_present("enable-per-target-ignores");
652 let document_private = matches.opt_present("document-private-items");
653 let document_hidden = matches.opt_present("document-hidden-items");
654 let run_check = matches.opt_present("check");
655 let generate_redirect_map = matches.opt_present("generate-redirect-map");
656 let show_type_layout = matches.opt_present("show-type-layout");
657 let nocapture = matches.opt_present("nocapture");
658 let generate_link_to_definition = matches.opt_present("generate-link-to-definition");
659 let extern_html_root_takes_precedence =
660 matches.opt_present("extern-html-root-takes-precedence");
661
662 if generate_link_to_definition && (show_coverage || output_format != OutputFormat::Html) {
663 diag.struct_err(
664 "--generate-link-to-definition option can only be used with HTML output format",
665 )
666 .emit();
667 return Err(1);
668 }
669
670 let scrape_examples_options = ScrapeExamplesOptions::new(&matches, &diag)?;
671 let with_examples = matches.opt_strs("with-examples");
672 let call_locations = crate::scrape_examples::load_call_locations(with_examples, &diag)?;
673
674 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
675
676 Ok(Options {
677 input,
678 proc_macro_crate,
679 error_format,
680 libs,
681 lib_strs,
682 externs,
683 extern_strs,
684 cfgs,
685 check_cfgs,
686 codegen_options,
687 codegen_options_strs,
688 debugging_opts,
689 debugging_opts_strs,
690 target,
691 edition,
692 maybe_sysroot,
693 lint_opts,
694 describe_lints,
695 lint_cap,
696 should_test,
697 test_args,
698 show_coverage,
699 crate_version,
700 test_run_directory,
701 persist_doctests,
702 runtool,
703 runtool_args,
704 enable_per_target_ignores,
705 test_builder,
706 run_check,
707 no_run,
708 nocapture,
709 render_options: RenderOptions {
710 output,
711 external_html,
712 id_map,
713 playground_url,
714 sort_modules_alphabetically,
715 themes,
716 extension_css,
717 extern_html_root_urls,
718 extern_html_root_takes_precedence,
719 default_settings,
720 resource_suffix,
721 enable_minification,
722 enable_index_page,
723 index_page,
724 static_root_path,
725 markdown_no_toc,
726 markdown_css,
727 markdown_playground_url,
728 document_private,
729 document_hidden,
730 generate_redirect_map,
731 show_type_layout,
732 unstable_features: rustc_feature::UnstableFeatures::from_environment(
733 crate_name.as_deref(),
734 ),
735 emit,
736 generate_link_to_definition,
737 call_locations,
738 no_emit_shared: false,
739 },
740 crate_name,
741 output_format,
742 json_unused_externs,
743 scrape_examples_options,
744 })
745 }
746
747 /// Returns `true` if the file given as `self.input` is a Markdown file.
748 crate fn markdown_input(&self) -> bool {
749 self.input.extension().map_or(false, |e| e == "md" || e == "markdown")
750 }
751 }
752
753 /// Prints deprecation warnings for deprecated options
754 fn check_deprecated_options(matches: &getopts::Matches, diag: &rustc_errors::Handler) {
755 let deprecated_flags = [];
756
757 for &flag in deprecated_flags.iter() {
758 if matches.opt_present(flag) {
759 diag.struct_warn(&format!("the `{}` flag is deprecated", flag))
760 .note(
761 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
762 for more information",
763 )
764 .emit();
765 }
766 }
767
768 let removed_flags = ["plugins", "plugin-path", "no-defaults", "passes", "input-format"];
769
770 for &flag in removed_flags.iter() {
771 if matches.opt_present(flag) {
772 let mut err = diag.struct_warn(&format!("the `{}` flag no longer functions", flag));
773 err.note(
774 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
775 for more information",
776 );
777
778 if flag == "no-defaults" || flag == "passes" {
779 err.help("you may want to use --document-private-items");
780 } else if flag == "plugins" || flag == "plugin-path" {
781 err.warn("see CVE-2018-1000622");
782 }
783
784 err.emit();
785 }
786 }
787 }
788
789 /// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
790 /// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
791 /// describing the issue.
792 fn parse_extern_html_roots(
793 matches: &getopts::Matches,
794 ) -> Result<BTreeMap<String, String>, &'static str> {
795 let mut externs = BTreeMap::new();
796 for arg in &matches.opt_strs("extern-html-root-url") {
797 let (name, url) =
798 arg.split_once('=').ok_or("--extern-html-root-url must be of the form name=url")?;
799 externs.insert(name.to_string(), url.to_string());
800 }
801 Ok(externs)
802 }