]> git.lizzy.rs Git - rust.git/blob - src/config/config_type.rs
Go back to a non-workspace structure
[rust.git] / src / config / config_type.rs
1 // Copyright 2018 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 use config::file_lines::FileLines;
12 use config::options::WidthHeuristics;
13
14 /// Trait for types that can be used in `Config`.
15 pub trait ConfigType: Sized {
16     /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a
17     /// pipe-separated list of variants; for other types it returns "<type>".
18     fn doc_hint() -> String;
19 }
20
21 impl ConfigType for bool {
22     fn doc_hint() -> String {
23         String::from("<boolean>")
24     }
25 }
26
27 impl ConfigType for usize {
28     fn doc_hint() -> String {
29         String::from("<unsigned integer>")
30     }
31 }
32
33 impl ConfigType for isize {
34     fn doc_hint() -> String {
35         String::from("<signed integer>")
36     }
37 }
38
39 impl ConfigType for String {
40     fn doc_hint() -> String {
41         String::from("<string>")
42     }
43 }
44
45 impl ConfigType for FileLines {
46     fn doc_hint() -> String {
47         String::from("<json>")
48     }
49 }
50
51 impl ConfigType for WidthHeuristics {
52     fn doc_hint() -> String {
53         String::new()
54     }
55 }
56
57 /// Check if we're in a nightly build.
58 ///
59 /// The environment variable `CFG_RELEASE_CHANNEL` is set during the rustc bootstrap
60 /// to "stable", "beta", or "nightly" depending on what toolchain is being built.
61 /// If we are being built as part of the stable or beta toolchains, we want
62 /// to disable unstable configuration options.
63 ///
64 /// If we're being built by cargo (e.g. `cargo +nightly install rustfmt-nightly`),
65 /// `CFG_RELEASE_CHANNEL` is not set. As we only support being built against the
66 /// nightly compiler when installed from crates.io, default to nightly mode.
67 macro_rules! is_nightly_channel {
68     () => {
69         option_env!("CFG_RELEASE_CHANNEL")
70             .map(|c| c == "nightly")
71             .unwrap_or(true)
72     };
73 }
74
75 macro_rules! create_config {
76     ($($i:ident: $ty:ty, $def:expr, $stb:expr, $( $dstring:expr ),+ );+ $(;)*) => (
77         use std::collections::HashSet;
78
79         #[derive(Clone)]
80         pub struct Config {
81             // For each config item, we store a bool indicating whether it has
82             // been accessed and the value, and a bool whether the option was
83             // manually initialised, or taken from the default,
84             $($i: (Cell<bool>, bool, $ty, bool)),+
85         }
86
87         // Just like the Config struct but with each property wrapped
88         // as Option<T>. This is used to parse a rustfmt.toml that doesn't
89         // specify all properties of `Config`.
90         // We first parse into `PartialConfig`, then create a default `Config`
91         // and overwrite the properties with corresponding values from `PartialConfig`.
92         #[derive(Deserialize, Serialize, Clone)]
93         pub struct PartialConfig {
94             $(pub $i: Option<$ty>),+
95         }
96
97         impl PartialConfig {
98             pub fn to_toml(&self) -> Result<String, String> {
99                 // Non-user-facing options can't be specified in TOML
100                 let mut cloned = self.clone();
101                 cloned.file_lines = None;
102                 cloned.verbose = None;
103                 cloned.width_heuristics = None;
104
105                 ::toml::to_string(&cloned)
106                     .map_err(|e| format!("Could not output config: {}", e.to_string()))
107             }
108         }
109
110         // Macro hygiene won't allow us to make `set_$i()` methods on Config
111         // for each item, so this struct is used to give the API to set values:
112         // `config.set().option(false)`. It's pretty ugly. Consider replacing
113         // with `config.set_option(false)` if we ever get a stable/usable
114         // `concat_idents!()`.
115         pub struct ConfigSetter<'a>(&'a mut Config);
116
117         impl<'a> ConfigSetter<'a> {
118             $(
119             pub fn $i(&mut self, value: $ty) {
120                 (self.0).$i.2 = value;
121                 if stringify!($i) == "use_small_heuristics" {
122                     self.0.set_heuristics();
123                 }
124             }
125             )+
126         }
127
128         // Query each option, returns true if the user set the option, false if
129         // a default was used.
130         pub struct ConfigWasSet<'a>(&'a Config);
131
132         impl<'a> ConfigWasSet<'a> {
133             $(
134             pub fn $i(&self) -> bool {
135                 (self.0).$i.1
136             }
137             )+
138         }
139
140         impl Config {
141             pub fn version_meets_requirement(&self, error_summary: &mut Summary) -> bool {
142                 if self.was_set().required_version() {
143                     let version = env!("CARGO_PKG_VERSION");
144                     let required_version = self.required_version();
145                     if version != required_version {
146                         println!(
147                             "Error: rustfmt version ({}) doesn't match the required version ({})",
148                             version,
149                             required_version,
150                         );
151                         error_summary.add_formatting_error();
152                         return false;
153                     }
154                 }
155
156                 true
157             }
158
159             $(
160             pub fn $i(&self) -> $ty {
161                 self.$i.0.set(true);
162                 self.$i.2.clone()
163             }
164             )+
165
166             pub fn set<'a>(&'a mut self) -> ConfigSetter<'a> {
167                 ConfigSetter(self)
168             }
169
170             pub fn was_set<'a>(&'a self) -> ConfigWasSet<'a> {
171                 ConfigWasSet(self)
172             }
173
174             fn fill_from_parsed_config(mut self, parsed: PartialConfig) -> Config {
175             $(
176                 if let Some(val) = parsed.$i {
177                     if self.$i.3 {
178                         self.$i.1 = true;
179                         self.$i.2 = val;
180                     } else {
181                         if is_nightly_channel!() {
182                             self.$i.1 = true;
183                             self.$i.2 = val;
184                         } else {
185                             eprintln!("Warning: can't set `{} = {:?}`, unstable features are only \
186                                        available in nightly channel.", stringify!($i), val);
187                         }
188                     }
189                 }
190             )+
191                 self.set_heuristics();
192                 self
193             }
194
195             /// Returns a hash set initialized with every user-facing config option name.
196             pub fn hash_set() -> HashSet<String> {
197                 let mut hash_set = HashSet::new();
198                 $(
199                     hash_set.insert(stringify!($i).to_owned());
200                 )+
201                 hash_set
202             }
203
204             pub fn is_valid_name(name: &str) -> bool {
205                 match name {
206                     $(
207                         stringify!($i) => true,
208                     )+
209                         _ => false,
210                 }
211             }
212
213             pub fn from_toml(toml: &str) -> Result<Config, String> {
214                 let parsed: ::toml::Value =
215                     toml.parse().map_err(|e| format!("Could not parse TOML: {}", e))?;
216                 let mut err: String = String::new();
217                 {
218                     let table = parsed
219                         .as_table()
220                         .ok_or(String::from("Parsed config was not table"))?;
221                     for key in table.keys() {
222                         if !Config::is_valid_name(key) {
223                             let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
224                             err.push_str(msg)
225                         }
226                     }
227                 }
228                 match parsed.try_into() {
229                     Ok(parsed_config) => {
230                         if !err.is_empty() {
231                             eprint!("{}", err);
232                         }
233                         Ok(Config::default().fill_from_parsed_config(parsed_config))
234                     }
235                     Err(e) => {
236                         err.push_str("Error: Decoding config file failed:\n");
237                         err.push_str(format!("{}\n", e).as_str());
238                         err.push_str("Please check your config file.");
239                         Err(err)
240                     }
241                 }
242             }
243
244             pub fn used_options(&self) -> PartialConfig {
245                 PartialConfig {
246                     $(
247                         $i: if self.$i.0.get() {
248                                 Some(self.$i.2.clone())
249                             } else {
250                                 None
251                             },
252                     )+
253                 }
254             }
255
256             pub fn all_options(&self) -> PartialConfig {
257                 PartialConfig {
258                     $(
259                         $i: Some(self.$i.2.clone()),
260                     )+
261                 }
262             }
263
264             pub fn override_value(&mut self, key: &str, val: &str)
265             {
266                 match key {
267                     $(
268                         stringify!($i) => {
269                             self.$i.2 = val.parse::<$ty>()
270                                 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
271                                                  stringify!($i),
272                                                  val,
273                                                  stringify!($ty)));
274                         }
275                     )+
276                     _ => panic!("Unknown config key in override: {}", key)
277                 }
278
279                 if key == "use_small_heuristics" {
280                     self.set_heuristics();
281                 }
282             }
283
284             /// Construct a `Config` from the toml file specified at `file_path`.
285             ///
286             /// This method only looks at the provided path, for a method that
287             /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
288             ///
289             /// Return a `Config` if the config could be read and parsed from
290             /// the file, Error otherwise.
291             pub fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
292                 let mut file = File::open(&file_path)?;
293                 let mut toml = String::new();
294                 file.read_to_string(&mut toml)?;
295                 Config::from_toml(&toml).map_err(|err| Error::new(ErrorKind::InvalidData, err))
296             }
297
298             /// Resolve the config for input in `dir`.
299             ///
300             /// Searches for `rustfmt.toml` beginning with `dir`, and
301             /// recursively checking parents of `dir` if no config file is found.
302             /// If no config file exists in `dir` or in any parent, a
303             /// default `Config` will be returned (and the returned path will be empty).
304             ///
305             /// Returns the `Config` to use, and the path of the project file if there was
306             /// one.
307             pub fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
308
309                 /// Try to find a project file in the given directory and its parents.
310                 /// Returns the path of a the nearest project file if one exists,
311                 /// or `None` if no project file was found.
312                 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
313                     let mut current = if dir.is_relative() {
314                         env::current_dir()?.join(dir)
315                     } else {
316                         dir.to_path_buf()
317                     };
318
319                     current = fs::canonicalize(current)?;
320
321                     loop {
322                         match get_toml_path(&current) {
323                             Ok(Some(path)) => return Ok(Some(path)),
324                             Err(e) => return Err(e),
325                             _ => ()
326                         }
327
328                         // If the current directory has no parent, we're done searching.
329                         if !current.pop() {
330                             return Ok(None);
331                         }
332                     }
333                 }
334
335                 match resolve_project_file(dir)? {
336                     None => Ok((Config::default(), None)),
337                     Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
338                 }
339             }
340
341             pub fn is_hidden_option(name: &str) -> bool {
342                 const HIDE_OPTIONS: [&str; 3] = ["verbose", "file_lines", "width_heuristics"];
343                 HIDE_OPTIONS.contains(&name)
344             }
345
346             pub fn print_docs() {
347                 use std::cmp;
348                 let max = 0;
349                 $( let max = cmp::max(max, stringify!($i).len()+1); )+
350                 let mut space_str = String::with_capacity(max);
351                 for _ in 0..max {
352                     space_str.push(' ');
353                 }
354                 println!("Configuration Options:");
355                 $(
356                     let name_raw = stringify!($i);
357
358                     if !Config::is_hidden_option(name_raw) {
359                         let mut name_out = String::with_capacity(max);
360                         for _ in name_raw.len()..max-1 {
361                             name_out.push(' ')
362                         }
363                         name_out.push_str(name_raw);
364                         name_out.push(' ');
365                         println!("{}{} Default: {:?}",
366                                 name_out,
367                                 <$ty>::doc_hint(),
368                                 $def);
369                         $(
370                             println!("{}{}", space_str, $dstring);
371                         )+
372                         println!();
373                     }
374                 )+
375             }
376
377             fn set_heuristics(&mut self) {
378                 if self.use_small_heuristics.2 {
379                     let max_width = self.max_width.2;
380                     self.set().width_heuristics(WidthHeuristics::scaled(max_width));
381                 } else {
382                     self.set().width_heuristics(WidthHeuristics::null());
383                 }
384             }
385         }
386
387         // Template for the default configuration
388         impl Default for Config {
389             fn default() -> Config {
390                 Config {
391                     $(
392                         $i: (Cell::new(false), false, $def, $stb),
393                     )+
394                 }
395             }
396         }
397     )
398 }