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