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