]> git.lizzy.rs Git - rust.git/blob - src/config/config_type.rs
Merge pull request #3522 from topecongiro/issue-3521
[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         #[derive(Clone)]
76         pub struct Config {
77             // if a license_template_path has been specified, successfully read, parsed and compiled
78             // into a regex, it will be stored here
79             pub license_template: Option<Regex>,
80             // For each config item, we store a bool indicating whether it has
81             // been accessed and the value, and a bool whether the option was
82             // manually initialised, or taken from the default,
83             $($i: (Cell<bool>, bool, $ty, bool)),+
84         }
85
86         // Just like the Config struct but with each property wrapped
87         // as Option<T>. This is used to parse a rustfmt.toml that doesn't
88         // specify all properties of `Config`.
89         // We first parse into `PartialConfig`, then create a default `Config`
90         // and overwrite the properties with corresponding values from `PartialConfig`.
91         #[derive(Deserialize, Serialize, Clone)]
92         pub struct PartialConfig {
93             $(pub $i: Option<$ty>),+
94         }
95
96         // Macro hygiene won't allow us to make `set_$i()` methods on Config
97         // for each item, so this struct is used to give the API to set values:
98         // `config.set().option(false)`. It's pretty ugly. Consider replacing
99         // with `config.set_option(false)` if we ever get a stable/usable
100         // `concat_idents!()`.
101         pub struct ConfigSetter<'a>(&'a mut Config);
102
103         impl<'a> ConfigSetter<'a> {
104             $(
105             pub fn $i(&mut self, value: $ty) {
106                 (self.0).$i.2 = value;
107                 match stringify!($i) {
108                     "max_width" | "use_small_heuristics" => self.0.set_heuristics(),
109                     "license_template_path" => self.0.set_license_template(),
110                     &_ => (),
111                 }
112             }
113             )+
114         }
115
116         // Query each option, returns true if the user set the option, false if
117         // a default was used.
118         pub struct ConfigWasSet<'a>(&'a Config);
119
120         impl<'a> ConfigWasSet<'a> {
121             $(
122             pub fn $i(&self) -> bool {
123                 (self.0).$i.1
124             }
125             )+
126         }
127
128         impl Config {
129             $(
130             pub fn $i(&self) -> $ty {
131                 self.$i.0.set(true);
132                 self.$i.2.clone()
133             }
134             )+
135
136             pub fn set(&mut self) -> ConfigSetter<'_> {
137                 ConfigSetter(self)
138             }
139
140             pub fn was_set(&self) -> ConfigWasSet<'_> {
141                 ConfigWasSet(self)
142             }
143
144             fn fill_from_parsed_config(mut self, parsed: PartialConfig, dir: &Path) -> Config {
145             $(
146                 if let Some(val) = parsed.$i {
147                     if self.$i.3 {
148                         self.$i.1 = true;
149                         self.$i.2 = val;
150                     } else {
151                         if is_nightly_channel!() {
152                             self.$i.1 = true;
153                             self.$i.2 = val;
154                         } else {
155                             eprintln!("Warning: can't set `{} = {:?}`, unstable features are only \
156                                        available in nightly channel.", stringify!($i), val);
157                         }
158                     }
159                 }
160             )+
161                 self.set_heuristics();
162                 self.set_license_template();
163                 self.set_ignore(dir);
164                 self
165             }
166
167             /// Returns a hash set initialized with every user-facing config option name.
168             #[cfg(test)]
169             pub(crate) fn hash_set() -> HashSet<String> {
170                 let mut hash_set = HashSet::new();
171                 $(
172                     hash_set.insert(stringify!($i).to_owned());
173                 )+
174                 hash_set
175             }
176
177             pub(crate) fn is_valid_name(name: &str) -> bool {
178                 match name {
179                     $(
180                         stringify!($i) => true,
181                     )+
182                         _ => false,
183                 }
184             }
185
186             pub fn used_options(&self) -> PartialConfig {
187                 PartialConfig {
188                     $(
189                         $i: if self.$i.0.get() {
190                                 Some(self.$i.2.clone())
191                             } else {
192                                 None
193                             },
194                     )+
195                 }
196             }
197
198             pub fn all_options(&self) -> PartialConfig {
199                 PartialConfig {
200                     $(
201                         $i: Some(self.$i.2.clone()),
202                     )+
203                 }
204             }
205
206             pub fn override_value(&mut self, key: &str, val: &str)
207             {
208                 match key {
209                     $(
210                         stringify!($i) => {
211                             self.$i.1 = true;
212                             self.$i.2 = val.parse::<$ty>()
213                                 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
214                                                  stringify!($i),
215                                                  val,
216                                                  stringify!($ty)));
217                         }
218                     )+
219                     _ => panic!("Unknown config key in override: {}", key)
220                 }
221
222                 match key {
223                     "max_width" | "use_small_heuristics" => self.set_heuristics(),
224                     "license_template_path" => self.set_license_template(),
225                     &_ => (),
226                 }
227             }
228
229             pub fn is_hidden_option(name: &str) -> bool {
230                 const HIDE_OPTIONS: [&str; 4] =
231                     ["verbose", "verbose_diff", "file_lines", "width_heuristics"];
232                 HIDE_OPTIONS.contains(&name)
233             }
234
235             pub fn print_docs(out: &mut dyn Write, include_unstable: bool) {
236                 use std::cmp;
237                 let max = 0;
238                 $( let max = cmp::max(max, stringify!($i).len()+1); )+
239                 let space_str = " ".repeat(max);
240                 writeln!(out, "Configuration Options:").unwrap();
241                 $(
242                     if $stb || include_unstable {
243                         let name_raw = stringify!($i);
244
245                         if !Config::is_hidden_option(name_raw) {
246                             let mut name_out = String::with_capacity(max);
247                             for _ in name_raw.len()..max-1 {
248                                 name_out.push(' ')
249                             }
250                             name_out.push_str(name_raw);
251                             name_out.push(' ');
252                             writeln!(out,
253                                     "{}{} Default: {:?}{}",
254                                     name_out,
255                                     <$ty>::doc_hint(),
256                                     $def,
257                                     if !$stb { " (unstable)" } else { "" }).unwrap();
258                             $(
259                                 writeln!(out, "{}{}", space_str, $dstring).unwrap();
260                             )+
261                             writeln!(out).unwrap();
262                         }
263                     }
264                 )+
265             }
266
267             fn set_heuristics(&mut self) {
268                 if self.use_small_heuristics.2 == Heuristics::Default {
269                     let max_width = self.max_width.2;
270                     self.set().width_heuristics(WidthHeuristics::scaled(max_width));
271                 } else if self.use_small_heuristics.2 == Heuristics::Max {
272                     let max_width = self.max_width.2;
273                     self.set().width_heuristics(WidthHeuristics::set(max_width));
274                 } else {
275                     self.set().width_heuristics(WidthHeuristics::null());
276                 }
277             }
278
279             fn set_license_template(&mut self) {
280                 if self.was_set().license_template_path() {
281                     let lt_path = self.license_template_path();
282                     match license::load_and_compile_template(&lt_path) {
283                         Ok(re) => self.license_template = Some(re),
284                         Err(msg) => eprintln!("Warning for license template file {:?}: {}",
285                                               lt_path, msg),
286                     }
287                 }
288             }
289
290             fn set_ignore(&mut self, dir: &Path) {
291                 self.ignore.2.add_prefix(dir);
292             }
293
294             /// Returns `true` if the config key was explicitly set and is the default value.
295             pub fn is_default(&self, key: &str) -> bool {
296                 $(
297                     if let stringify!($i) = key {
298                         return self.$i.1 && self.$i.2 == $def;
299                     }
300                  )+
301                 false
302             }
303         }
304
305         // Template for the default configuration
306         impl Default for Config {
307             fn default() -> Config {
308                 Config {
309                     license_template: None,
310                     $(
311                         $i: (Cell::new(false), false, $def, $stb),
312                     )+
313                 }
314             }
315         }
316     )
317 }