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