]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/config.rs
improve error messages and documentation
[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::{CrateType, parse_crate_types_from_list};
11 use rustc::session::config::{CodegenOptions, DebuggingOptions, ErrorOutputType, Externs};
12 use rustc::session::config::{nightly_options, build_codegen_options, build_debugging_options,
13                              get_cmd_lint_options, host_triple, ExternEntry};
14 use rustc::session::search_paths::SearchPath;
15 use rustc_driver;
16 use rustc_target::spec::TargetTriple;
17 use syntax::edition::{Edition, DEFAULT_EDITION};
18
19 use crate::core::new_handler;
20 use crate::externalfiles::ExternalHtml;
21 use crate::html;
22 use crate::html::{static_files};
23 use crate::html::markdown::{IdMap};
24 use crate::opts;
25 use crate::passes::{self, DefaultPassOption};
26 use crate::theme;
27
28 /// Configuration options for rustdoc.
29 #[derive(Clone)]
30 pub struct Options {
31     // Basic options / Options passed directly to rustc
32
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
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
98     /// The selected default set of passes to use.
99     ///
100     /// Be aware: This option can come both from the CLI and from crate attributes!
101     pub default_passes: DefaultPassOption,
102     /// Any passes manually selected by the user.
103     ///
104     /// Be aware: This option can come both from the CLI and from crate attributes!
105     pub manual_passes: Vec<String>,
106     /// Whether to display warnings during doc generation or while gathering doctests. By default,
107     /// all non-rustdoc-specific lints are allowed when generating docs.
108     pub display_warnings: bool,
109     /// Whether to run the `calculate-doc-coverage` pass, which counts the number of public items
110     /// with and without documentation.
111     pub show_coverage: bool,
112
113     // Options that alter generated documentation pages
114
115     /// Crate version to note on the sidebar of generated docs.
116     pub crate_version: Option<String>,
117     /// Collected options specific to outputting final pages.
118     pub render_options: RenderOptions,
119 }
120
121 impl fmt::Debug for Options {
122     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123         struct FmtExterns<'a>(&'a Externs);
124
125         impl<'a> fmt::Debug for FmtExterns<'a> {
126             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127                 f.debug_map()
128                     .entries(self.0.iter())
129                     .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("manual_passes", &self.manual_passes)
154             .field("display_warnings", &self.display_warnings)
155             .field("show_coverage", &self.show_coverage)
156             .field("crate_version", &self.crate_version)
157             .field("render_options", &self.render_options)
158             .field("runtool", &self.runtool)
159             .field("runtool_args", &self.runtool_args)
160             .field("enable-per-target-ignores", &self.enable_per_target_ignores)
161             .finish()
162     }
163 }
164
165 /// Configuration options for the HTML page-creation process.
166 #[derive(Clone, Debug)]
167 pub struct RenderOptions {
168     /// Output directory to generate docs into. Defaults to `doc`.
169     pub output: PathBuf,
170     /// External files to insert into generated pages.
171     pub external_html: ExternalHtml,
172     /// A pre-populated `IdMap` with the default headings and any headings added by Markdown files
173     /// processed by `external_html`.
174     pub id_map: IdMap,
175     /// If present, playground URL to use in the "Run" button added to code samples.
176     ///
177     /// Be aware: This option can come both from the CLI and from crate attributes!
178     pub playground_url: Option<String>,
179     /// Whether to sort modules alphabetically on a module page instead of using declaration order.
180     /// `true` by default.
181     //
182     // FIXME(misdreavus): the flag name is `--sort-modules-by-appearance` but the meaning is
183     // inverted once read.
184     pub sort_modules_alphabetically: bool,
185     /// List of themes to extend the docs with. Original argument name is included to assist in
186     /// displaying errors if it fails a theme check.
187     pub themes: Vec<PathBuf>,
188     /// If present, CSS file that contains rules to add to the default CSS.
189     pub extension_css: Option<PathBuf>,
190     /// A map of crate names to the URL to use instead of querying the crate's `html_root_url`.
191     pub extern_html_root_urls: BTreeMap<String, String>,
192     /// If present, suffix added to CSS/JavaScript files when referencing them in generated pages.
193     pub resource_suffix: String,
194     /// Whether to run the static CSS/JavaScript through a minifier when outputting them. `true` by
195     /// default.
196     //
197     // FIXME(misdreavus): the flag name is `--disable-minification` but the meaning is inverted
198     // once read.
199     pub enable_minification: bool,
200     /// Whether to create an index page in the root of the output directory. If this is true but
201     /// `enable_index_page` is None, generate a static listing of crates instead.
202     pub enable_index_page: bool,
203     /// A file to use as the index page at the root of the output directory. Overrides
204     /// `enable_index_page` to be true if set.
205     pub index_page: Option<PathBuf>,
206     /// An optional path to use as the location of static files. If not set, uses combinations of
207     /// `../` to reach the documentation root.
208     pub static_root_path: Option<String>,
209
210     // Options specific to reading standalone Markdown files
211
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 pass in passes::DEFAULT_PASSES {
249                 println!("{:>20}", pass.name);
250             }
251             println!("\nPasses run with `--document-private-items`:");
252             for pass in passes::DEFAULT_PRIVATE_PASSES {
253                 println!("{:>20}", pass.name);
254             }
255
256             if nightly_options::is_nightly_build() {
257                 println!("\nPasses run with `--show-coverage`:");
258                 for pass in passes::DEFAULT_COVERAGE_PASSES {
259                     println!("{:>20}", pass.name);
260                 }
261                 println!("\nPasses run with `--show-coverage --document-private-items`:");
262                 for pass in passes::PRIVATE_COVERAGE_PASSES {
263                     println!("{:>20}", pass.name);
264                 }
265             }
266
267             return Err(0);
268         }
269
270         let color = session::config::parse_color(&matches);
271         let (json_rendered, _artifacts) = session::config::parse_json(&matches);
272         let error_format = session::config::parse_error_format(&matches, color, json_rendered);
273
274         let codegen_options = build_codegen_options(matches, error_format);
275         let debugging_options = build_debugging_options(matches, error_format);
276
277         let diag = new_handler(error_format,
278                                None,
279                                debugging_options.treat_err_as_bug,
280                                debugging_options.ui_testing);
281
282         // check for deprecated options
283         check_deprecated_options(&matches, &diag);
284
285         let to_check = matches.opt_strs("check-theme");
286         if !to_check.is_empty() {
287             let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
288             let mut errors = 0;
289
290             println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
291             for theme_file in to_check.iter() {
292                 print!(" - Checking \"{}\"...", theme_file);
293                 let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag);
294                 if !differences.is_empty() || !success {
295                     println!(" FAILED");
296                     errors += 1;
297                     if !differences.is_empty() {
298                         println!("{}", differences.join("\n"));
299                     }
300                 } else {
301                     println!(" OK");
302                 }
303             }
304             if errors != 0 {
305                 return Err(1);
306             }
307             return Err(0);
308         }
309
310         if matches.free.is_empty() {
311             diag.struct_err("missing file operand").emit();
312             return Err(1);
313         }
314         if matches.free.len() > 1 {
315             diag.struct_err("too many file operands").emit();
316             return Err(1);
317         }
318         let input = PathBuf::from(&matches.free[0]);
319
320         let libs = matches.opt_strs("L").iter()
321             .map(|s| SearchPath::from_cli_opt(s, error_format))
322             .collect();
323         let externs = match parse_externs(&matches) {
324             Ok(ex) => ex,
325             Err(err) => {
326                 diag.struct_err(&err).emit();
327                 return Err(1);
328             }
329         };
330         let extern_html_root_urls = match parse_extern_html_roots(&matches) {
331             Ok(ex) => ex,
332             Err(err) => {
333                 diag.struct_err(err).emit();
334                 return Err(1);
335             }
336         };
337
338         let test_args = matches.opt_strs("test-args");
339         let test_args: Vec<String> = test_args.iter()
340                                               .flat_map(|s| s.split_whitespace())
341                                               .map(|s| s.to_string())
342                                               .collect();
343
344         let should_test = matches.opt_present("test");
345
346         let output = matches.opt_str("o")
347                             .map(|s| PathBuf::from(&s))
348                             .unwrap_or_else(|| PathBuf::from("doc"));
349         let cfgs = matches.opt_strs("cfg");
350
351         let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
352
353         if let Some(ref p) = extension_css {
354             if !p.is_file() {
355                 diag.struct_err("option --extend-css argument must be a file").emit();
356                 return Err(1);
357             }
358         }
359
360         let mut themes = Vec::new();
361         if matches.opt_present("theme") {
362             let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
363
364             for (theme_file, theme_s) in matches.opt_strs("theme")
365                                                 .iter()
366                                                 .map(|s| (PathBuf::from(&s), s.to_owned())) {
367                 if !theme_file.is_file() {
368                     diag.struct_err(&format!("invalid argument: \"{}\"", theme_s))
369                         .help("arguments to --theme must be files")
370                         .emit();
371                     return Err(1);
372                 }
373                 if theme_file.extension() != Some(OsStr::new("css")) {
374                     diag.struct_err(&format!("invalid argument: \"{}\"", theme_s))
375                         .emit();
376                     return Err(1);
377                 }
378                 let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
379                 if !success {
380                     diag.struct_err(&format!("error loading theme file: \"{}\"", theme_s)).emit();
381                     return Err(1);
382                 } else if !ret.is_empty() {
383                     diag.struct_warn(&format!("theme file \"{}\" is missing CSS rules from the \
384                                                default theme", theme_s))
385                         .warn("the theme may appear incorrect when loaded")
386                         .help(&format!("to see what rules are missing, call `rustdoc \
387                                         --check-theme \"{}\"`", theme_s))
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, &mut id_map, edition, &None) {
415             Some(eh) => eh,
416             None => return Err(3),
417         };
418
419         match matches.opt_str("r").as_ref().map(|s| &**s) {
420             Some("rust") | None => {}
421             Some(s) => {
422                 diag.struct_err(&format!("unknown input format: {}", s)).emit();
423                 return Err(1);
424             }
425         }
426
427         match matches.opt_str("w").as_ref().map(|s| &**s) {
428             Some("html") | None => {}
429             Some(s) => {
430                 diag.struct_err(&format!("unknown output format: {}", s)).emit();
431                 return Err(1);
432             }
433         }
434
435         let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
436         if let Some(ref index_page) = index_page {
437             if !index_page.is_file() {
438                 diag.struct_err("option `--index-page` argument must be a file").emit();
439                 return Err(1);
440             }
441         }
442
443         let target = matches.opt_str("target").map_or(
444             TargetTriple::from_triple(host_triple()),
445             |target| {
446             if target.ends_with(".json") {
447                 TargetTriple::TargetPath(PathBuf::from(target))
448             } else {
449                 TargetTriple::TargetTriple(target)
450             }
451         });
452
453         let show_coverage = matches.opt_present("show-coverage");
454         let document_private = matches.opt_present("document-private-items");
455
456         let default_passes = if matches.opt_present("no-defaults") {
457             passes::DefaultPassOption::None
458         } else if show_coverage && document_private {
459             passes::DefaultPassOption::PrivateCoverage
460         } else if show_coverage {
461             passes::DefaultPassOption::Coverage
462         } else if document_private {
463             passes::DefaultPassOption::Private
464         } else {
465             passes::DefaultPassOption::Default
466         };
467         let manual_passes = matches.opt_strs("passes");
468
469         let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
470             Ok(types) => types,
471             Err(e) =>{
472                 diag.struct_err(&format!("unknown crate type: {}", e)).emit();
473                 return Err(1);
474             }
475         };
476
477         let crate_name = matches.opt_str("crate-name");
478         let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
479         let playground_url = matches.opt_str("playground-url");
480         let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
481         let display_warnings = matches.opt_present("display-warnings");
482         let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
483         let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
484         let enable_minification = !matches.opt_present("disable-minification");
485         let markdown_no_toc = matches.opt_present("markdown-no-toc");
486         let markdown_css = matches.opt_strs("markdown-css");
487         let markdown_playground_url = matches.opt_str("markdown-playground-url");
488         let crate_version = matches.opt_str("crate-version");
489         let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
490         let static_root_path = matches.opt_str("static-root-path");
491         let generate_search_filter = !matches.opt_present("disable-per-crate-search");
492         let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
493         let generate_redirect_pages = matches.opt_present("generate-redirect-pages");
494         let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
495         let codegen_options_strs = matches.opt_strs("C");
496         let debugging_options_strs = matches.opt_strs("Z");
497         let lib_strs = matches.opt_strs("L");
498         let extern_strs = matches.opt_strs("extern");
499         let runtool = matches.opt_str("runtool");
500         let runtool_args = matches.opt_strs("runtool-arg");
501         let enable_per_target_ignores = matches.opt_present("enable-per-target-ignores");
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             manual_passes,
529             display_warnings,
530             show_coverage,
531             crate_version,
532             persist_doctests,
533             runtool,
534             runtool_args,
535             enable_per_target_ignores,
536             test_builder,
537             render_options: RenderOptions {
538                 output,
539                 external_html,
540                 id_map,
541                 playground_url,
542                 sort_modules_alphabetically,
543                 themes,
544                 extension_css,
545                 extern_html_root_urls,
546                 resource_suffix,
547                 enable_minification,
548                 enable_index_page,
549                 index_page,
550                 static_root_path,
551                 markdown_no_toc,
552                 markdown_css,
553                 markdown_playground_url,
554                 generate_search_filter,
555                 generate_redirect_pages,
556             }
557         })
558     }
559
560     /// Returns `true` if the file given as `self.input` is a Markdown file.
561     pub fn markdown_input(&self) -> bool {
562         self.input.extension()
563             .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: &errors::Handler) {
569     let deprecated_flags = [
570        "input-format",
571        "output-format",
572        "no-defaults",
573        "passes",
574     ];
575
576     for flag in deprecated_flags.iter() {
577         if matches.opt_present(flag) {
578             let mut err = diag.struct_warn(&format!("the '{}' flag is considered deprecated",
579                                                     flag));
580             err.warn("please see https://github.com/rust-lang/rust/issues/44136");
581
582             if *flag == "no-defaults" {
583                 err.help("you may want to use --document-private-items");
584             }
585
586             err.emit();
587         }
588     }
589
590     let removed_flags = [
591         "plugins",
592         "plugin-path",
593     ];
594
595     for &flag in removed_flags.iter() {
596         if matches.opt_present(flag) {
597             diag.struct_warn(&format!("the '{}' flag no longer functions", flag))
598                 .warn("see CVE-2018-1000622")
599                 .emit();
600         }
601     }
602 }
603
604 /// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
605 /// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
606 /// describing the issue.
607 fn parse_extern_html_roots(
608     matches: &getopts::Matches,
609 ) -> Result<BTreeMap<String, String>, &'static str> {
610     let mut externs = BTreeMap::new();
611     for arg in &matches.opt_strs("extern-html-root-url") {
612         let mut parts = arg.splitn(2, '=');
613         let name = parts.next().ok_or("--extern-html-root-url must not be empty")?;
614         let url = parts.next().ok_or("--extern-html-root-url must be of the form name=url")?;
615         externs.insert(name.to_string(), url.to_string());
616     }
617
618     Ok(externs)
619 }
620
621 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
622 /// returns a map mapping crate names to their paths or else an
623 /// error message.
624 /// Also handles `--extern-private` which for the purposes of rustdoc
625 /// we can treat as `--extern`
626 // FIXME(eddyb) This shouldn't be duplicated with `rustc::session`.
627 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
628     let mut externs: BTreeMap<_, ExternEntry> = BTreeMap::new();
629     for arg in matches.opt_strs("extern").iter().chain(matches.opt_strs("extern-private").iter()) {
630         let mut parts = arg.splitn(2, '=');
631         let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
632         let location = parts.next().map(|s| s.to_string());
633         let name = name.to_string();
634         // For Rustdoc purposes, we can treat all externs as public
635         externs.entry(name)
636             .or_default()
637             .locations.insert(location.clone());
638     }
639     Ok(Externs::new(externs))
640 }