]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/config.rs
Auto merge of #65474 - Mark-Simulacrum:rustc-dev-split, r=pietroalbini
[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, host_triple, ExternEntry};
13 use rustc::session::search_paths::SearchPath;
14 use rustc_driver;
15 use rustc_target::spec::TargetTriple;
16 use syntax::edition::{Edition, DEFAULT_EDITION};
17
18 use crate::core::new_handler;
19 use crate::externalfiles::ExternalHtml;
20 use crate::html;
21 use crate::html::{static_files};
22 use crate::html::markdown::{IdMap};
23 use crate::opts;
24 use crate::passes::{self, DefaultPassOption};
25 use crate::theme;
26
27 /// Configuration options for rustdoc.
28 #[derive(Clone)]
29 pub struct Options {
30     // Basic options / Options passed directly to rustc
31
32     /// The crate root or Markdown file to load.
33     pub input: PathBuf,
34     /// The name of the crate being documented.
35     pub crate_name: Option<String>,
36     /// Whether or not this is a proc-macro crate
37     pub proc_macro_crate: bool,
38     /// How to format errors and warnings.
39     pub error_format: ErrorOutputType,
40     /// Library search paths to hand to the compiler.
41     pub libs: Vec<SearchPath>,
42     /// Library search paths strings to hand to the compiler.
43     pub lib_strs: Vec<String>,
44     /// The list of external crates to link against.
45     pub externs: Externs,
46     /// The list of external crates strings to link against.
47     pub extern_strs: Vec<String>,
48     /// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`.
49     pub cfgs: Vec<String>,
50     /// Codegen options to hand to the compiler.
51     pub codegen_options: CodegenOptions,
52     /// Codegen options strings to hand to the compiler.
53     pub codegen_options_strs: Vec<String>,
54     /// Debugging (`-Z`) options to pass to the compiler.
55     pub debugging_options: DebuggingOptions,
56     /// Debugging (`-Z`) options strings to pass to the compiler.
57     pub debugging_options_strs: Vec<String>,
58     /// The target used to compile the crate against.
59     pub target: TargetTriple,
60     /// Edition used when reading the crate. Defaults to "2015". Also used by default when
61     /// compiling doctests from the crate.
62     pub edition: Edition,
63     /// The path to the sysroot. Used during the compilation process.
64     pub maybe_sysroot: Option<PathBuf>,
65     /// Lint information passed over the command-line.
66     pub lint_opts: Vec<(String, Level)>,
67     /// Whether to ask rustc to describe the lints it knows. Practically speaking, this will not be
68     /// used, since we abort if we have no input file, but it's included for completeness.
69     pub describe_lints: bool,
70     /// What level to cap lints at.
71     pub lint_cap: Option<Level>,
72
73     // Options specific to running doctests
74
75     /// Whether we should run doctests instead of generating docs.
76     pub should_test: bool,
77     /// List of arguments to pass to the test harness, if running tests.
78     pub test_args: Vec<String>,
79     /// Optional path to persist the doctest executables to, defaults to a
80     /// temporary directory if not set.
81     pub persist_doctests: Option<PathBuf>,
82     /// Runtool to run doctests with
83     pub runtool: Option<String>,
84     /// Arguments to pass to the runtool
85     pub runtool_args: Vec<String>,
86     /// Whether to allow ignoring doctests on a per-target basis
87     /// For example, using ignore-foo to ignore running the doctest on any target that
88     /// contains "foo" as a substring
89     pub enable_per_target_ignores: bool,
90
91     /// The path to a rustc-like binary to build tests with. If not set, we
92     /// default to loading from $sysroot/bin/rustc.
93     pub test_builder: Option<PathBuf>,
94
95     // Options that affect the documentation process
96
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     /// Any passes manually selected by the user.
102     ///
103     /// Be aware: This option can come both from the CLI and from crate attributes!
104     pub manual_passes: Vec<String>,
105     /// Whether to display warnings during doc generation or while gathering doctests. By default,
106     /// all non-rustdoc-specific lints are allowed when generating docs.
107     pub display_warnings: bool,
108     /// Whether to run the `calculate-doc-coverage` pass, which counts the number of public items
109     /// with and without documentation.
110     pub show_coverage: bool,
111
112     // Options that alter generated documentation pages
113
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()
127                     .entries(self.0.iter())
128                     .finish()
129             }
130         }
131
132         f.debug_struct("Options")
133             .field("input", &self.input)
134             .field("crate_name", &self.crate_name)
135             .field("proc_macro_crate", &self.proc_macro_crate)
136             .field("error_format", &self.error_format)
137             .field("libs", &self.libs)
138             .field("externs", &FmtExterns(&self.externs))
139             .field("cfgs", &self.cfgs)
140             .field("codegen_options", &"...")
141             .field("debugging_options", &"...")
142             .field("target", &self.target)
143             .field("edition", &self.edition)
144             .field("maybe_sysroot", &self.maybe_sysroot)
145             .field("lint_opts", &self.lint_opts)
146             .field("describe_lints", &self.describe_lints)
147             .field("lint_cap", &self.lint_cap)
148             .field("should_test", &self.should_test)
149             .field("test_args", &self.test_args)
150             .field("persist_doctests", &self.persist_doctests)
151             .field("default_passes", &self.default_passes)
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
211     /// Whether to generate a table of contents on the output file when reading a standalone
212     /// Markdown file.
213     pub markdown_no_toc: bool,
214     /// Additional CSS files to link in pages generated from standalone Markdown files.
215     pub markdown_css: Vec<String>,
216     /// If present, playground URL to use in the "Run" button added to code samples generated from
217     /// standalone Markdown files. If not present, `playground_url` is used.
218     pub markdown_playground_url: Option<String>,
219     /// If false, the `select` element to have search filtering by crates on rendered docs
220     /// won't be generated.
221     pub generate_search_filter: bool,
222     /// Option (disabled by default) to generate files used by RLS and some other tools.
223     pub generate_redirect_pages: bool,
224 }
225
226 impl Options {
227     /// Parses the given command-line for options. If an error message or other early-return has
228     /// been printed, returns `Err` with the exit code.
229     pub fn from_matches(matches: &getopts::Matches) -> Result<Options, i32> {
230         // Check for unstable options.
231         nightly_options::check_nightly_options(&matches, &opts());
232
233         if matches.opt_present("h") || matches.opt_present("help") {
234             crate::usage("rustdoc");
235             return Err(0);
236         } else if matches.opt_present("version") {
237             rustc_driver::version("rustdoc", &matches);
238             return Err(0);
239         }
240
241         if matches.opt_strs("passes") == ["list"] {
242             println!("Available passes for running rustdoc:");
243             for pass in passes::PASSES {
244                 println!("{:>20} - {}", pass.name, pass.description);
245             }
246             println!("\nDefault passes for rustdoc:");
247             for pass in passes::DEFAULT_PASSES {
248                 println!("{:>20}", pass.name);
249             }
250             println!("\nPasses run with `--document-private-items`:");
251             for pass in passes::DEFAULT_PRIVATE_PASSES {
252                 println!("{:>20}", pass.name);
253             }
254
255             if nightly_options::is_nightly_build() {
256                 println!("\nPasses run with `--show-coverage`:");
257                 for pass in passes::DEFAULT_COVERAGE_PASSES {
258                     println!("{:>20}", pass.name);
259                 }
260                 println!("\nPasses run with `--show-coverage --document-private-items`:");
261                 for pass in passes::PRIVATE_COVERAGE_PASSES {
262                     println!("{:>20}", pass.name);
263                 }
264             }
265
266             return Err(0);
267         }
268
269         let color = session::config::parse_color(&matches);
270         let (json_rendered, _artifacts) = session::config::parse_json(&matches);
271         let error_format = session::config::parse_error_format(&matches, color, json_rendered);
272
273         let codegen_options = build_codegen_options(matches, error_format);
274         let debugging_options = build_debugging_options(matches, error_format);
275
276         let diag = new_handler(error_format,
277                                None,
278                                debugging_options.treat_err_as_bug,
279                                debugging_options.ui_testing);
280
281         // check for deprecated options
282         check_deprecated_options(&matches, &diag);
283
284         let to_check = matches.opt_strs("theme-checker");
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: [theme-checker] Starting tests!");
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.opt_strs("L").iter()
320             .map(|s| SearchPath::from_cli_opt(s, error_format))
321             .collect();
322         let externs = match parse_externs(&matches) {
323             Ok(ex) => ex,
324             Err(err) => {
325                 diag.struct_err(&err).emit();
326                 return Err(1);
327             }
328         };
329         let extern_html_root_urls = match parse_extern_html_roots(&matches) {
330             Ok(ex) => ex,
331             Err(err) => {
332                 diag.struct_err(err).emit();
333                 return Err(1);
334             }
335         };
336
337         let test_args = matches.opt_strs("test-args");
338         let test_args: Vec<String> = test_args.iter()
339                                               .flat_map(|s| s.split_whitespace())
340                                               .map(|s| s.to_string())
341                                               .collect();
342
343         let should_test = matches.opt_present("test");
344
345         let output = matches.opt_str("o")
346                             .map(|s| PathBuf::from(&s))
347                             .unwrap_or_else(|| PathBuf::from("doc"));
348         let cfgs = matches.opt_strs("cfg");
349
350         let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
351
352         if let Some(ref p) = extension_css {
353             if !p.is_file() {
354                 diag.struct_err("option --extend-css argument must be a file").emit();
355                 return Err(1);
356             }
357         }
358
359         let mut themes = Vec::new();
360         if matches.opt_present("themes") {
361             let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
362
363             for (theme_file, theme_s) in matches.opt_strs("themes")
364                                                 .iter()
365                                                 .map(|s| (PathBuf::from(&s), s.to_owned())) {
366                 if !theme_file.is_file() {
367                     diag.struct_err("option --themes arguments must all be files").emit();
368                     return Err(1);
369                 }
370                 let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
371                 if !success || !ret.is_empty() {
372                     diag.struct_err(&format!("invalid theme: \"{}\"", theme_s))
373                         .help("check what's wrong with the --theme-checker option")
374                         .emit();
375                     return Err(1);
376                 }
377                 themes.push(theme_file);
378             }
379         }
380
381         let edition = if let Some(e) = matches.opt_str("edition") {
382             match e.parse() {
383                 Ok(e) => e,
384                 Err(_) => {
385                     diag.struct_err("could not parse edition").emit();
386                     return Err(1);
387                 }
388             }
389         } else {
390             DEFAULT_EDITION
391         };
392
393         let mut id_map = html::markdown::IdMap::new();
394         id_map.populate(html::render::initial_ids());
395         let external_html = match ExternalHtml::load(
396                 &matches.opt_strs("html-in-header"),
397                 &matches.opt_strs("html-before-content"),
398                 &matches.opt_strs("html-after-content"),
399                 &matches.opt_strs("markdown-before-content"),
400                 &matches.opt_strs("markdown-after-content"),
401                 &diag, &mut id_map, edition, &None) {
402             Some(eh) => eh,
403             None => return Err(3),
404         };
405
406         match matches.opt_str("r").as_ref().map(|s| &**s) {
407             Some("rust") | None => {}
408             Some(s) => {
409                 diag.struct_err(&format!("unknown input format: {}", s)).emit();
410                 return Err(1);
411             }
412         }
413
414         match matches.opt_str("w").as_ref().map(|s| &**s) {
415             Some("html") | None => {}
416             Some(s) => {
417                 diag.struct_err(&format!("unknown output format: {}", s)).emit();
418                 return Err(1);
419             }
420         }
421
422         let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
423         if let Some(ref index_page) = index_page {
424             if !index_page.is_file() {
425                 diag.struct_err("option `--index-page` argument must be a file").emit();
426                 return Err(1);
427             }
428         }
429
430         let target = matches.opt_str("target").map_or(
431             TargetTriple::from_triple(host_triple()),
432             |target| {
433             if target.ends_with(".json") {
434                 TargetTriple::TargetPath(PathBuf::from(target))
435             } else {
436                 TargetTriple::TargetTriple(target)
437             }
438         });
439
440         let show_coverage = matches.opt_present("show-coverage");
441         let document_private = matches.opt_present("document-private-items");
442
443         let default_passes = if matches.opt_present("no-defaults") {
444             passes::DefaultPassOption::None
445         } else if show_coverage && document_private {
446             passes::DefaultPassOption::PrivateCoverage
447         } else if show_coverage {
448             passes::DefaultPassOption::Coverage
449         } else if document_private {
450             passes::DefaultPassOption::Private
451         } else {
452             passes::DefaultPassOption::Default
453         };
454         let manual_passes = matches.opt_strs("passes");
455
456         let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
457             Ok(types) => types,
458             Err(e) =>{
459                 diag.struct_err(&format!("unknown crate type: {}", e)).emit();
460                 return Err(1);
461             }
462         };
463
464         let crate_name = matches.opt_str("crate-name");
465         let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
466         let playground_url = matches.opt_str("playground-url");
467         let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
468         let display_warnings = matches.opt_present("display-warnings");
469         let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
470         let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
471         let enable_minification = !matches.opt_present("disable-minification");
472         let markdown_no_toc = matches.opt_present("markdown-no-toc");
473         let markdown_css = matches.opt_strs("markdown-css");
474         let markdown_playground_url = matches.opt_str("markdown-playground-url");
475         let crate_version = matches.opt_str("crate-version");
476         let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
477         let static_root_path = matches.opt_str("static-root-path");
478         let generate_search_filter = !matches.opt_present("disable-per-crate-search");
479         let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
480         let generate_redirect_pages = matches.opt_present("generate-redirect-pages");
481         let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
482         let codegen_options_strs = matches.opt_strs("C");
483         let debugging_options_strs = matches.opt_strs("Z");
484         let lib_strs = matches.opt_strs("L");
485         let extern_strs = matches.opt_strs("extern");
486         let runtool = matches.opt_str("runtool");
487         let runtool_args = matches.opt_strs("runtool-arg");
488         let enable_per_target_ignores = matches.opt_present("enable-per-target-ignores");
489
490         let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
491
492         Ok(Options {
493             input,
494             crate_name,
495             proc_macro_crate,
496             error_format,
497             libs,
498             lib_strs,
499             externs,
500             extern_strs,
501             cfgs,
502             codegen_options,
503             codegen_options_strs,
504             debugging_options,
505             debugging_options_strs,
506             target,
507             edition,
508             maybe_sysroot,
509             lint_opts,
510             describe_lints,
511             lint_cap,
512             should_test,
513             test_args,
514             default_passes,
515             manual_passes,
516             display_warnings,
517             show_coverage,
518             crate_version,
519             persist_doctests,
520             runtool,
521             runtool_args,
522             enable_per_target_ignores,
523             test_builder,
524             render_options: RenderOptions {
525                 output,
526                 external_html,
527                 id_map,
528                 playground_url,
529                 sort_modules_alphabetically,
530                 themes,
531                 extension_css,
532                 extern_html_root_urls,
533                 resource_suffix,
534                 enable_minification,
535                 enable_index_page,
536                 index_page,
537                 static_root_path,
538                 markdown_no_toc,
539                 markdown_css,
540                 markdown_playground_url,
541                 generate_search_filter,
542                 generate_redirect_pages,
543             }
544         })
545     }
546
547     /// Returns `true` if the file given as `self.input` is a Markdown file.
548     pub fn markdown_input(&self) -> bool {
549         self.input.extension()
550             .map_or(false, |e| e == "md" || e == "markdown")
551     }
552 }
553
554 /// Prints deprecation warnings for deprecated options
555 fn check_deprecated_options(matches: &getopts::Matches, diag: &errors::Handler) {
556     let deprecated_flags = [
557        "input-format",
558        "output-format",
559        "no-defaults",
560        "passes",
561     ];
562
563     for flag in deprecated_flags.iter() {
564         if matches.opt_present(flag) {
565             let mut err = diag.struct_warn(&format!("the '{}' flag is considered deprecated",
566                                                     flag));
567             err.warn("please see https://github.com/rust-lang/rust/issues/44136");
568
569             if *flag == "no-defaults" {
570                 err.help("you may want to use --document-private-items");
571             }
572
573             err.emit();
574         }
575     }
576
577     let removed_flags = [
578         "plugins",
579         "plugin-path",
580     ];
581
582     for &flag in removed_flags.iter() {
583         if matches.opt_present(flag) {
584             diag.struct_warn(&format!("the '{}' flag no longer functions", flag))
585                 .warn("see CVE-2018-1000622")
586                 .emit();
587         }
588     }
589 }
590
591 /// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
592 /// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
593 /// describing the issue.
594 fn parse_extern_html_roots(
595     matches: &getopts::Matches,
596 ) -> Result<BTreeMap<String, String>, &'static str> {
597     let mut externs = BTreeMap::new();
598     for arg in &matches.opt_strs("extern-html-root-url") {
599         let mut parts = arg.splitn(2, '=');
600         let name = parts.next().ok_or("--extern-html-root-url must not be empty")?;
601         let url = parts.next().ok_or("--extern-html-root-url must be of the form name=url")?;
602         externs.insert(name.to_string(), url.to_string());
603     }
604
605     Ok(externs)
606 }
607
608 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
609 /// returns a map mapping crate names to their paths or else an
610 /// error message.
611 // FIXME(eddyb) This shouldn't be duplicated with `rustc::session`.
612 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
613     let mut externs: BTreeMap<_, ExternEntry> = BTreeMap::new();
614     for arg in &matches.opt_strs("extern") {
615         let mut parts = arg.splitn(2, '=');
616         let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
617         let location = parts.next().map(|s| s.to_string());
618         if location.is_none() && !nightly_options::is_unstable_enabled(matches) {
619             return Err("the `-Z unstable-options` flag must also be passed to \
620                         enable `--extern crate_name` without `=path`".to_string());
621         }
622         let name = name.to_string();
623         // For Rustdoc purposes, we can treat all externs as public
624         externs.entry(name)
625             .or_default()
626             .locations.insert(location.clone());
627     }
628     Ok(Externs::new(externs))
629 }