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