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