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