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