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