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