]> git.lizzy.rs Git - rust.git/blob - src/config/config_type.rs
Merge pull request #3545 from euclio/serde-derive
[rust.git] / src / config / config_type.rs
1 use crate::config::file_lines::FileLines;
2 use crate::config::options::{IgnoreList, WidthHeuristics};
3
4 /// Trait for types that can be used in `Config`.
5 pub trait ConfigType: Sized {
6     /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a
7     /// pipe-separated list of variants; for other types it returns "<type>".
8     fn doc_hint() -> String;
9 }
10
11 impl ConfigType for bool {
12     fn doc_hint() -> String {
13         String::from("<boolean>")
14     }
15 }
16
17 impl ConfigType for usize {
18     fn doc_hint() -> String {
19         String::from("<unsigned integer>")
20     }
21 }
22
23 impl ConfigType for isize {
24     fn doc_hint() -> String {
25         String::from("<signed integer>")
26     }
27 }
28
29 impl ConfigType for String {
30     fn doc_hint() -> String {
31         String::from("<string>")
32     }
33 }
34
35 impl ConfigType for FileLines {
36     fn doc_hint() -> String {
37         String::from("<json>")
38     }
39 }
40
41 impl ConfigType for WidthHeuristics {
42     fn doc_hint() -> String {
43         String::new()
44     }
45 }
46
47 impl ConfigType for IgnoreList {
48     fn doc_hint() -> String {
49         String::from("[<string>,..]")
50     }
51 }
52
53 /// Checks if we're in a nightly build.
54 ///
55 /// The environment variable `CFG_RELEASE_CHANNEL` is set during the rustc bootstrap
56 /// to "stable", "beta", or "nightly" depending on what toolchain is being built.
57 /// If we are being built as part of the stable or beta toolchains, we want
58 /// to disable unstable configuration options.
59 ///
60 /// If we're being built by cargo (e.g., `cargo +nightly install rustfmt-nightly`),
61 /// `CFG_RELEASE_CHANNEL` is not set. As we only support being built against the
62 /// nightly compiler when installed from crates.io, default to nightly mode.
63 macro_rules! is_nightly_channel {
64     () => {
65         option_env!("CFG_RELEASE_CHANNEL").map_or(true, |c| c == "nightly" || c == "dev")
66     };
67 }
68
69 macro_rules! create_config {
70     ($($i:ident: $ty:ty, $def:expr, $stb:expr, $( $dstring:expr ),+ );+ $(;)*) => (
71         #[cfg(test)]
72         use std::collections::HashSet;
73         use std::io::Write;
74
75         use serde::{Deserialize, Serialize};
76
77         #[derive(Clone)]
78         pub struct Config {
79             // if a license_template_path has been specified, successfully read, parsed and compiled
80             // into a regex, it will be stored here
81             pub license_template: Option<Regex>,
82             // For each config item, we store a bool indicating whether it has
83             // been accessed and the value, and a bool whether the option was
84             // manually initialised, or taken from the default,
85             $($i: (Cell<bool>, bool, $ty, bool)),+
86         }
87
88         // Just like the Config struct but with each property wrapped
89         // as Option<T>. This is used to parse a rustfmt.toml that doesn't
90         // specify all properties of `Config`.
91         // We first parse into `PartialConfig`, then create a default `Config`
92         // and overwrite the properties with corresponding values from `PartialConfig`.
93         #[derive(Deserialize, Serialize, Clone)]
94         pub struct PartialConfig {
95             $(pub $i: Option<$ty>),+
96         }
97
98         // Macro hygiene won't allow us to make `set_$i()` methods on Config
99         // for each item, so this struct is used to give the API to set values:
100         // `config.set().option(false)`. It's pretty ugly. Consider replacing
101         // with `config.set_option(false)` if we ever get a stable/usable
102         // `concat_idents!()`.
103         pub struct ConfigSetter<'a>(&'a mut Config);
104
105         impl<'a> ConfigSetter<'a> {
106             $(
107             pub fn $i(&mut self, value: $ty) {
108                 (self.0).$i.2 = value;
109                 match stringify!($i) {
110                     "max_width" | "use_small_heuristics" => self.0.set_heuristics(),
111                     "license_template_path" => self.0.set_license_template(),
112                     &_ => (),
113                 }
114             }
115             )+
116         }
117
118         // Query each option, returns true if the user set the option, false if
119         // a default was used.
120         pub struct ConfigWasSet<'a>(&'a Config);
121
122         impl<'a> ConfigWasSet<'a> {
123             $(
124             pub fn $i(&self) -> bool {
125                 (self.0).$i.1
126             }
127             )+
128         }
129
130         impl Config {
131             $(
132             pub fn $i(&self) -> $ty {
133                 self.$i.0.set(true);
134                 self.$i.2.clone()
135             }
136             )+
137
138             pub fn set(&mut self) -> ConfigSetter<'_> {
139                 ConfigSetter(self)
140             }
141
142             pub fn was_set(&self) -> ConfigWasSet<'_> {
143                 ConfigWasSet(self)
144             }
145
146             fn fill_from_parsed_config(mut self, parsed: PartialConfig, dir: &Path) -> Config {
147             $(
148                 if let Some(val) = parsed.$i {
149                     if self.$i.3 {
150                         self.$i.1 = true;
151                         self.$i.2 = val;
152                     } else {
153                         if is_nightly_channel!() {
154                             self.$i.1 = true;
155                             self.$i.2 = val;
156                         } else {
157                             eprintln!("Warning: can't set `{} = {:?}`, unstable features are only \
158                                        available in nightly channel.", stringify!($i), val);
159                         }
160                     }
161                 }
162             )+
163                 self.set_heuristics();
164                 self.set_license_template();
165                 self.set_ignore(dir);
166                 self
167             }
168
169             /// Returns a hash set initialized with every user-facing config option name.
170             #[cfg(test)]
171             pub(crate) fn hash_set() -> HashSet<String> {
172                 let mut hash_set = HashSet::new();
173                 $(
174                     hash_set.insert(stringify!($i).to_owned());
175                 )+
176                 hash_set
177             }
178
179             pub(crate) fn is_valid_name(name: &str) -> bool {
180                 match name {
181                     $(
182                         stringify!($i) => true,
183                     )+
184                         _ => false,
185                 }
186             }
187
188             pub fn used_options(&self) -> PartialConfig {
189                 PartialConfig {
190                     $(
191                         $i: if self.$i.0.get() {
192                                 Some(self.$i.2.clone())
193                             } else {
194                                 None
195                             },
196                     )+
197                 }
198             }
199
200             pub fn all_options(&self) -> PartialConfig {
201                 PartialConfig {
202                     $(
203                         $i: Some(self.$i.2.clone()),
204                     )+
205                 }
206             }
207
208             pub fn override_value(&mut self, key: &str, val: &str)
209             {
210                 match key {
211                     $(
212                         stringify!($i) => {
213                             self.$i.1 = true;
214                             self.$i.2 = val.parse::<$ty>()
215                                 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
216                                                  stringify!($i),
217                                                  val,
218                                                  stringify!($ty)));
219                         }
220                     )+
221                     _ => panic!("Unknown config key in override: {}", key)
222                 }
223
224                 match key {
225                     "max_width" | "use_small_heuristics" => self.set_heuristics(),
226                     "license_template_path" => self.set_license_template(),
227                     &_ => (),
228                 }
229             }
230
231             pub fn is_hidden_option(name: &str) -> bool {
232                 const HIDE_OPTIONS: [&str; 4] =
233                     ["verbose", "verbose_diff", "file_lines", "width_heuristics"];
234                 HIDE_OPTIONS.contains(&name)
235             }
236
237             pub fn print_docs(out: &mut dyn Write, include_unstable: bool) {
238                 use std::cmp;
239                 let max = 0;
240                 $( let max = cmp::max(max, stringify!($i).len()+1); )+
241                 let space_str = " ".repeat(max);
242                 writeln!(out, "Configuration Options:").unwrap();
243                 $(
244                     if $stb || include_unstable {
245                         let name_raw = stringify!($i);
246
247                         if !Config::is_hidden_option(name_raw) {
248                             let mut name_out = String::with_capacity(max);
249                             for _ in name_raw.len()..max-1 {
250                                 name_out.push(' ')
251                             }
252                             name_out.push_str(name_raw);
253                             name_out.push(' ');
254                             writeln!(out,
255                                     "{}{} Default: {:?}{}",
256                                     name_out,
257                                     <$ty>::doc_hint(),
258                                     $def,
259                                     if !$stb { " (unstable)" } else { "" }).unwrap();
260                             $(
261                                 writeln!(out, "{}{}", space_str, $dstring).unwrap();
262                             )+
263                             writeln!(out).unwrap();
264                         }
265                     }
266                 )+
267             }
268
269             fn set_heuristics(&mut self) {
270                 if self.use_small_heuristics.2 == Heuristics::Default {
271                     let max_width = self.max_width.2;
272                     self.set().width_heuristics(WidthHeuristics::scaled(max_width));
273                 } else if self.use_small_heuristics.2 == Heuristics::Max {
274                     let max_width = self.max_width.2;
275                     self.set().width_heuristics(WidthHeuristics::set(max_width));
276                 } else {
277                     self.set().width_heuristics(WidthHeuristics::null());
278                 }
279             }
280
281             fn set_license_template(&mut self) {
282                 if self.was_set().license_template_path() {
283                     let lt_path = self.license_template_path();
284                     match license::load_and_compile_template(&lt_path) {
285                         Ok(re) => self.license_template = Some(re),
286                         Err(msg) => eprintln!("Warning for license template file {:?}: {}",
287                                               lt_path, msg),
288                     }
289                 }
290             }
291
292             fn set_ignore(&mut self, dir: &Path) {
293                 self.ignore.2.add_prefix(dir);
294             }
295
296             /// Returns `true` if the config key was explicitly set and is the default value.
297             pub fn is_default(&self, key: &str) -> bool {
298                 $(
299                     if let stringify!($i) = key {
300                         return self.$i.1 && self.$i.2 == $def;
301                     }
302                  )+
303                 false
304             }
305         }
306
307         // Template for the default configuration
308         impl Default for Config {
309             fn default() -> Config {
310                 Config {
311                     license_template: None,
312                     $(
313                         $i: (Cell::new(false), false, $def, $stb),
314                     )+
315                 }
316             }
317         }
318     )
319 }