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