1 use std::collections::BTreeMap;
2 use std::convert::TryFrom;
5 use std::path::PathBuf;
7 use rustc_session::config::{self, parse_crate_types_from_list, parse_externs, CrateType};
8 use rustc_session::config::{
9 build_codegen_options, build_debugging_options, get_cmd_lint_options, host_triple,
12 use rustc_session::config::{CodegenOptions, DebuggingOptions, ErrorOutputType, Externs};
13 use rustc_session::lint::Level;
14 use rustc_session::search_paths::SearchPath;
15 use rustc_span::edition::{Edition, DEFAULT_EDITION};
16 use rustc_target::spec::TargetTriple;
18 use crate::core::new_handler;
19 use crate::externalfiles::ExternalHtml;
21 use crate::html::markdown::IdMap;
22 use crate::html::static_files;
24 use crate::passes::{self, Condition, DefaultPassOption};
27 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
28 pub enum OutputFormat {
34 pub fn is_json(&self) -> bool {
36 OutputFormat::Json => true,
42 impl TryFrom<&str> for OutputFormat {
45 fn try_from(value: &str) -> Result<Self, Self::Error> {
47 "json" => Ok(OutputFormat::Json),
48 "html" => Ok(OutputFormat::Html),
49 _ => Err(format!("unknown output format `{}`", value)),
54 /// Configuration options for rustdoc.
57 // Basic options / Options passed directly to rustc
58 /// The crate root or Markdown file to load.
60 /// The name of the crate being documented.
61 pub crate_name: Option<String>,
62 /// Whether or not this is a proc-macro crate
63 pub proc_macro_crate: bool,
64 /// How to format errors and warnings.
65 pub error_format: ErrorOutputType,
66 /// Library search paths to hand to the compiler.
67 pub libs: Vec<SearchPath>,
68 /// Library search paths strings to hand to the compiler.
69 pub lib_strs: Vec<String>,
70 /// The list of external crates to link against.
72 /// The list of external crates strings to link against.
73 pub extern_strs: Vec<String>,
74 /// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`.
75 pub cfgs: Vec<String>,
76 /// Codegen options to hand to the compiler.
77 pub codegen_options: CodegenOptions,
78 /// Codegen options strings to hand to the compiler.
79 pub codegen_options_strs: Vec<String>,
80 /// Debugging (`-Z`) options to pass to the compiler.
81 pub debugging_options: DebuggingOptions,
82 /// Debugging (`-Z`) options strings to pass to the compiler.
83 pub debugging_options_strs: Vec<String>,
84 /// The target used to compile the crate against.
85 pub target: TargetTriple,
86 /// Edition used when reading the crate. Defaults to "2015". Also used by default when
87 /// compiling doctests from the crate.
89 /// The path to the sysroot. Used during the compilation process.
90 pub maybe_sysroot: Option<PathBuf>,
91 /// Lint information passed over the command-line.
92 pub lint_opts: Vec<(String, Level)>,
93 /// Whether to ask rustc to describe the lints it knows. Practically speaking, this will not be
94 /// used, since we abort if we have no input file, but it's included for completeness.
95 pub describe_lints: bool,
96 /// What level to cap lints at.
97 pub lint_cap: Option<Level>,
99 // Options specific to running doctests
100 /// Whether we should run doctests instead of generating docs.
101 pub should_test: bool,
102 /// List of arguments to pass to the test harness, if running tests.
103 pub test_args: Vec<String>,
104 /// Optional path to persist the doctest executables to, defaults to a
105 /// temporary directory if not set.
106 pub persist_doctests: Option<PathBuf>,
107 /// Runtool to run doctests with
108 pub runtool: Option<String>,
109 /// Arguments to pass to the runtool
110 pub runtool_args: Vec<String>,
111 /// Whether to allow ignoring doctests on a per-target basis
112 /// For example, using ignore-foo to ignore running the doctest on any target that
113 /// contains "foo" as a substring
114 pub enable_per_target_ignores: bool,
116 /// The path to a rustc-like binary to build tests with. If not set, we
117 /// default to loading from $sysroot/bin/rustc.
118 pub test_builder: Option<PathBuf>,
120 // Options that affect the documentation process
121 /// The selected default set of passes to use.
123 /// Be aware: This option can come both from the CLI and from crate attributes!
124 pub default_passes: DefaultPassOption,
125 /// Document items that have lower than `pub` visibility.
126 pub document_private: bool,
127 /// Document items that have `doc(hidden)`.
128 pub document_hidden: bool,
129 /// Any passes manually selected by the user.
131 /// Be aware: This option can come both from the CLI and from crate attributes!
132 pub manual_passes: Vec<String>,
133 /// Whether to display warnings during doc generation or while gathering doctests. By default,
134 /// all non-rustdoc-specific lints are allowed when generating docs.
135 pub display_warnings: bool,
136 /// Whether to run the `calculate-doc-coverage` pass, which counts the number of public items
137 /// with and without documentation.
138 pub show_coverage: bool,
140 // Options that alter generated documentation pages
141 /// Crate version to note on the sidebar of generated docs.
142 pub crate_version: Option<String>,
143 /// Collected options specific to outputting final pages.
144 pub render_options: RenderOptions,
145 /// Output format rendering (used only for "show-coverage" option for the moment)
146 pub output_format: Option<OutputFormat>,
149 impl fmt::Debug for Options {
150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151 struct FmtExterns<'a>(&'a Externs);
153 impl<'a> fmt::Debug for FmtExterns<'a> {
154 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155 f.debug_map().entries(self.0.iter()).finish()
159 f.debug_struct("Options")
160 .field("input", &self.input)
161 .field("crate_name", &self.crate_name)
162 .field("proc_macro_crate", &self.proc_macro_crate)
163 .field("error_format", &self.error_format)
164 .field("libs", &self.libs)
165 .field("externs", &FmtExterns(&self.externs))
166 .field("cfgs", &self.cfgs)
167 .field("codegen_options", &"...")
168 .field("debugging_options", &"...")
169 .field("target", &self.target)
170 .field("edition", &self.edition)
171 .field("maybe_sysroot", &self.maybe_sysroot)
172 .field("lint_opts", &self.lint_opts)
173 .field("describe_lints", &self.describe_lints)
174 .field("lint_cap", &self.lint_cap)
175 .field("should_test", &self.should_test)
176 .field("test_args", &self.test_args)
177 .field("persist_doctests", &self.persist_doctests)
178 .field("default_passes", &self.default_passes)
179 .field("document_private", &self.document_private)
180 .field("document_hidden", &self.document_hidden)
181 .field("manual_passes", &self.manual_passes)
182 .field("display_warnings", &self.display_warnings)
183 .field("show_coverage", &self.show_coverage)
184 .field("crate_version", &self.crate_version)
185 .field("render_options", &self.render_options)
186 .field("runtool", &self.runtool)
187 .field("runtool_args", &self.runtool_args)
188 .field("enable-per-target-ignores", &self.enable_per_target_ignores)
193 /// Configuration options for the HTML page-creation process.
194 #[derive(Clone, Debug)]
195 pub struct RenderOptions {
196 /// Output directory to generate docs into. Defaults to `doc`.
198 /// External files to insert into generated pages.
199 pub external_html: ExternalHtml,
200 /// A pre-populated `IdMap` with the default headings and any headings added by Markdown files
201 /// processed by `external_html`.
203 /// If present, playground URL to use in the "Run" button added to code samples.
205 /// Be aware: This option can come both from the CLI and from crate attributes!
206 pub playground_url: Option<String>,
207 /// Whether to sort modules alphabetically on a module page instead of using declaration order.
208 /// `true` by default.
210 // FIXME(misdreavus): the flag name is `--sort-modules-by-appearance` but the meaning is
211 // inverted once read.
212 pub sort_modules_alphabetically: bool,
213 /// List of themes to extend the docs with. Original argument name is included to assist in
214 /// displaying errors if it fails a theme check.
215 pub themes: Vec<PathBuf>,
216 /// If present, CSS file that contains rules to add to the default CSS.
217 pub extension_css: Option<PathBuf>,
218 /// A map of crate names to the URL to use instead of querying the crate's `html_root_url`.
219 pub extern_html_root_urls: BTreeMap<String, String>,
220 /// If present, suffix added to CSS/JavaScript files when referencing them in generated pages.
221 pub resource_suffix: String,
222 /// Whether to run the static CSS/JavaScript through a minifier when outputting them. `true` by
225 // FIXME(misdreavus): the flag name is `--disable-minification` but the meaning is inverted
227 pub enable_minification: bool,
228 /// Whether to create an index page in the root of the output directory. If this is true but
229 /// `enable_index_page` is None, generate a static listing of crates instead.
230 pub enable_index_page: bool,
231 /// A file to use as the index page at the root of the output directory. Overrides
232 /// `enable_index_page` to be true if set.
233 pub index_page: Option<PathBuf>,
234 /// An optional path to use as the location of static files. If not set, uses combinations of
235 /// `../` to reach the documentation root.
236 pub static_root_path: Option<String>,
238 // Options specific to reading standalone Markdown files
239 /// Whether to generate a table of contents on the output file when reading a standalone
241 pub markdown_no_toc: bool,
242 /// Additional CSS files to link in pages generated from standalone Markdown files.
243 pub markdown_css: Vec<String>,
244 /// If present, playground URL to use in the "Run" button added to code samples generated from
245 /// standalone Markdown files. If not present, `playground_url` is used.
246 pub markdown_playground_url: Option<String>,
247 /// If false, the `select` element to have search filtering by crates on rendered docs
248 /// won't be generated.
249 pub generate_search_filter: bool,
250 /// Option (disabled by default) to generate files used by RLS and some other tools.
251 pub generate_redirect_pages: bool,
255 /// Parses the given command-line for options. If an error message or other early-return has
256 /// been printed, returns `Err` with the exit code.
257 pub fn from_matches(matches: &getopts::Matches) -> Result<Options, i32> {
258 // Check for unstable options.
259 nightly_options::check_nightly_options(&matches, &opts());
261 if matches.opt_present("h") || matches.opt_present("help") {
262 crate::usage("rustdoc");
264 } else if matches.opt_present("version") {
265 rustc_driver::version("rustdoc", &matches);
269 if matches.opt_strs("passes") == ["list"] {
270 println!("Available passes for running rustdoc:");
271 for pass in passes::PASSES {
272 println!("{:>20} - {}", pass.name, pass.description);
274 println!("\nDefault passes for rustdoc:");
275 for p in passes::DEFAULT_PASSES {
276 print!("{:>20}", p.pass.name);
277 println_condition(p.condition);
280 if nightly_options::is_nightly_build() {
281 println!("\nPasses run with `--show-coverage`:");
282 for p in passes::COVERAGE_PASSES {
283 print!("{:>20}", p.pass.name);
284 println_condition(p.condition);
288 fn println_condition(condition: Condition) {
291 Always => println!(),
292 WhenDocumentPrivate => println!(" (when --document-private-items)"),
293 WhenNotDocumentPrivate => println!(" (when not --document-private-items)"),
294 WhenNotDocumentHidden => println!(" (when not --document-hidden-items)"),
301 let color = config::parse_color(&matches);
302 let (json_rendered, _artifacts) = config::parse_json(&matches);
303 let error_format = config::parse_error_format(&matches, color, json_rendered);
305 let codegen_options = build_codegen_options(matches, error_format);
306 let debugging_options = build_debugging_options(matches, error_format);
308 let diag = new_handler(error_format, None, &debugging_options);
310 // check for deprecated options
311 check_deprecated_options(&matches, &diag);
313 let to_check = matches.opt_strs("check-theme");
314 if !to_check.is_empty() {
315 let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
318 println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
319 for theme_file in to_check.iter() {
320 print!(" - Checking \"{}\"...", theme_file);
321 let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag);
322 if !differences.is_empty() || !success {
325 if !differences.is_empty() {
326 println!("{}", differences.join("\n"));
338 if matches.free.is_empty() {
339 diag.struct_err("missing file operand").emit();
342 if matches.free.len() > 1 {
343 diag.struct_err("too many file operands").emit();
346 let input = PathBuf::from(&matches.free[0]);
351 .map(|s| SearchPath::from_cli_opt(s, error_format))
353 let externs = parse_externs(&matches, &debugging_options, error_format);
354 let extern_html_root_urls = match parse_extern_html_roots(&matches) {
357 diag.struct_err(err).emit();
362 let test_args = matches.opt_strs("test-args");
363 let test_args: Vec<String> =
364 test_args.iter().flat_map(|s| s.split_whitespace()).map(|s| s.to_string()).collect();
366 let should_test = matches.opt_present("test");
369 matches.opt_str("o").map(|s| PathBuf::from(&s)).unwrap_or_else(|| PathBuf::from("doc"));
370 let cfgs = matches.opt_strs("cfg");
372 let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
374 if let Some(ref p) = extension_css {
376 diag.struct_err("option --extend-css argument must be a file").emit();
381 let mut themes = Vec::new();
382 if matches.opt_present("theme") {
383 let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
385 for (theme_file, theme_s) in
386 matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
388 if !theme_file.is_file() {
389 diag.struct_err(&format!("invalid argument: \"{}\"", theme_s))
390 .help("arguments to --theme must be files")
394 if theme_file.extension() != Some(OsStr::new("css")) {
395 diag.struct_err(&format!("invalid argument: \"{}\"", theme_s)).emit();
398 let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
400 diag.struct_err(&format!("error loading theme file: \"{}\"", theme_s)).emit();
402 } else if !ret.is_empty() {
403 diag.struct_warn(&format!(
404 "theme file \"{}\" is missing CSS rules from the \
408 .warn("the theme may appear incorrect when loaded")
410 "to see what rules are missing, call `rustdoc \
411 --check-theme \"{}\"`",
416 themes.push(theme_file);
420 let edition = if let Some(e) = matches.opt_str("edition") {
424 diag.struct_err("could not parse edition").emit();
432 let mut id_map = html::markdown::IdMap::new();
433 id_map.populate(html::render::initial_ids());
434 let external_html = match ExternalHtml::load(
435 &matches.opt_strs("html-in-header"),
436 &matches.opt_strs("html-before-content"),
437 &matches.opt_strs("html-after-content"),
438 &matches.opt_strs("markdown-before-content"),
439 &matches.opt_strs("markdown-after-content"),
446 None => return Err(3),
449 match matches.opt_str("r").as_ref().map(|s| &**s) {
450 Some("rust") | None => {}
452 diag.struct_err(&format!("unknown input format: {}", s)).emit();
457 let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
458 if let Some(ref index_page) = index_page {
459 if !index_page.is_file() {
460 diag.struct_err("option `--index-page` argument must be a file").emit();
466 matches.opt_str("target").map_or(TargetTriple::from_triple(host_triple()), |target| {
467 if target.ends_with(".json") {
468 TargetTriple::TargetPath(PathBuf::from(target))
470 TargetTriple::TargetTriple(target)
474 let show_coverage = matches.opt_present("show-coverage");
476 let default_passes = if matches.opt_present("no-defaults") {
477 passes::DefaultPassOption::None
478 } else if show_coverage {
479 passes::DefaultPassOption::Coverage
481 passes::DefaultPassOption::Default
483 let manual_passes = matches.opt_strs("passes");
485 let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
488 diag.struct_err(&format!("unknown crate type: {}", e)).emit();
493 let output_format = match matches.opt_str("output-format") {
494 Some(s) => match OutputFormat::try_from(s.as_str()) {
496 if o.is_json() && !show_coverage {
497 diag.struct_err("json output format isn't supported for doc generation")
500 } else if !o.is_json() && show_coverage {
502 "html output format isn't supported for the --show-coverage option",
510 diag.struct_err(&e).emit();
516 let crate_name = matches.opt_str("crate-name");
517 let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
518 let playground_url = matches.opt_str("playground-url");
519 let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
520 let display_warnings = matches.opt_present("display-warnings");
521 let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
522 let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
523 let enable_minification = !matches.opt_present("disable-minification");
524 let markdown_no_toc = matches.opt_present("markdown-no-toc");
525 let markdown_css = matches.opt_strs("markdown-css");
526 let markdown_playground_url = matches.opt_str("markdown-playground-url");
527 let crate_version = matches.opt_str("crate-version");
528 let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
529 let static_root_path = matches.opt_str("static-root-path");
530 let generate_search_filter = !matches.opt_present("disable-per-crate-search");
531 let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
532 let generate_redirect_pages = matches.opt_present("generate-redirect-pages");
533 let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
534 let codegen_options_strs = matches.opt_strs("C");
535 let debugging_options_strs = matches.opt_strs("Z");
536 let lib_strs = matches.opt_strs("L");
537 let extern_strs = matches.opt_strs("extern");
538 let runtool = matches.opt_str("runtool");
539 let runtool_args = matches.opt_strs("runtool-arg");
540 let enable_per_target_ignores = matches.opt_present("enable-per-target-ignores");
541 let document_private = matches.opt_present("document-private-items");
542 let document_hidden = matches.opt_present("document-hidden-items");
544 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
557 codegen_options_strs,
559 debugging_options_strs,
578 enable_per_target_ignores,
580 render_options: RenderOptions {
585 sort_modules_alphabetically,
588 extern_html_root_urls,
596 markdown_playground_url,
597 generate_search_filter,
598 generate_redirect_pages,
604 /// Returns `true` if the file given as `self.input` is a Markdown file.
605 pub fn markdown_input(&self) -> bool {
606 self.input.extension().map_or(false, |e| e == "md" || e == "markdown")
610 /// Prints deprecation warnings for deprecated options
611 fn check_deprecated_options(matches: &getopts::Matches, diag: &rustc_errors::Handler) {
612 let deprecated_flags = ["input-format", "output-format", "no-defaults", "passes"];
614 for flag in deprecated_flags.iter() {
615 if matches.opt_present(flag) {
616 if *flag == "output-format" && matches.opt_present("show-coverage") {
620 diag.struct_warn(&format!("the '{}' flag is considered deprecated", flag));
622 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
623 for more information",
626 if *flag == "no-defaults" {
627 err.help("you may want to use --document-private-items");
634 let removed_flags = ["plugins", "plugin-path"];
636 for &flag in removed_flags.iter() {
637 if matches.opt_present(flag) {
638 diag.struct_warn(&format!("the '{}' flag no longer functions", flag))
639 .warn("see CVE-2018-1000622")
645 /// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
646 /// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
647 /// describing the issue.
648 fn parse_extern_html_roots(
649 matches: &getopts::Matches,
650 ) -> Result<BTreeMap<String, String>, &'static str> {
651 let mut externs = BTreeMap::new();
652 for arg in &matches.opt_strs("extern-html-root-url") {
653 let mut parts = arg.splitn(2, '=');
654 let name = parts.next().ok_or("--extern-html-root-url must not be empty")?;
655 let url = parts.next().ok_or("--extern-html-root-url must be of the form name=url")?;
656 externs.insert(name.to_string(), url.to_string());