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