]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/config.rs
Auto merge of #60955 - agnxy:rename-assoc, r=oli-obk,Centril
[rust.git] / src / librustdoc / config.rs
1 use std::collections::BTreeMap;
2 use std::fmt;
3 use std::path::PathBuf;
4
5 use errors;
6 use errors::emitter::{ColorConfig, HumanReadableErrorType};
7 use getopts;
8 use rustc::lint::Level;
9 use rustc::session::early_error;
10 use rustc::session::config::{CodegenOptions, DebuggingOptions, ErrorOutputType, Externs};
11 use rustc::session::config::{nightly_options, build_codegen_options, build_debugging_options,
12                              get_cmd_lint_options, ExternEntry};
13 use rustc::session::search_paths::SearchPath;
14 use rustc_driver;
15 use rustc_target::spec::TargetTriple;
16 use syntax::edition::{Edition, DEFAULT_EDITION};
17
18 use crate::core::new_handler;
19 use crate::externalfiles::ExternalHtml;
20 use crate::html;
21 use crate::html::{static_files};
22 use crate::html::markdown::{IdMap};
23 use crate::opts;
24 use crate::passes::{self, DefaultPassOption};
25 use crate::theme;
26
27 /// Configuration options for rustdoc.
28 #[derive(Clone)]
29 pub struct Options {
30     // Basic options / Options passed directly to rustc
31
32     /// The crate root or Markdown file to load.
33     pub input: PathBuf,
34     /// The name of the crate being documented.
35     pub crate_name: Option<String>,
36     /// How to format errors and warnings.
37     pub error_format: ErrorOutputType,
38     /// Library search paths to hand to the compiler.
39     pub libs: Vec<SearchPath>,
40     /// The list of external crates to link against.
41     pub externs: Externs,
42     /// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`.
43     pub cfgs: Vec<String>,
44     /// Codegen options to hand to the compiler.
45     pub codegen_options: CodegenOptions,
46     /// Debugging (`-Z`) options to pass to the compiler.
47     pub debugging_options: DebuggingOptions,
48     /// The target used to compile the crate against.
49     pub target: Option<TargetTriple>,
50     /// Edition used when reading the crate. Defaults to "2015". Also used by default when
51     /// compiling doctests from the crate.
52     pub edition: Edition,
53     /// The path to the sysroot. Used during the compilation process.
54     pub maybe_sysroot: Option<PathBuf>,
55     /// Linker to use when building doctests.
56     pub linker: Option<PathBuf>,
57     /// Lint information passed over the command-line.
58     pub lint_opts: Vec<(String, Level)>,
59     /// Whether to ask rustc to describe the lints it knows. Practically speaking, this will not be
60     /// used, since we abort if we have no input file, but it's included for completeness.
61     pub describe_lints: bool,
62     /// What level to cap lints at.
63     pub lint_cap: Option<Level>,
64
65     // Options specific to running doctests
66
67     /// Whether we should run doctests instead of generating docs.
68     pub should_test: bool,
69     /// List of arguments to pass to the test harness, if running tests.
70     pub test_args: Vec<String>,
71     /// Optional path to persist the doctest executables to, defaults to a
72     /// temporary directory if not set.
73     pub persist_doctests: Option<PathBuf>,
74
75     // Options that affect the documentation process
76
77     /// The selected default set of passes to use.
78     ///
79     /// Be aware: This option can come both from the CLI and from crate attributes!
80     pub default_passes: DefaultPassOption,
81     /// Any passes manually selected by the user.
82     ///
83     /// Be aware: This option can come both from the CLI and from crate attributes!
84     pub manual_passes: Vec<String>,
85     /// Whether to display warnings during doc generation or while gathering doctests. By default,
86     /// all non-rustdoc-specific lints are allowed when generating docs.
87     pub display_warnings: bool,
88     /// Whether to run the `calculate-doc-coverage` pass, which counts the number of public items
89     /// with and without documentation.
90     pub show_coverage: bool,
91
92     // Options that alter generated documentation pages
93
94     /// Crate version to note on the sidebar of generated docs.
95     pub crate_version: Option<String>,
96     /// Collected options specific to outputting final pages.
97     pub render_options: RenderOptions,
98 }
99
100 impl fmt::Debug for Options {
101     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102         struct FmtExterns<'a>(&'a Externs);
103
104         impl<'a> fmt::Debug for FmtExterns<'a> {
105             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106                 f.debug_map()
107                     .entries(self.0.iter())
108                     .finish()
109             }
110         }
111
112         f.debug_struct("Options")
113             .field("input", &self.input)
114             .field("crate_name", &self.crate_name)
115             .field("error_format", &self.error_format)
116             .field("libs", &self.libs)
117             .field("externs", &FmtExterns(&self.externs))
118             .field("cfgs", &self.cfgs)
119             .field("codegen_options", &"...")
120             .field("debugging_options", &"...")
121             .field("target", &self.target)
122             .field("edition", &self.edition)
123             .field("maybe_sysroot", &self.maybe_sysroot)
124             .field("linker", &self.linker)
125             .field("lint_opts", &self.lint_opts)
126             .field("describe_lints", &self.describe_lints)
127             .field("lint_cap", &self.lint_cap)
128             .field("should_test", &self.should_test)
129             .field("test_args", &self.test_args)
130             .field("persist_doctests", &self.persist_doctests)
131             .field("default_passes", &self.default_passes)
132             .field("manual_passes", &self.manual_passes)
133             .field("display_warnings", &self.display_warnings)
134             .field("show_coverage", &self.show_coverage)
135             .field("crate_version", &self.crate_version)
136             .field("render_options", &self.render_options)
137             .finish()
138     }
139 }
140
141 /// Configuration options for the HTML page-creation process.
142 #[derive(Clone, Debug)]
143 pub struct RenderOptions {
144     /// Output directory to generate docs into. Defaults to `doc`.
145     pub output: PathBuf,
146     /// External files to insert into generated pages.
147     pub external_html: ExternalHtml,
148     /// A pre-populated `IdMap` with the default headings and any headings added by Markdown files
149     /// processed by `external_html`.
150     pub id_map: IdMap,
151     /// If present, playground URL to use in the "Run" button added to code samples.
152     ///
153     /// Be aware: This option can come both from the CLI and from crate attributes!
154     pub playground_url: Option<String>,
155     /// Whether to sort modules alphabetically on a module page instead of using declaration order.
156     /// `true` by default.
157     //
158     // FIXME(misdreavus): the flag name is `--sort-modules-by-appearance` but the meaning is
159     // inverted once read.
160     pub sort_modules_alphabetically: bool,
161     /// List of themes to extend the docs with. Original argument name is included to assist in
162     /// displaying errors if it fails a theme check.
163     pub themes: Vec<PathBuf>,
164     /// If present, CSS file that contains rules to add to the default CSS.
165     pub extension_css: Option<PathBuf>,
166     /// A map of crate names to the URL to use instead of querying the crate's `html_root_url`.
167     pub extern_html_root_urls: BTreeMap<String, String>,
168     /// If present, suffix added to CSS/JavaScript files when referencing them in generated pages.
169     pub resource_suffix: String,
170     /// Whether to run the static CSS/JavaScript through a minifier when outputting them. `true` by
171     /// default.
172     //
173     // FIXME(misdreavus): the flag name is `--disable-minification` but the meaning is inverted
174     // once read.
175     pub enable_minification: bool,
176     /// Whether to create an index page in the root of the output directory. If this is true but
177     /// `enable_index_page` is None, generate a static listing of crates instead.
178     pub enable_index_page: bool,
179     /// A file to use as the index page at the root of the output directory. Overrides
180     /// `enable_index_page` to be true if set.
181     pub index_page: Option<PathBuf>,
182     /// An optional path to use as the location of static files. If not set, uses combinations of
183     /// `../` to reach the documentation root.
184     pub static_root_path: Option<String>,
185
186     // Options specific to reading standalone Markdown files
187
188     /// Whether to generate a table of contents on the output file when reading a standalone
189     /// Markdown file.
190     pub markdown_no_toc: bool,
191     /// Additional CSS files to link in pages generated from standalone Markdown files.
192     pub markdown_css: Vec<String>,
193     /// If present, playground URL to use in the "Run" button added to code samples generated from
194     /// standalone Markdown files. If not present, `playground_url` is used.
195     pub markdown_playground_url: Option<String>,
196     /// If false, the `select` element to have search filtering by crates on rendered docs
197     /// won't be generated.
198     pub generate_search_filter: bool,
199     /// Option (disabled by default) to generate files used by RLS and some other tools.
200     pub generate_redirect_pages: bool,
201 }
202
203 impl Options {
204     /// Parses the given command-line for options. If an error message or other early-return has
205     /// been printed, returns `Err` with the exit code.
206     pub fn from_matches(matches: &getopts::Matches) -> Result<Options, i32> {
207         // Check for unstable options.
208         nightly_options::check_nightly_options(&matches, &opts());
209
210         if matches.opt_present("h") || matches.opt_present("help") {
211             crate::usage("rustdoc");
212             return Err(0);
213         } else if matches.opt_present("version") {
214             rustc_driver::version("rustdoc", &matches);
215             return Err(0);
216         }
217
218         if matches.opt_strs("passes") == ["list"] {
219             println!("Available passes for running rustdoc:");
220             for pass in passes::PASSES {
221                 println!("{:>20} - {}", pass.name, pass.description);
222             }
223             println!("\nDefault passes for rustdoc:");
224             for &name in passes::DEFAULT_PASSES {
225                 println!("{:>20}", name);
226             }
227             println!("\nPasses run with `--document-private-items`:");
228             for &name in passes::DEFAULT_PRIVATE_PASSES {
229                 println!("{:>20}", name);
230             }
231
232             if nightly_options::is_nightly_build() {
233                 println!("\nPasses run with `--show-coverage`:");
234                 for &name in passes::DEFAULT_COVERAGE_PASSES {
235                     println!("{:>20}", name);
236                 }
237                 println!("\nPasses run with `--show-coverage --document-private-items`:");
238                 for &name in passes::PRIVATE_COVERAGE_PASSES {
239                     println!("{:>20}", name);
240                 }
241             }
242
243             return Err(0);
244         }
245
246         let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
247             Some("auto") => ColorConfig::Auto,
248             Some("always") => ColorConfig::Always,
249             Some("never") => ColorConfig::Never,
250             None => ColorConfig::Auto,
251             Some(arg) => {
252                 early_error(ErrorOutputType::default(),
253                             &format!("argument for --color must be `auto`, `always` or `never` \
254                                       (instead was `{}`)", arg));
255             }
256         };
257         // FIXME: deduplicate this code from the identical code in librustc/session/config.rs
258         let error_format = match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
259             None |
260             Some("human") => ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color)),
261             Some("json") => ErrorOutputType::Json {
262                 pretty: false,
263                 json_rendered: HumanReadableErrorType::Default(ColorConfig::Never),
264             },
265             Some("pretty-json") => ErrorOutputType::Json {
266                 pretty: true,
267                 json_rendered: HumanReadableErrorType::Default(ColorConfig::Never),
268             },
269             Some("short") => ErrorOutputType::HumanReadable(HumanReadableErrorType::Short(color)),
270             Some(arg) => {
271                 early_error(ErrorOutputType::default(),
272                             &format!("argument for --error-format must be `human`, `json` or \
273                                       `short` (instead was `{}`)", arg));
274             }
275         };
276
277         let codegen_options = build_codegen_options(matches, error_format);
278         let debugging_options = build_debugging_options(matches, error_format);
279
280         let diag = new_handler(error_format,
281                                None,
282                                debugging_options.treat_err_as_bug,
283                                debugging_options.ui_testing);
284
285         // check for deprecated options
286         check_deprecated_options(&matches, &diag);
287
288         let to_check = matches.opt_strs("theme-checker");
289         if !to_check.is_empty() {
290             let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
291             let mut errors = 0;
292
293             println!("rustdoc: [theme-checker] Starting tests!");
294             for theme_file in to_check.iter() {
295                 print!(" - Checking \"{}\"...", theme_file);
296                 let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag);
297                 if !differences.is_empty() || !success {
298                     println!(" FAILED");
299                     errors += 1;
300                     if !differences.is_empty() {
301                         println!("{}", differences.join("\n"));
302                     }
303                 } else {
304                     println!(" OK");
305                 }
306             }
307             if errors != 0 {
308                 return Err(1);
309             }
310             return Err(0);
311         }
312
313         if matches.free.is_empty() {
314             diag.struct_err("missing file operand").emit();
315             return Err(1);
316         }
317         if matches.free.len() > 1 {
318             diag.struct_err("too many file operands").emit();
319             return Err(1);
320         }
321         let input = PathBuf::from(&matches.free[0]);
322
323         let libs = matches.opt_strs("L").iter()
324             .map(|s| SearchPath::from_cli_opt(s, error_format))
325             .collect();
326         let externs = match parse_externs(&matches) {
327             Ok(ex) => ex,
328             Err(err) => {
329                 diag.struct_err(&err).emit();
330                 return Err(1);
331             }
332         };
333         let extern_html_root_urls = match parse_extern_html_roots(&matches) {
334             Ok(ex) => ex,
335             Err(err) => {
336                 diag.struct_err(err).emit();
337                 return Err(1);
338             }
339         };
340
341         let test_args = matches.opt_strs("test-args");
342         let test_args: Vec<String> = test_args.iter()
343                                               .flat_map(|s| s.split_whitespace())
344                                               .map(|s| s.to_string())
345                                               .collect();
346
347         let should_test = matches.opt_present("test");
348
349         let output = matches.opt_str("o")
350                             .map(|s| PathBuf::from(&s))
351                             .unwrap_or_else(|| PathBuf::from("doc"));
352         let mut cfgs = matches.opt_strs("cfg");
353         cfgs.push("rustdoc".to_string());
354         if should_test {
355             cfgs.push("test".to_string());
356         }
357
358         let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
359
360         if let Some(ref p) = extension_css {
361             if !p.is_file() {
362                 diag.struct_err("option --extend-css argument must be a file").emit();
363                 return Err(1);
364             }
365         }
366
367         let mut themes = Vec::new();
368         if matches.opt_present("themes") {
369             let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
370
371             for (theme_file, theme_s) in matches.opt_strs("themes")
372                                                 .iter()
373                                                 .map(|s| (PathBuf::from(&s), s.to_owned())) {
374                 if !theme_file.is_file() {
375                     diag.struct_err("option --themes arguments must all be files").emit();
376                     return Err(1);
377                 }
378                 let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
379                 if !success || !ret.is_empty() {
380                     diag.struct_err(&format!("invalid theme: \"{}\"", theme_s))
381                         .help("check what's wrong with the --theme-checker option")
382                         .emit();
383                     return Err(1);
384                 }
385                 themes.push(theme_file);
386             }
387         }
388
389         let edition = if let Some(e) = matches.opt_str("edition") {
390             match e.parse() {
391                 Ok(e) => e,
392                 Err(_) => {
393                     diag.struct_err("could not parse edition").emit();
394                     return Err(1);
395                 }
396             }
397         } else {
398             DEFAULT_EDITION
399         };
400
401         let mut id_map = html::markdown::IdMap::new();
402         id_map.populate(html::render::initial_ids());
403         let external_html = match ExternalHtml::load(
404                 &matches.opt_strs("html-in-header"),
405                 &matches.opt_strs("html-before-content"),
406                 &matches.opt_strs("html-after-content"),
407                 &matches.opt_strs("markdown-before-content"),
408                 &matches.opt_strs("markdown-after-content"),
409                 &diag, &mut id_map, edition) {
410             Some(eh) => eh,
411             None => return Err(3),
412         };
413
414         match matches.opt_str("r").as_ref().map(|s| &**s) {
415             Some("rust") | None => {}
416             Some(s) => {
417                 diag.struct_err(&format!("unknown input format: {}", s)).emit();
418                 return Err(1);
419             }
420         }
421
422         match matches.opt_str("w").as_ref().map(|s| &**s) {
423             Some("html") | None => {}
424             Some(s) => {
425                 diag.struct_err(&format!("unknown output format: {}", s)).emit();
426                 return Err(1);
427             }
428         }
429
430         let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
431         if let Some(ref index_page) = index_page {
432             if !index_page.is_file() {
433                 diag.struct_err("option `--index-page` argument must be a file").emit();
434                 return Err(1);
435             }
436         }
437
438         let target = matches.opt_str("target").map(|target| {
439             if target.ends_with(".json") {
440                 TargetTriple::TargetPath(PathBuf::from(target))
441             } else {
442                 TargetTriple::TargetTriple(target)
443             }
444         });
445
446         let show_coverage = matches.opt_present("show-coverage");
447         let document_private = matches.opt_present("document-private-items");
448
449         let default_passes = if matches.opt_present("no-defaults") {
450             passes::DefaultPassOption::None
451         } else if show_coverage && document_private {
452             passes::DefaultPassOption::PrivateCoverage
453         } else if show_coverage {
454             passes::DefaultPassOption::Coverage
455         } else if document_private {
456             passes::DefaultPassOption::Private
457         } else {
458             passes::DefaultPassOption::Default
459         };
460         let manual_passes = matches.opt_strs("passes");
461
462         let crate_name = matches.opt_str("crate-name");
463         let playground_url = matches.opt_str("playground-url");
464         let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
465         let display_warnings = matches.opt_present("display-warnings");
466         let linker = matches.opt_str("linker").map(PathBuf::from);
467         let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
468         let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
469         let enable_minification = !matches.opt_present("disable-minification");
470         let markdown_no_toc = matches.opt_present("markdown-no-toc");
471         let markdown_css = matches.opt_strs("markdown-css");
472         let markdown_playground_url = matches.opt_str("markdown-playground-url");
473         let crate_version = matches.opt_str("crate-version");
474         let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
475         let static_root_path = matches.opt_str("static-root-path");
476         let generate_search_filter = !matches.opt_present("disable-per-crate-search");
477         let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
478         let generate_redirect_pages = matches.opt_present("generate-redirect-pages");
479
480         let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
481
482         Ok(Options {
483             input,
484             crate_name,
485             error_format,
486             libs,
487             externs,
488             cfgs,
489             codegen_options,
490             debugging_options,
491             target,
492             edition,
493             maybe_sysroot,
494             linker,
495             lint_opts,
496             describe_lints,
497             lint_cap,
498             should_test,
499             test_args,
500             default_passes,
501             manual_passes,
502             display_warnings,
503             show_coverage,
504             crate_version,
505             persist_doctests,
506             render_options: RenderOptions {
507                 output,
508                 external_html,
509                 id_map,
510                 playground_url,
511                 sort_modules_alphabetically,
512                 themes,
513                 extension_css,
514                 extern_html_root_urls,
515                 resource_suffix,
516                 enable_minification,
517                 enable_index_page,
518                 index_page,
519                 static_root_path,
520                 markdown_no_toc,
521                 markdown_css,
522                 markdown_playground_url,
523                 generate_search_filter,
524                 generate_redirect_pages,
525             }
526         })
527     }
528
529     /// Returns `true` if the file given as `self.input` is a Markdown file.
530     pub fn markdown_input(&self) -> bool {
531         self.input.extension()
532             .map_or(false, |e| e == "md" || e == "markdown")
533     }
534 }
535
536 /// Prints deprecation warnings for deprecated options
537 fn check_deprecated_options(matches: &getopts::Matches, diag: &errors::Handler) {
538     let deprecated_flags = [
539        "input-format",
540        "output-format",
541        "no-defaults",
542        "passes",
543     ];
544
545     for flag in deprecated_flags.iter() {
546         if matches.opt_present(flag) {
547             let mut err = diag.struct_warn(&format!("the '{}' flag is considered deprecated",
548                                                     flag));
549             err.warn("please see https://github.com/rust-lang/rust/issues/44136");
550
551             if *flag == "no-defaults" {
552                 err.help("you may want to use --document-private-items");
553             }
554
555             err.emit();
556         }
557     }
558
559     let removed_flags = [
560         "plugins",
561         "plugin-path",
562     ];
563
564     for &flag in removed_flags.iter() {
565         if matches.opt_present(flag) {
566             diag.struct_warn(&format!("the '{}' flag no longer functions", flag))
567                 .warn("see CVE-2018-1000622")
568                 .emit();
569         }
570     }
571 }
572
573 /// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
574 /// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
575 /// describing the issue.
576 fn parse_extern_html_roots(
577     matches: &getopts::Matches,
578 ) -> Result<BTreeMap<String, String>, &'static str> {
579     let mut externs = BTreeMap::new();
580     for arg in &matches.opt_strs("extern-html-root-url") {
581         let mut parts = arg.splitn(2, '=');
582         let name = parts.next().ok_or("--extern-html-root-url must not be empty")?;
583         let url = parts.next().ok_or("--extern-html-root-url must be of the form name=url")?;
584         externs.insert(name.to_string(), url.to_string());
585     }
586
587     Ok(externs)
588 }
589
590 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
591 /// returns a map mapping crate names to their paths or else an
592 /// error message.
593 // FIXME(eddyb) This shouldn't be duplicated with `rustc::session`.
594 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
595     let mut externs: BTreeMap<_, ExternEntry> = BTreeMap::new();
596     for arg in &matches.opt_strs("extern") {
597         let mut parts = arg.splitn(2, '=');
598         let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
599         let location = parts.next().map(|s| s.to_string());
600         if location.is_none() && !nightly_options::is_unstable_enabled(matches) {
601             return Err("the `-Z unstable-options` flag must also be passed to \
602                         enable `--extern crate_name` without `=path`".to_string());
603         }
604         let name = name.to_string();
605         // For Rustdoc purposes, we can treat all externs as public
606         externs.entry(name)
607             .or_default()
608             .locations.insert(location.clone());
609     }
610     Ok(Externs::new(externs))
611 }