]> git.lizzy.rs Git - rust.git/blob - src/config/mod.rs
tests: augment heuristics tests
[rust.git] / src / config / mod.rs
1 use std::cell::Cell;
2 use std::default::Default;
3 use std::fs::File;
4 use std::io::{Error, ErrorKind, Read};
5 use std::path::{Path, PathBuf};
6 use std::{env, fs};
7
8 use regex::Regex;
9 use thiserror::Error;
10
11 use crate::config::config_type::ConfigType;
12 #[allow(unreachable_pub)]
13 pub use crate::config::file_lines::{FileLines, FileName, Range};
14 #[allow(unreachable_pub)]
15 pub use crate::config::lists::*;
16 #[allow(unreachable_pub)]
17 pub use crate::config::options::*;
18
19 #[macro_use]
20 pub(crate) mod config_type;
21 #[macro_use]
22 pub(crate) mod options;
23
24 pub(crate) mod file_lines;
25 pub(crate) mod license;
26 pub(crate) mod lists;
27
28 // This macro defines configuration options used in rustfmt. Each option
29 // is defined as follows:
30 //
31 // `name: value type, default value, is stable, description;`
32 create_config! {
33     // Fundamental stuff
34     max_width: usize, 100, true, "Maximum width of each line";
35     hard_tabs: bool, false, true, "Use tab characters for indentation, spaces for alignment";
36     tab_spaces: usize, 4, true, "Number of spaces per tab";
37     newline_style: NewlineStyle, NewlineStyle::Auto, true, "Unix or Windows line endings";
38     indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items";
39
40     // Width Heuristics
41     use_small_heuristics: Heuristics, Heuristics::Default, true, "Whether to use different \
42         formatting for items and expressions if they satisfy a heuristic notion of 'small'";
43     width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
44         "'small' heuristic values";
45     fn_call_width: usize, 60, true, "Maximum width of the args of a function call before \
46         falling back to vertical formatting.";
47     attr_fn_like_width: usize, 70, true, "Maximum width of the args of a function-like \
48         attributes before falling back to vertical formatting.";
49     struct_lit_width: usize, 18, true, "Maximum width in the body of a struct lit before \
50         falling back to vertical formatting.";
51     struct_variant_width: usize, 35, true, "Maximum width in the body of a struct variant before \
52         falling back to vertical formatting.";
53     array_width: usize, 60, true,  "Maximum width of an array literal before falling \
54         back to vertical formatting.";
55     chain_width: usize, 60, true, "Maximum length of a chain to fit on a single line.";
56     single_line_if_else_max_width: usize, 50, true, "Maximum line length for single line if-else \
57         expressions. A value of zero means always break if-else expressions.";
58
59     // Comments. macros, and strings
60     wrap_comments: bool, false, false, "Break comments to fit on the line";
61     format_code_in_doc_comments: bool, false, false, "Format the code snippet in doc comments.";
62     comment_width: usize, 80, false,
63         "Maximum length of comments. No effect unless wrap_comments = true";
64     normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible";
65     normalize_doc_attributes: bool, false, false, "Normalize doc attributes as doc comments";
66     license_template_path: String, String::default(), false,
67         "Beginning of file must match license template";
68     format_strings: bool, false, false, "Format string literals where necessary";
69     format_macro_matchers: bool, false, false,
70         "Format the metavariable matching patterns in macros";
71     format_macro_bodies: bool, true, false, "Format the bodies of macros";
72
73     // Single line expressions and items
74     empty_item_single_line: bool, true, false,
75         "Put empty-body functions and impls on a single line";
76     struct_lit_single_line: bool, true, false,
77         "Put small struct literals on a single line";
78     fn_single_line: bool, false, false, "Put single-expression functions on a single line";
79     where_single_line: bool, false, false, "Force where-clauses to be on a single line";
80
81     // Imports
82     imports_indent: IndentStyle, IndentStyle::Block, false, "Indent of imports";
83     imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
84     imports_granularity: ImportGranularity, ImportGranularity::Preserve, false,
85         "Merge or split imports to the provided granularity";
86     group_imports: GroupImportsTactic, GroupImportsTactic::Preserve, false,
87         "Controls the strategy for how imports are grouped together";
88     merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)";
89
90     // Ordering
91     reorder_imports: bool, true, true, "Reorder import and extern crate statements alphabetically";
92     reorder_modules: bool, true, true, "Reorder module statements alphabetically in group";
93     reorder_impl_items: bool, false, false, "Reorder impl items";
94
95     // Spaces around punctuation
96     type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
97         "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
98     space_before_colon: bool, false, false, "Leave a space before the colon";
99     space_after_colon: bool, true, false, "Leave a space after the colon";
100     spaces_around_ranges: bool, false, false, "Put spaces around the  .. and ..= range operators";
101     binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
102         "Where to put a binary operator when a binary expression goes multiline";
103
104     // Misc.
105     remove_nested_parens: bool, true, true, "Remove nested parens";
106     combine_control_expr: bool, true, false, "Combine control expressions with function calls";
107     overflow_delimited_expr: bool, false, false,
108         "Allow trailing bracket/brace delimited expressions to overflow";
109     struct_field_align_threshold: usize, 0, false,
110         "Align struct fields if their diffs fits within threshold";
111     enum_discrim_align_threshold: usize, 0, false,
112         "Align enum variants discrims, if their diffs fit within threshold";
113     match_arm_blocks: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \
114         the same line with the pattern of arms";
115     match_arm_leading_pipes: MatchArmLeadingPipe, MatchArmLeadingPipe::Never, true,
116         "Determines whether leading pipes are emitted on match arms";
117     force_multiline_blocks: bool, false, false,
118         "Force multiline closure bodies and match arms to be wrapped in a block";
119     fn_args_layout: Density, Density::Tall, true,
120         "Control the layout of arguments in a function";
121     brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items";
122     control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false,
123         "Brace style for control flow constructs";
124     trailing_semicolon: bool, true, false,
125         "Add trailing semicolon after break, continue and return";
126     trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
127         "How to handle trailing commas for lists";
128     match_block_trailing_comma: bool, false, false,
129         "Put a trailing comma after a block based match arm (non-block arms are not affected)";
130     blank_lines_upper_bound: usize, 1, false,
131         "Maximum number of blank lines which can be put between items";
132     blank_lines_lower_bound: usize, 0, false,
133         "Minimum number of blank lines which must be put between items";
134     edition: Edition, Edition::Edition2015, true, "The edition of the parser (RFC 2052)";
135     version: Version, Version::One, false, "Version of formatting rules";
136     inline_attribute_width: usize, 0, false,
137         "Write an item and its attribute on the same line \
138         if their combined width is below a threshold";
139
140     // Options that can change the source code beyond whitespace/blocks (somewhat linty things)
141     merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one";
142     use_try_shorthand: bool, false, true, "Replace uses of the try! macro by the ? shorthand";
143     use_field_init_shorthand: bool, false, true, "Use field initialization shorthand if possible";
144     force_explicit_abi: bool, true, true, "Always print the abi for extern items";
145     condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
146                                                      in tuple patterns";
147
148     // Control options (changes the operation of rustfmt, rather than the formatting)
149     color: Color, Color::Auto, false,
150         "What Color option to use when none is supplied: Always, Never, Auto";
151     required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
152         "Require a specific version of rustfmt";
153     unstable_features: bool, false, false,
154             "Enables unstable features. Only available on nightly channel";
155     disable_all_formatting: bool, false, false, "Don't reformat anything";
156     skip_children: bool, false, false, "Don't reformat out of line modules";
157     hide_parse_errors: bool, false, false, "Hide errors from the parser";
158     error_on_line_overflow: bool, false, false, "Error if unable to get all lines within max_width";
159     error_on_unformatted: bool, false, false,
160         "Error if unable to get comments or string literals within max_width, \
161          or they are left with trailing whitespaces";
162     report_todo: ReportTactic, ReportTactic::Never, false,
163         "Report all, none or unnumbered occurrences of TODO in source file comments";
164     report_fixme: ReportTactic, ReportTactic::Never, false,
165         "Report all, none or unnumbered occurrences of FIXME in source file comments";
166     ignore: IgnoreList, IgnoreList::default(), false,
167         "Skip formatting the specified files and directories";
168
169     // Not user-facing
170     verbose: Verbosity, Verbosity::Normal, false, "How much to information to emit to the user";
171     file_lines: FileLines, FileLines::all(), false,
172         "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
173          via the --file-lines option";
174     emit_mode: EmitMode, EmitMode::Files, false,
175         "What emit Mode to use when none is supplied";
176     make_backup: bool, false, false, "Backup changed files";
177     print_misformatted_file_names: bool, false, true,
178         "Prints the names of mismatched files that were formatted. Prints the names of \
179          files that would be formated when used with `--check` mode. ";
180 }
181
182 #[derive(Error, Debug)]
183 #[error("Could not output config: {0}")]
184 pub struct ToTomlError(toml::ser::Error);
185
186 impl PartialConfig {
187     pub fn to_toml(&self) -> Result<String, ToTomlError> {
188         // Non-user-facing options can't be specified in TOML
189         let mut cloned = self.clone();
190         cloned.file_lines = None;
191         cloned.verbose = None;
192         cloned.width_heuristics = None;
193         cloned.print_misformatted_file_names = None;
194         cloned.merge_imports = None;
195
196         ::toml::to_string(&cloned).map_err(ToTomlError)
197     }
198 }
199
200 impl Config {
201     pub(crate) fn version_meets_requirement(&self) -> bool {
202         if self.was_set().required_version() {
203             let version = env!("CARGO_PKG_VERSION");
204             let required_version = self.required_version();
205             if version != required_version {
206                 println!(
207                     "Error: rustfmt version ({}) doesn't match the required version ({})",
208                     version, required_version,
209                 );
210                 return false;
211             }
212         }
213
214         true
215     }
216
217     /// Constructs a `Config` from the toml file specified at `file_path`.
218     ///
219     /// This method only looks at the provided path, for a method that
220     /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
221     ///
222     /// Returns a `Config` if the config could be read and parsed from
223     /// the file, otherwise errors.
224     pub(super) fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
225         let mut file = File::open(&file_path)?;
226         let mut toml = String::new();
227         file.read_to_string(&mut toml)?;
228         Config::from_toml(&toml, file_path.parent().unwrap())
229             .map_err(|err| Error::new(ErrorKind::InvalidData, err))
230     }
231
232     /// Resolves the config for input in `dir`.
233     ///
234     /// Searches for `rustfmt.toml` beginning with `dir`, and
235     /// recursively checking parents of `dir` if no config file is found.
236     /// If no config file exists in `dir` or in any parent, a
237     /// default `Config` will be returned (and the returned path will be empty).
238     ///
239     /// Returns the `Config` to use, and the path of the project file if there was
240     /// one.
241     pub(super) fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
242         /// Try to find a project file in the given directory and its parents.
243         /// Returns the path of a the nearest project file if one exists,
244         /// or `None` if no project file was found.
245         fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
246             let mut current = if dir.is_relative() {
247                 env::current_dir()?.join(dir)
248             } else {
249                 dir.to_path_buf()
250             };
251
252             current = fs::canonicalize(current)?;
253
254             loop {
255                 match get_toml_path(&current) {
256                     Ok(Some(path)) => return Ok(Some(path)),
257                     Err(e) => return Err(e),
258                     _ => (),
259                 }
260
261                 // If the current directory has no parent, we're done searching.
262                 if !current.pop() {
263                     break;
264                 }
265             }
266
267             // If nothing was found, check in the home directory.
268             if let Some(home_dir) = dirs::home_dir() {
269                 if let Some(path) = get_toml_path(&home_dir)? {
270                     return Ok(Some(path));
271                 }
272             }
273
274             // If none was found ther either, check in the user's configuration directory.
275             if let Some(mut config_dir) = dirs::config_dir() {
276                 config_dir.push("rustfmt");
277                 if let Some(path) = get_toml_path(&config_dir)? {
278                     return Ok(Some(path));
279                 }
280             }
281
282             Ok(None)
283         }
284
285         match resolve_project_file(dir)? {
286             None => Ok((Config::default(), None)),
287             Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
288         }
289     }
290
291     pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> {
292         let parsed: ::toml::Value = toml
293             .parse()
294             .map_err(|e| format!("Could not parse TOML: {}", e))?;
295         let mut err = String::new();
296         let table = parsed
297             .as_table()
298             .ok_or_else(|| String::from("Parsed config was not table"))?;
299         for key in table.keys() {
300             if !Config::is_valid_name(key) {
301                 let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
302                 err.push_str(msg)
303             }
304         }
305         match parsed.try_into() {
306             Ok(parsed_config) => {
307                 if !err.is_empty() {
308                     eprint!("{}", err);
309                 }
310                 Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
311             }
312             Err(e) => {
313                 err.push_str("Error: Decoding config file failed:\n");
314                 err.push_str(format!("{}\n", e).as_str());
315                 err.push_str("Please check your config file.");
316                 Err(err)
317             }
318         }
319     }
320 }
321
322 /// Loads a config by checking the client-supplied options and if appropriate, the
323 /// file system (including searching the file system for overrides).
324 pub fn load_config<O: CliOptions>(
325     file_path: Option<&Path>,
326     options: Option<O>,
327 ) -> Result<(Config, Option<PathBuf>), Error> {
328     let over_ride = match options {
329         Some(ref opts) => config_path(opts)?,
330         None => None,
331     };
332
333     let result = if let Some(over_ride) = over_ride {
334         Config::from_toml_path(over_ride.as_ref()).map(|p| (p, Some(over_ride.to_owned())))
335     } else if let Some(file_path) = file_path {
336         Config::from_resolved_toml_path(file_path)
337     } else {
338         Ok((Config::default(), None))
339     };
340
341     result.map(|(mut c, p)| {
342         if let Some(options) = options {
343             options.apply_to(&mut c);
344         }
345         (c, p)
346     })
347 }
348
349 // Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
350 //
351 // Return the path if a config file exists, empty if no file exists, and Error for IO errors
352 fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
353     const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
354     for config_file_name in &CONFIG_FILE_NAMES {
355         let config_file = dir.join(config_file_name);
356         match fs::metadata(&config_file) {
357             // Only return if it's a file to handle the unlikely situation of a directory named
358             // `rustfmt.toml`.
359             Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
360             // Return the error if it's something other than `NotFound`; otherwise we didn't
361             // find the project file yet, and continue searching.
362             Err(e) => {
363                 if e.kind() != ErrorKind::NotFound {
364                     return Err(e);
365                 }
366             }
367             _ => {}
368         }
369     }
370     Ok(None)
371 }
372
373 fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
374     let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
375         Err(Error::new(
376             ErrorKind::NotFound,
377             format!(
378                 "Error: unable to find a config file for the given path: `{}`",
379                 path
380             ),
381         ))
382     };
383
384     // Read the config_path and convert to parent dir if a file is provided.
385     // If a config file cannot be found from the given path, return error.
386     match options.config_path() {
387         Some(path) if !path.exists() => config_path_not_found(path.to_str().unwrap()),
388         Some(path) if path.is_dir() => {
389             let config_file_path = get_toml_path(path)?;
390             if config_file_path.is_some() {
391                 Ok(config_file_path)
392             } else {
393                 config_path_not_found(path.to_str().unwrap())
394             }
395         }
396         path => Ok(path.map(ToOwned::to_owned)),
397     }
398 }
399
400 #[cfg(test)]
401 mod test {
402     use super::*;
403     use std::str;
404
405     #[allow(dead_code)]
406     mod mock {
407         use super::super::*;
408
409         create_config! {
410             // Options that are used by the generated functions
411             max_width: usize, 100, true, "Maximum width of each line";
412             license_template_path: String, String::default(), false,
413                 "Beginning of file must match license template";
414             required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
415                 "Require a specific version of rustfmt.";
416             ignore: IgnoreList, IgnoreList::default(), false,
417                 "Skip formatting the specified files and directories.";
418             verbose: Verbosity, Verbosity::Normal, false,
419                 "How much to information to emit to the user";
420             file_lines: FileLines, FileLines::all(), false,
421                 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
422                     via the --file-lines option";
423
424             // merge_imports deprecation
425             imports_granularity: ImportGranularity, ImportGranularity::Preserve, false,
426                 "Merge imports";
427             merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)";
428
429             // Width Heuristics
430             use_small_heuristics: Heuristics, Heuristics::Default, true,
431                 "Whether to use different formatting for items and \
432                  expressions if they satisfy a heuristic notion of 'small'.";
433             width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
434                 "'small' heuristic values";
435
436             fn_call_width: usize, 60, true, "Maximum width of the args of a function call before \
437                 falling back to vertical formatting.";
438             attr_fn_like_width: usize, 70, true, "Maximum width of the args of a function-like \
439                 attributes before falling back to vertical formatting.";
440             struct_lit_width: usize, 18, true, "Maximum width in the body of a struct lit before \
441                 falling back to vertical formatting.";
442             struct_variant_width: usize, 35, true, "Maximum width in the body of a struct \
443                 variant before falling back to vertical formatting.";
444             array_width: usize, 60, true,  "Maximum width of an array literal before falling \
445                 back to vertical formatting.";
446             chain_width: usize, 60, true, "Maximum length of a chain to fit on a single line.";
447             single_line_if_else_max_width: usize, 50, true, "Maximum line length for single \
448                 line if-else expressions. A value of zero means always break if-else expressions.";
449
450             // Options that are used by the tests
451             stable_option: bool, false, true, "A stable option";
452             unstable_option: bool, false, false, "An unstable option";
453         }
454     }
455
456     #[test]
457     fn test_config_set() {
458         let mut config = Config::default();
459         config.set().verbose(Verbosity::Quiet);
460         assert_eq!(config.verbose(), Verbosity::Quiet);
461         config.set().verbose(Verbosity::Normal);
462         assert_eq!(config.verbose(), Verbosity::Normal);
463     }
464
465     #[test]
466     fn test_config_used_to_toml() {
467         let config = Config::default();
468
469         let merge_derives = config.merge_derives();
470         let skip_children = config.skip_children();
471
472         let used_options = config.used_options();
473         let toml = used_options.to_toml().unwrap();
474         assert_eq!(
475             toml,
476             format!(
477                 "merge_derives = {}\nskip_children = {}\n",
478                 merge_derives, skip_children,
479             )
480         );
481     }
482
483     #[test]
484     fn test_was_set() {
485         let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap();
486
487         assert_eq!(config.was_set().hard_tabs(), true);
488         assert_eq!(config.was_set().verbose(), false);
489     }
490
491     #[test]
492     fn test_print_docs_exclude_unstable() {
493         use self::mock::Config;
494
495         let mut output = Vec::new();
496         Config::print_docs(&mut output, false);
497
498         let s = str::from_utf8(&output).unwrap();
499
500         assert_eq!(s.contains("stable_option"), true);
501         assert_eq!(s.contains("unstable_option"), false);
502         assert_eq!(s.contains("(unstable)"), false);
503     }
504
505     #[test]
506     fn test_print_docs_include_unstable() {
507         use self::mock::Config;
508
509         let mut output = Vec::new();
510         Config::print_docs(&mut output, true);
511
512         let s = str::from_utf8(&output).unwrap();
513         assert_eq!(s.contains("stable_option"), true);
514         assert_eq!(s.contains("unstable_option"), true);
515         assert_eq!(s.contains("(unstable)"), true);
516     }
517
518     #[test]
519     fn test_empty_string_license_template_path() {
520         let toml = r#"license_template_path = """#;
521         let config = Config::from_toml(toml, Path::new("")).unwrap();
522         assert!(config.license_template.is_none());
523     }
524
525     #[test]
526     fn test_valid_license_template_path() {
527         if !crate::is_nightly_channel!() {
528             return;
529         }
530         let toml = r#"license_template_path = "tests/license-template/lt.txt""#;
531         let config = Config::from_toml(toml, Path::new("")).unwrap();
532         assert!(config.license_template.is_some());
533     }
534
535     #[test]
536     fn test_override_existing_license_with_no_license() {
537         if !crate::is_nightly_channel!() {
538             return;
539         }
540         let toml = r#"license_template_path = "tests/license-template/lt.txt""#;
541         let mut config = Config::from_toml(toml, Path::new("")).unwrap();
542         assert!(config.license_template.is_some());
543         config.override_value("license_template_path", "");
544         assert!(config.license_template.is_none());
545     }
546
547     #[test]
548     fn test_dump_default_config() {
549         let default_config = format!(
550             r#"max_width = 100
551 hard_tabs = false
552 tab_spaces = 4
553 newline_style = "Auto"
554 indent_style = "Block"
555 use_small_heuristics = "Default"
556 fn_call_width = 60
557 attr_fn_like_width = 70
558 struct_lit_width = 18
559 struct_variant_width = 35
560 array_width = 60
561 chain_width = 60
562 single_line_if_else_max_width = 50
563 wrap_comments = false
564 format_code_in_doc_comments = false
565 comment_width = 80
566 normalize_comments = false
567 normalize_doc_attributes = false
568 license_template_path = ""
569 format_strings = false
570 format_macro_matchers = false
571 format_macro_bodies = true
572 empty_item_single_line = true
573 struct_lit_single_line = true
574 fn_single_line = false
575 where_single_line = false
576 imports_indent = "Block"
577 imports_layout = "Mixed"
578 imports_granularity = "Preserve"
579 group_imports = "Preserve"
580 reorder_imports = true
581 reorder_modules = true
582 reorder_impl_items = false
583 type_punctuation_density = "Wide"
584 space_before_colon = false
585 space_after_colon = true
586 spaces_around_ranges = false
587 binop_separator = "Front"
588 remove_nested_parens = true
589 combine_control_expr = true
590 overflow_delimited_expr = false
591 struct_field_align_threshold = 0
592 enum_discrim_align_threshold = 0
593 match_arm_blocks = true
594 match_arm_leading_pipes = "Never"
595 force_multiline_blocks = false
596 fn_args_layout = "Tall"
597 brace_style = "SameLineWhere"
598 control_brace_style = "AlwaysSameLine"
599 trailing_semicolon = true
600 trailing_comma = "Vertical"
601 match_block_trailing_comma = false
602 blank_lines_upper_bound = 1
603 blank_lines_lower_bound = 0
604 edition = "2015"
605 version = "One"
606 inline_attribute_width = 0
607 merge_derives = true
608 use_try_shorthand = false
609 use_field_init_shorthand = false
610 force_explicit_abi = true
611 condense_wildcard_suffixes = false
612 color = "Auto"
613 required_version = "{}"
614 unstable_features = false
615 disable_all_formatting = false
616 skip_children = false
617 hide_parse_errors = false
618 error_on_line_overflow = false
619 error_on_unformatted = false
620 report_todo = "Never"
621 report_fixme = "Never"
622 ignore = []
623 emit_mode = "Files"
624 make_backup = false
625 "#,
626             env!("CARGO_PKG_VERSION")
627         );
628         let toml = Config::default().all_options().to_toml().unwrap();
629         assert_eq!(&toml, &default_config);
630     }
631
632     // FIXME(#2183): these tests cannot be run in parallel because they use env vars.
633     // #[test]
634     // fn test_as_not_nightly_channel() {
635     //     let mut config = Config::default();
636     //     assert_eq!(config.was_set().unstable_features(), false);
637     //     config.set().unstable_features(true);
638     //     assert_eq!(config.was_set().unstable_features(), false);
639     // }
640
641     // #[test]
642     // fn test_as_nightly_channel() {
643     //     let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
644     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
645     //     let mut config = Config::default();
646     //     config.set().unstable_features(true);
647     //     assert_eq!(config.was_set().unstable_features(), false);
648     //     config.set().unstable_features(true);
649     //     assert_eq!(config.unstable_features(), true);
650     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
651     // }
652
653     // #[test]
654     // fn test_unstable_from_toml() {
655     //     let mut config = Config::from_toml("unstable_features = true").unwrap();
656     //     assert_eq!(config.was_set().unstable_features(), false);
657     //     let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
658     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
659     //     config = Config::from_toml("unstable_features = true").unwrap();
660     //     assert_eq!(config.was_set().unstable_features(), true);
661     //     assert_eq!(config.unstable_features(), true);
662     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
663     // }
664
665     #[cfg(test)]
666     mod deprecated_option_merge_imports {
667         use super::*;
668
669         #[test]
670         fn test_old_option_set() {
671             if !crate::is_nightly_channel!() {
672                 return;
673             }
674             let toml = r#"
675                 unstable_features = true
676                 merge_imports = true
677             "#;
678             let config = Config::from_toml(toml, Path::new("")).unwrap();
679             assert_eq!(config.imports_granularity(), ImportGranularity::Crate);
680         }
681
682         #[test]
683         fn test_both_set() {
684             if !crate::is_nightly_channel!() {
685                 return;
686             }
687             let toml = r#"
688                 unstable_features = true
689                 merge_imports = true
690                 imports_granularity = "Preserve"
691             "#;
692             let config = Config::from_toml(toml, Path::new("")).unwrap();
693             assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
694         }
695
696         #[test]
697         fn test_new_overridden() {
698             if !crate::is_nightly_channel!() {
699                 return;
700             }
701             let toml = r#"
702                 unstable_features = true
703                 merge_imports = true
704             "#;
705             let mut config = Config::from_toml(toml, Path::new("")).unwrap();
706             config.override_value("imports_granularity", "Preserve");
707             assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
708         }
709
710         #[test]
711         fn test_old_overridden() {
712             if !crate::is_nightly_channel!() {
713                 return;
714             }
715             let toml = r#"
716                 unstable_features = true
717                 imports_granularity = "Module"
718             "#;
719             let mut config = Config::from_toml(toml, Path::new("")).unwrap();
720             config.override_value("merge_imports", "true");
721             // no effect: the new option always takes precedence
722             assert_eq!(config.imports_granularity(), ImportGranularity::Module);
723         }
724     }
725
726     #[cfg(test)]
727     mod use_small_heuristics {
728         use super::*;
729
730         #[test]
731         fn test_default_sets_correct_widths() {
732             let toml = r#"
733                 use_small_heuristics = "Default"
734                 max_width = 200
735             "#;
736             let config = Config::from_toml(toml, Path::new("")).unwrap();
737             assert_eq!(config.array_width(), 120);
738             assert_eq!(config.attr_fn_like_width(), 140);
739             assert_eq!(config.chain_width(), 120);
740             assert_eq!(config.fn_call_width(), 120);
741             assert_eq!(config.single_line_if_else_max_width(), 100);
742             assert_eq!(config.struct_lit_width(), 36);
743             assert_eq!(config.struct_variant_width(), 70);
744         }
745
746         #[test]
747         fn test_max_sets_correct_widths() {
748             let toml = r#"
749                 use_small_heuristics = "Max"
750                 max_width = 120
751             "#;
752             let config = Config::from_toml(toml, Path::new("")).unwrap();
753             assert_eq!(config.array_width(), 120);
754             assert_eq!(config.attr_fn_like_width(), 120);
755             assert_eq!(config.chain_width(), 120);
756             assert_eq!(config.fn_call_width(), 120);
757             assert_eq!(config.single_line_if_else_max_width(), 120);
758             assert_eq!(config.struct_lit_width(), 120);
759             assert_eq!(config.struct_variant_width(), 120);
760         }
761
762         #[test]
763         fn test_off_sets_correct_widths() {
764             let toml = r#"
765                 use_small_heuristics = "Off"
766                 max_width = 100
767             "#;
768             let config = Config::from_toml(toml, Path::new("")).unwrap();
769             assert_eq!(config.array_width(), usize::max_value());
770             assert_eq!(config.attr_fn_like_width(), usize::max_value());
771             assert_eq!(config.chain_width(), usize::max_value());
772             assert_eq!(config.fn_call_width(), usize::max_value());
773             assert_eq!(config.single_line_if_else_max_width(), 0);
774             assert_eq!(config.struct_lit_width(), 0);
775             assert_eq!(config.struct_variant_width(), 0);
776         }
777
778         #[test]
779         fn test_override_works_with_default() {
780             let toml = r#"
781                 use_small_heuristics = "Default"
782                 array_width = 20
783                 attr_fn_like_width = 40
784                 chain_width = 20
785                 fn_call_width = 90
786                 single_line_if_else_max_width = 40
787                 struct_lit_width = 30
788                 struct_variant_width = 34
789             "#;
790             let config = Config::from_toml(toml, Path::new("")).unwrap();
791             assert_eq!(config.array_width(), 20);
792             assert_eq!(config.attr_fn_like_width(), 40);
793             assert_eq!(config.chain_width(), 20);
794             assert_eq!(config.fn_call_width(), 90);
795             assert_eq!(config.single_line_if_else_max_width(), 40);
796             assert_eq!(config.struct_lit_width(), 30);
797             assert_eq!(config.struct_variant_width(), 34);
798         }
799
800         #[test]
801         fn test_override_with_max() {
802             let toml = r#"
803                 use_small_heuristics = "Max"
804                 array_width = 20
805                 attr_fn_like_width = 40
806                 chain_width = 20
807                 fn_call_width = 90
808                 single_line_if_else_max_width = 40
809                 struct_lit_width = 30
810                 struct_variant_width = 34
811             "#;
812             let config = Config::from_toml(toml, Path::new("")).unwrap();
813             assert_eq!(config.array_width(), 20);
814             assert_eq!(config.attr_fn_like_width(), 40);
815             assert_eq!(config.chain_width(), 20);
816             assert_eq!(config.fn_call_width(), 90);
817             assert_eq!(config.single_line_if_else_max_width(), 40);
818             assert_eq!(config.struct_lit_width(), 30);
819             assert_eq!(config.struct_variant_width(), 34);
820         }
821
822         #[test]
823         fn test_override_with_off() {
824             let toml = r#"
825                 use_small_heuristics = "Off"
826                 array_width = 20
827                 attr_fn_like_width = 40
828                 chain_width = 20
829                 fn_call_width = 90
830                 single_line_if_else_max_width = 40
831                 struct_lit_width = 30
832                 struct_variant_width = 34
833             "#;
834             let config = Config::from_toml(toml, Path::new("")).unwrap();
835             assert_eq!(config.array_width(), 20);
836             assert_eq!(config.attr_fn_like_width(), 40);
837             assert_eq!(config.chain_width(), 20);
838             assert_eq!(config.fn_call_width(), 90);
839             assert_eq!(config.single_line_if_else_max_width(), 40);
840             assert_eq!(config.struct_lit_width(), 30);
841             assert_eq!(config.struct_variant_width(), 34);
842         }
843
844         #[test]
845         #[should_panic(expected = "`fn_call_width` cannot have a value that exceeds `max_width")]
846         fn test_panics_when_fn_call_width_config_exceeds_max_width() {
847             let toml = r#"
848                 max_width = 80
849                 fn_call_width = 90
850             "#;
851             Config::from_toml(toml, Path::new("")).unwrap();
852         }
853
854         #[test]
855         #[should_panic(
856             expected = "`attr_fn_like_width` cannot have a value that exceeds `max_width"
857         )]
858         fn test_panics_when_attr_fn_like_width_config_exceeds_max_width() {
859             let toml = r#"
860                 max_width = 80
861                 attr_fn_like_width = 90
862             "#;
863             Config::from_toml(toml, Path::new("")).unwrap();
864         }
865
866         #[test]
867         #[should_panic(expected = "`struct_lit_width` cannot have a value that exceeds `max_width")]
868         fn test_panics_when_struct_lit_config_exceeds_max_width() {
869             let toml = r#"
870                 max_width = 80
871                 struct_lit_width = 90
872             "#;
873             Config::from_toml(toml, Path::new("")).unwrap();
874         }
875
876         #[test]
877         #[should_panic(
878             expected = "`struct_variant_width` cannot have a value that exceeds `max_width"
879         )]
880         fn test_panics_when_struct_variant_width_config_exceeds_max_width() {
881             let toml = r#"
882                 max_width = 80
883                 struct_variant_width = 90
884             "#;
885             Config::from_toml(toml, Path::new("")).unwrap();
886         }
887
888         #[test]
889         #[should_panic(expected = "`array_width` cannot have a value that exceeds `max_width")]
890         fn test_panics_when_array_width_config_exceeds_max_width() {
891             let toml = r#"
892                 max_width = 80
893                 array_width = 90
894             "#;
895             Config::from_toml(toml, Path::new("")).unwrap();
896         }
897
898         #[test]
899         #[should_panic(expected = "`chain_width` cannot have a value that exceeds `max_width")]
900         fn test_panics_when_chain_width_config_exceeds_max_width() {
901             let toml = r#"
902                 max_width = 80
903                 chain_width = 90
904             "#;
905             Config::from_toml(toml, Path::new("")).unwrap();
906         }
907
908         #[test]
909         #[should_panic(
910             expected = "`single_line_if_else_max_width` cannot have a value that exceeds `max_width"
911         )]
912         fn test_panics_when_single_line_if_else_max_width_config_exceeds_max_width() {
913             let toml = r#"
914                 max_width = 80
915                 single_line_if_else_max_width = 90
916             "#;
917             Config::from_toml(toml, Path::new("")).unwrap();
918         }
919
920         #[test]
921         #[should_panic(expected = "`fn_call_width` cannot have a value that exceeds `max_width")]
922         fn test_panics_when_fn_call_width_override_exceeds_max_width() {
923             let mut config = Config::default();
924             config.override_value("fn_call_width", "101");
925         }
926
927         #[test]
928         #[should_panic(
929             expected = "`attr_fn_like_width` cannot have a value that exceeds `max_width"
930         )]
931         fn test_panics_when_attr_fn_like_width_override_exceeds_max_width() {
932             let mut config = Config::default();
933             config.override_value("attr_fn_like_width", "101");
934         }
935
936         #[test]
937         #[should_panic(expected = "`struct_lit_width` cannot have a value that exceeds `max_width")]
938         fn test_panics_when_struct_lit_override_exceeds_max_width() {
939             let mut config = Config::default();
940             config.override_value("struct_lit_width", "101");
941         }
942
943         #[test]
944         #[should_panic(
945             expected = "`struct_variant_width` cannot have a value that exceeds `max_width"
946         )]
947         fn test_panics_when_struct_variant_width_override_exceeds_max_width() {
948             let mut config = Config::default();
949             config.override_value("struct_variant_width", "101");
950         }
951
952         #[test]
953         #[should_panic(expected = "`array_width` cannot have a value that exceeds `max_width")]
954         fn test_panics_when_array_width_override_exceeds_max_width() {
955             let mut config = Config::default();
956             config.override_value("array_width", "101");
957         }
958
959         #[test]
960         #[should_panic(expected = "`chain_width` cannot have a value that exceeds `max_width")]
961         fn test_panics_when_chain_width_override_exceeds_max_width() {
962             let mut config = Config::default();
963             config.override_value("chain_width", "101");
964         }
965
966         #[test]
967         #[should_panic(
968             expected = "`single_line_if_else_max_width` cannot have a value that exceeds `max_width"
969         )]
970         fn test_panics_when_single_line_if_else_max_width_override_exceeds_max_width() {
971             let mut config = Config::default();
972             config.override_value("single_line_if_else_max_width", "101");
973         }
974     }
975 }