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