]> git.lizzy.rs Git - rust.git/blob - src/config.rs
Merge pull request #2102 from topecongiro/soft-wrapping-comments
[rust.git] / src / config.rs
1 // Copyright 2015 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 extern crate toml;
12
13 use std::{env, fs};
14 use std::cell::Cell;
15 use std::fs::File;
16 use std::io::{Error, ErrorKind, Read};
17 use std::path::{Path, PathBuf};
18
19 use file_lines::FileLines;
20 use lists::{ListTactic, SeparatorPlace, SeparatorTactic};
21 use Summary;
22
23
24 macro_rules! is_nightly_channel {
25     () => {
26     env::var("CFG_RELEASE_CHANNEL")
27         .map(|c| c == "nightly")
28         .unwrap_or(false)
29     }
30 }
31
32 macro_rules! configuration_option_enum{
33     ($e:ident: $( $x:ident ),+ $(,)*) => {
34         #[derive(Copy, Clone, Eq, PartialEq, Debug)]
35         pub enum $e {
36             $( $x ),+
37         }
38
39         impl_enum_serialize_and_deserialize!($e, $( $x ),+);
40     }
41 }
42
43 configuration_option_enum! { Style:
44     Rfc, // Follow the style RFCs style.
45     Legacy, // Follow the traditional Rustfmt style.
46 }
47
48 configuration_option_enum! { NewlineStyle:
49     Windows, // \r\n
50     Unix, // \n
51     Native, // \r\n in Windows, \n on other platforms
52 }
53
54 configuration_option_enum! { BraceStyle:
55     AlwaysNextLine,
56     PreferSameLine,
57     // Prefer same line except where there is a where clause, in which case force
58     // the brace to the next line.
59     SameLineWhere,
60 }
61
62 configuration_option_enum! { ControlBraceStyle:
63     // K&R style, Rust community default
64     AlwaysSameLine,
65     // Stroustrup style
66     ClosingNextLine,
67     // Allman style
68     AlwaysNextLine,
69 }
70
71 // How to indent a function's return type.
72 configuration_option_enum! { ReturnIndent:
73     // Aligned with the arguments
74     WithArgs,
75     // Aligned with the where clause
76     WithWhereClause,
77 }
78
79 configuration_option_enum! { IndentStyle:
80     // First line on the same line as the opening brace, all lines aligned with
81     // the first line.
82     Visual,
83     // First line is on a new line and all lines align with block indent.
84     Block,
85 }
86
87 configuration_option_enum! { Density:
88     // Fit as much on one line as possible.
89     Compressed,
90     // Use more lines.
91     Tall,
92     // Try to compress if the body is empty.
93     CompressedIfEmpty,
94     // Place every item on a separate line.
95     Vertical,
96 }
97
98 configuration_option_enum! { TypeDensity:
99     // No spaces around "=" and "+"
100     Compressed,
101     // Spaces around " = " and " + "
102     Wide,
103 }
104
105
106 impl Density {
107     pub fn to_list_tactic(self) -> ListTactic {
108         match self {
109             Density::Compressed => ListTactic::Mixed,
110             Density::Tall | Density::CompressedIfEmpty => ListTactic::HorizontalVertical,
111             Density::Vertical => ListTactic::Vertical,
112         }
113     }
114 }
115
116 configuration_option_enum! { LicensePolicy:
117     // Do not place license text at top of files
118     NoLicense,
119     // Use the text in "license" field as the license
120     TextLicense,
121     // Use a text file as the license text
122     FileLicense,
123 }
124
125 configuration_option_enum! { MultilineStyle:
126     // Use horizontal layout if it fits in one line, fall back to vertical
127     PreferSingle,
128     // Use vertical layout
129     ForceMulti,
130 }
131
132 impl MultilineStyle {
133     pub fn to_list_tactic(self) -> ListTactic {
134         match self {
135             MultilineStyle::PreferSingle => ListTactic::HorizontalVertical,
136             MultilineStyle::ForceMulti => ListTactic::Vertical,
137         }
138     }
139 }
140
141 configuration_option_enum! { ReportTactic:
142     Always,
143     Unnumbered,
144     Never,
145 }
146
147 configuration_option_enum! { WriteMode:
148     // Backs the original file up and overwrites the original.
149     Replace,
150     // Overwrites original file without backup.
151     Overwrite,
152     // Writes the output to stdout.
153     Display,
154     // Writes the diff to stdout.
155     Diff,
156     // Displays how much of the input file was processed
157     Coverage,
158     // Unfancy stdout
159     Plain,
160     // Outputs a checkstyle XML file.
161     Checkstyle,
162 }
163
164 /// Trait for types that can be used in `Config`.
165 pub trait ConfigType: Sized {
166     /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a
167     /// pipe-separated list of variants; for other types it returns "<type>".
168     fn doc_hint() -> String;
169 }
170
171 impl ConfigType for bool {
172     fn doc_hint() -> String {
173         String::from("<boolean>")
174     }
175 }
176
177 impl ConfigType for usize {
178     fn doc_hint() -> String {
179         String::from("<unsigned integer>")
180     }
181 }
182
183 impl ConfigType for isize {
184     fn doc_hint() -> String {
185         String::from("<signed integer>")
186     }
187 }
188
189 impl ConfigType for String {
190     fn doc_hint() -> String {
191         String::from("<string>")
192     }
193 }
194
195 impl ConfigType for FileLines {
196     fn doc_hint() -> String {
197         String::from("<json>")
198     }
199 }
200
201 pub struct ConfigHelpItem {
202     option_name: &'static str,
203     doc_string: &'static str,
204     variant_names: String,
205     default: &'static str,
206 }
207
208 impl ConfigHelpItem {
209     pub fn option_name(&self) -> &'static str {
210         self.option_name
211     }
212
213     pub fn doc_string(&self) -> &'static str {
214         self.doc_string
215     }
216
217     pub fn variant_names(&self) -> &String {
218         &self.variant_names
219     }
220
221     pub fn default(&self) -> &'static str {
222         self.default
223     }
224 }
225
226 macro_rules! create_config {
227     ($($i:ident: $ty:ty, $def:expr, $stb:expr, $( $dstring:expr ),+ );+ $(;)*) => (
228         #[derive(Clone)]
229         pub struct Config {
230             // For each config item, we store a bool indicating whether it has
231             // been accessed and the value, and a bool whether the option was
232             // manually initialised, or taken from the default,
233             $($i: (Cell<bool>, bool, $ty, bool)),+
234         }
235
236         // Just like the Config struct but with each property wrapped
237         // as Option<T>. This is used to parse a rustfmt.toml that doesn't
238         // specify all properties of `Config`.
239         // We first parse into `PartialConfig`, then create a default `Config`
240         // and overwrite the properties with corresponding values from `PartialConfig`.
241         #[derive(Deserialize, Serialize, Clone)]
242         pub struct PartialConfig {
243             $(pub $i: Option<$ty>),+
244         }
245
246         impl PartialConfig {
247             pub fn to_toml(&self) -> Result<String, String> {
248                 // file_lines can't be specified in TOML
249                 let mut cloned = self.clone();
250                 cloned.file_lines = None;
251
252                 toml::to_string(&cloned)
253                     .map_err(|e| format!("Could not output config: {}", e.to_string()))
254             }
255         }
256
257         // Macro hygiene won't allow us to make `set_$i()` methods on Config
258         // for each item, so this struct is used to give the API to set values:
259         // `config.get().option(false)`. It's pretty ugly. Consider replacing
260         // with `config.set_option(false)` if we ever get a stable/usable
261         // `concat_idents!()`.
262         pub struct ConfigSetter<'a>(&'a mut Config);
263
264         impl<'a> ConfigSetter<'a> {
265             $(
266             pub fn $i(&mut self, value: $ty) {
267                 (self.0).$i.2 = value;
268             }
269             )+
270         }
271
272         // Query each option, returns true if the user set the option, false if
273         // a default was used.
274         pub struct ConfigWasSet<'a>(&'a Config);
275
276         impl<'a> ConfigWasSet<'a> {
277             $(
278             pub fn $i(&self) -> bool {
279                 (self.0).$i.1
280             }
281             )+
282         }
283
284         impl Config {
285             pub fn version_meets_requirement(&self, error_summary: &mut Summary) -> bool {
286                 if self.was_set().required_version() {
287                     let version = env!("CARGO_PKG_VERSION");
288                     let required_version = self.required_version();
289                     if version != required_version {
290                         println!(
291                             "Error: rustfmt version ({}) doesn't match the required version ({})",
292                             version,
293                             required_version,
294                         );
295                         error_summary.add_formatting_error();
296                         return false;
297                     }
298                 }
299
300                 true
301             }
302
303             $(
304             pub fn $i(&self) -> $ty {
305                 self.$i.0.set(true);
306                 self.$i.2.clone()
307             }
308             )+
309
310             pub fn set<'a>(&'a mut self) -> ConfigSetter<'a> {
311                 ConfigSetter(self)
312             }
313
314             pub fn was_set<'a>(&'a self) -> ConfigWasSet<'a> {
315                 ConfigWasSet(self)
316             }
317
318             fn fill_from_parsed_config(mut self, parsed: PartialConfig) -> Config {
319             $(
320                 if let Some(val) = parsed.$i {
321                     if !self.$i.3 {
322                         self.$i.1 = true;
323                         self.$i.2 = val;
324                     } else {
325                         if is_nightly_channel!() {
326                             self.$i.1 = true;
327                             self.$i.2 = val;
328                         } else {
329                             println!("Warning: can't set some features as unstable \
330                                     features are only available in nightly channel.");
331                         }
332                     }
333                 }
334             )+
335                 self
336             }
337
338             pub fn from_toml(toml: &str) -> Result<Config, String> {
339                 let parsed: toml::Value =
340                     toml.parse().map_err(|e| format!("Could not parse TOML: {}", e))?;
341                 let mut err: String = String::new();
342                 {
343                     let table = parsed
344                         .as_table()
345                         .ok_or(String::from("Parsed config was not table"))?;
346                     for key in table.keys() {
347                         match &**key {
348                             $(
349                                 stringify!($i) => (),
350                             )+
351                                 _ => {
352                                     let msg =
353                                         &format!("Warning: Unknown configuration option `{}`\n",
354                                                  key);
355                                     err.push_str(msg)
356                                 }
357                         }
358                     }
359                 }
360                 match parsed.try_into() {
361                     Ok(parsed_config) =>
362                         Ok(Config::default().fill_from_parsed_config(parsed_config)),
363                     Err(e) => {
364                         err.push_str("Error: Decoding config file failed:\n");
365                         err.push_str(format!("{}\n", e).as_str());
366                         err.push_str("Please check your config file.\n");
367                         Err(err)
368                     }
369                 }
370             }
371
372             pub fn used_options(&self) -> PartialConfig {
373                 PartialConfig {
374                     $(
375                         $i: if self.$i.0.get() {
376                                 Some(self.$i.2.clone())
377                             } else {
378                                 None
379                             },
380                     )+
381                 }
382             }
383
384             pub fn all_options(&self) -> PartialConfig {
385                 PartialConfig {
386                     $(
387                         $i: Some(self.$i.2.clone()),
388                     )+
389                 }
390             }
391
392             pub fn override_value(&mut self, key: &str, val: &str)
393             {
394                 match key {
395                     $(
396                         stringify!($i) => {
397                             self.$i.2 = val.parse::<$ty>()
398                                 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
399                                                  stringify!($i),
400                                                  val,
401                                                  stringify!($ty)));
402                         }
403                     )+
404                     _ => panic!("Unknown config key in override: {}", key)
405                 }
406             }
407
408             /// Construct a `Config` from the toml file specified at `file_path`.
409             ///
410             /// This method only looks at the provided path, for a method that
411             /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
412             ///
413             /// Return a `Config` if the config could be read and parsed from
414             /// the file, Error otherwise.
415             pub fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
416                 let mut file = File::open(&file_path)?;
417                 let mut toml = String::new();
418                 file.read_to_string(&mut toml)?;
419                 Config::from_toml(&toml).map_err(|err| Error::new(ErrorKind::InvalidData, err))
420             }
421
422             /// Resolve the config for input in `dir`.
423             ///
424             /// Searches for `rustfmt.toml` beginning with `dir`, and
425             /// recursively checking parents of `dir` if no config file is found.
426             /// If no config file exists in `dir` or in any parent, a
427             /// default `Config` will be returned (and the returned path will be empty).
428             ///
429             /// Returns the `Config` to use, and the path of the project file if there was
430             /// one.
431             pub fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
432
433                 /// Try to find a project file in the given directory and its parents.
434                 /// Returns the path of a the nearest project file if one exists,
435                 /// or `None` if no project file was found.
436                 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
437                     let mut current = if dir.is_relative() {
438                         env::current_dir()?.join(dir)
439                     } else {
440                         dir.to_path_buf()
441                     };
442
443                     current = fs::canonicalize(current)?;
444
445                     loop {
446                         match get_toml_path(&current) {
447                             Ok(Some(path)) => return Ok(Some(path)),
448                             Err(e) => return Err(e),
449                             _ => ()
450                         }
451
452                         // If the current directory has no parent, we're done searching.
453                         if !current.pop() {
454                             return Ok(None);
455                         }
456                     }
457                 }
458
459                 match resolve_project_file(dir)? {
460                     None => Ok((Config::default(), None)),
461                     Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
462                 }
463             }
464
465
466             pub fn print_docs() {
467                 use std::cmp;
468                 let max = 0;
469                 $( let max = cmp::max(max, stringify!($i).len()+1); )+
470                 let mut space_str = String::with_capacity(max);
471                 for _ in 0..max {
472                     space_str.push(' ');
473                 }
474                 println!("Configuration Options:");
475                 $(
476                     let name_raw = stringify!($i);
477                     let mut name_out = String::with_capacity(max);
478                     for _ in name_raw.len()..max-1 {
479                         name_out.push(' ')
480                     }
481                     name_out.push_str(name_raw);
482                     name_out.push(' ');
483                     println!("{}{} Default: {:?}",
484                              name_out,
485                              <$ty>::doc_hint(),
486                              $def);
487                     $(
488                         println!("{}{}", space_str, $dstring);
489                     )+
490                     println!("");
491                 )+
492             }
493         }
494
495         // Template for the default configuration
496         impl Default for Config {
497             fn default() -> Config {
498                 Config {
499                     $(
500                         $i: (Cell::new(false), false, $def, $stb),
501                     )+
502                 }
503             }
504         }
505     )
506 }
507
508 /// Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
509 ///
510 /// Return the path if a config file exists, empty if no file exists, and Error for IO errors
511 pub fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
512     const CONFIG_FILE_NAMES: [&'static str; 2] = [".rustfmt.toml", "rustfmt.toml"];
513     for config_file_name in &CONFIG_FILE_NAMES {
514         let config_file = dir.join(config_file_name);
515         match fs::metadata(&config_file) {
516             // Only return if it's a file to handle the unlikely situation of a directory named
517             // `rustfmt.toml`.
518             Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
519             // Return the error if it's something other than `NotFound`; otherwise we didn't
520             // find the project file yet, and continue searching.
521             Err(e) => if e.kind() != ErrorKind::NotFound {
522                 return Err(e);
523             },
524             _ => {}
525         }
526     }
527     Ok(None)
528 }
529
530
531
532 create_config! {
533     unstable_features: bool, false, true,
534             "Enables unstable features. Only available on nightly channel";
535     verbose: bool, false, false, "Use verbose output";
536     disable_all_formatting: bool, false, false, "Don't reformat anything";
537     skip_children: bool, false, false, "Don't reformat out of line modules";
538     file_lines: FileLines, FileLines::all(), false,
539         "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
540          via the --file-lines option";
541     max_width: usize, 100, false, "Maximum width of each line";
542     error_on_line_overflow: bool, true, false, "Error if unable to get all lines within max_width";
543     error_on_line_overflow_comments: bool, true, false,
544         "Error if unable to get comments within max_width";
545     tab_spaces: usize, 4, false, "Number of spaces per tab";
546     fn_call_width: usize, 60, false,
547         "Maximum width of the args of a function call before falling back to vertical formatting";
548     struct_lit_width: usize, 18, false,
549         "Maximum width in the body of a struct lit before falling back to vertical formatting";
550     struct_variant_width: usize, 35, false,
551         "Maximum width in the body of a struct variant before falling back to vertical formatting";
552     force_explicit_abi: bool, true, false, "Always print the abi for extern items";
553     newline_style: NewlineStyle, NewlineStyle::Unix, false, "Unix or Windows line endings";
554     fn_brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for functions";
555     item_brace_style: BraceStyle, BraceStyle::SameLineWhere, false,
556         "Brace style for structs and enums";
557     control_style: Style, Style::Rfc, false, "Indent style for control flow statements";
558     control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false,
559         "Brace style for control flow constructs";
560     impl_empty_single_line: bool, true, false, "Put empty-body implementations on a single line";
561     trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
562         "How to handle trailing commas for lists";
563     trailing_semicolon: bool, true, false,
564         "Add trailing semicolon after break, continue and return";
565     fn_empty_single_line: bool, true, false, "Put empty-body functions on a single line";
566     fn_single_line: bool, false, false, "Put single-expression functions on a single line";
567     fn_return_indent: ReturnIndent, ReturnIndent::WithArgs, false,
568         "Location of return type in function declaration";
569     fn_args_paren_newline: bool, false, false, "If function argument parenthesis goes on a newline";
570     fn_args_density: Density, Density::Tall, false, "Argument density in functions";
571     fn_args_layout: IndentStyle, IndentStyle::Block, false,
572         "Layout of function arguments and tuple structs";
573     array_layout: IndentStyle, IndentStyle::Block, false, "Indent on arrays";
574     array_width: usize, 60, false,
575         "Maximum width of an array literal before falling back to vertical formatting";
576     array_horizontal_layout_threshold: usize, 0, false,
577         "How many elements array must have before rustfmt uses horizontal layout.";
578     type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
579         "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
580     where_style: Style, Style::Rfc, false, "Overall strategy for where clauses";
581     // TODO:
582     // 1. Should we at least try to put the where clause on the same line as the rest of the
583     // function decl?
584     // 2. Currently options `Tall` and `Vertical` produce the same output.
585     where_density: Density, Density::Vertical, false, "Density of a where clause";
586     where_layout: ListTactic, ListTactic::Vertical, false, "Element layout inside a where clause";
587     where_pred_indent: IndentStyle, IndentStyle::Visual, false,
588         "Indentation style of a where predicate";
589     generics_indent: IndentStyle, IndentStyle::Block, false, "Indentation of generics";
590     struct_lit_style: IndentStyle, IndentStyle::Block, false, "Style of struct definition";
591     struct_lit_multiline_style: MultilineStyle, MultilineStyle::PreferSingle, false,
592         "Multiline style on literal structs";
593     fn_call_style: IndentStyle, IndentStyle::Block, false, "Indentation for function calls, etc.";
594     report_todo: ReportTactic, ReportTactic::Never, false,
595         "Report all, none or unnumbered occurrences of TODO in source file comments";
596     report_fixme: ReportTactic, ReportTactic::Never, false,
597         "Report all, none or unnumbered occurrences of FIXME in source file comments";
598     chain_indent: IndentStyle, IndentStyle::Block, false, "Indentation of chain";
599     chain_one_line_max: usize, 60, false, "Maximum length of a chain to fit on a single line";
600     chain_split_single_child: bool, false, false, "Split a chain with a single child if its length \
601                                             exceeds `chain_one_line_max`";
602     imports_indent: IndentStyle, IndentStyle::Visual, false, "Indent of imports";
603     imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
604     reorder_extern_crates: bool, true, false, "Reorder extern crate statements alphabetically";
605     reorder_extern_crates_in_group: bool, true, false, "Reorder extern crate statements in group";
606     reorder_imports: bool, false, false, "Reorder import statements alphabetically";
607     reorder_imports_in_group: bool, false, false, "Reorder import statements in group";
608     reorder_imported_names: bool, true, false,
609         "Reorder lists of names in import statements alphabetically";
610     single_line_if_else_max_width: usize, 50, false, "Maximum line length for single line if-else \
611                                                 expressions. A value of zero means always break \
612                                                 if-else expressions.";
613     format_strings: bool, false, false, "Format string literals where necessary";
614     force_format_strings: bool, false, false, "Always format string literals";
615     take_source_hints: bool, false, false,
616         "Retain some formatting characteristics from the source code";
617     hard_tabs: bool, false, false, "Use tab characters for indentation, spaces for alignment";
618     wrap_comments: bool, false, false, "Break comments to fit on the line";
619     comment_width: usize, 80, false,
620         "Maximum length of comments. No effect unless wrap_comments = true";
621     normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible";
622     wrap_match_arms: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \
623                                   the same line with the pattern of arms";
624     match_block_trailing_comma: bool, false, false,
625         "Put a trailing comma after a block based match arm (non-block arms are not affected)";
626     match_arm_forces_newline: bool, false, false,
627         "Force match arm bodies to be in a new lines";
628     indent_match_arms: bool, true, false, "Indent match arms instead of keeping them at the same \
629                                     indentation level as the match keyword";
630     match_pattern_separator_break_point: SeparatorPlace, SeparatorPlace::Back, false,
631         "Put a match sub-patterns' separator in front or back.";
632     closure_block_indent_threshold: isize, 7, false,
633         "How many lines a closure must have before it is block indented. \
634         -1 means never use block indent.";
635     space_before_type_annotation: bool, false, false,
636         "Leave a space before the colon in a type annotation";
637     space_after_type_annotation_colon: bool, true, false,
638         "Leave a space after the colon in a type annotation";
639     space_before_struct_lit_field_colon: bool, false, false,
640         "Leave a space before the colon in a struct literal field";
641     space_after_struct_lit_field_colon: bool, true, false,
642         "Leave a space after the colon in a struct literal field";
643     space_before_bound: bool, false, false,
644         "Leave a space before the colon in a trait or lifetime bound";
645     space_after_bound_colon: bool, true, false,
646         "Leave a space after the colon in a trait or lifetime bound";
647     spaces_around_ranges: bool, false, false, "Put spaces around the  .. and ... range operators";
648     spaces_within_angle_brackets: bool, false, false,
649         "Put spaces within non-empty generic arguments";
650     spaces_within_square_brackets: bool, false, false,
651         "Put spaces within non-empty square brackets";
652     spaces_within_parens: bool, false, false, "Put spaces within non-empty parentheses";
653     use_try_shorthand: bool, false, false, "Replace uses of the try! macro by the ? shorthand";
654     write_mode: WriteMode, WriteMode::Overwrite, false,
655         "What Write Mode to use when none is supplied: \
656          Replace, Overwrite, Display, Plain, Diff, Coverage";
657     condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
658                                               in tuple patterns";
659     combine_control_expr: bool, true, false, "Combine control expressions with function calls.";
660     struct_field_align_threshold: usize, 0, false, "Align struct fields if their diffs fits within \
661                                              threshold.";
662     remove_blank_lines_at_start_or_end_of_block: bool, true, false,
663         "Remove blank lines at start or end of a block";
664     attributes_on_same_line_as_field: bool, true, false,
665         "Try to put attributes on the same line as fields.";
666     attributes_on_same_line_as_variant: bool, true, false,
667         "Try to put attributes on the same line as variants in enum declarations.";
668     multiline_closure_forces_block: bool, false, false,
669         "Force multiline closure bodies to be wrapped in a block";
670     multiline_match_arm_forces_block: bool, false, false,
671         "Force multiline match arm bodies to be wrapped in a block";
672     merge_derives: bool, true, false, "Merge multiple `#[derive(...)]` into a single one";
673     binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
674         "Where to put a binary operator when a binary expression goes multiline.";
675     required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
676         "Require a specific version of rustfmt."
677 }
678
679 #[cfg(test)]
680 mod test {
681     use super::Config;
682
683     #[test]
684     fn test_config_set() {
685         let mut config = Config::default();
686         config.set().verbose(false);
687         assert_eq!(config.verbose(), false);
688         config.set().verbose(true);
689         assert_eq!(config.verbose(), true);
690     }
691
692     #[test]
693     fn test_config_used_to_toml() {
694         let config = Config::default();
695
696         let verbose = config.verbose();
697         let skip_children = config.skip_children();
698
699         let used_options = config.used_options();
700         let toml = used_options.to_toml().unwrap();
701         assert_eq!(
702             toml,
703             format!("verbose = {}\nskip_children = {}\n", verbose, skip_children)
704         );
705     }
706
707     #[test]
708     fn test_was_set() {
709         let config = Config::from_toml("hard_tabs = true").unwrap();
710
711         assert_eq!(config.was_set().hard_tabs(), true);
712         assert_eq!(config.was_set().verbose(), false);
713     }
714
715     #[test]
716     fn test_as_not_nightly_channel() {
717         let mut config = Config::default();
718         assert_eq!(config.was_set().unstable_features(), false);
719         config.set().unstable_features(true);
720         assert_eq!(config.was_set().unstable_features(), false);
721     }
722
723     #[test]
724     fn test_as_nightly_channel() {
725         let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
726         ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
727         let mut config = Config::default();
728         config.set().unstable_features(true);
729         assert_eq!(config.was_set().unstable_features(), false);
730         config.set().unstable_features(true);
731         assert_eq!(config.unstable_features(), true);
732         ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
733     }
734
735     #[test]
736     fn test_unstable_from_toml() {
737         let mut config = Config::from_toml("unstable_features = true").unwrap();
738         assert_eq!(config.was_set().unstable_features(), false);
739         let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
740         ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
741         config = Config::from_toml("unstable_features = true").unwrap();
742         assert_eq!(config.was_set().unstable_features(), true);
743         assert_eq!(config.unstable_features(), true);
744         ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
745     }
746
747 }