]> git.lizzy.rs Git - rust.git/blob - src/config.rs
Provide `config.set().item(value)` API.
[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::cell::Cell;
14
15 use file_lines::FileLines;
16 use lists::{SeparatorTactic, ListTactic};
17
18 macro_rules! configuration_option_enum{
19     ($e:ident: $( $x:ident ),+ $(,)*) => {
20         #[derive(Copy, Clone, Eq, PartialEq, Debug)]
21         pub enum $e {
22             $( $x ),+
23         }
24
25         impl_enum_serialize_and_deserialize!($e, $( $x ),+);
26     }
27 }
28
29 configuration_option_enum! { Style:
30     Rfc, // Follow the style RFCs style.
31     Default, // Follow the traditional Rustfmt style.
32 }
33
34 configuration_option_enum! { NewlineStyle:
35     Windows, // \r\n
36     Unix, // \n
37     Native, // \r\n in Windows, \n on other platforms
38 }
39
40 configuration_option_enum! { BraceStyle:
41     AlwaysNextLine,
42     PreferSameLine,
43     // Prefer same line except where there is a where clause, in which case force
44     // the brace to the next line.
45     SameLineWhere,
46 }
47
48 configuration_option_enum! { ControlBraceStyle:
49     // K&R style, Rust community default
50     AlwaysSameLine,
51     // Stroustrup style
52     ClosingNextLine,
53     // Allman style
54     AlwaysNextLine,
55 }
56
57 // How to indent a function's return type.
58 configuration_option_enum! { ReturnIndent:
59     // Aligned with the arguments
60     WithArgs,
61     // Aligned with the where clause
62     WithWhereClause,
63 }
64
65 configuration_option_enum! { IndentStyle:
66     // First line on the same line as the opening brace, all lines aligned with
67     // the first line.
68     Visual,
69     // First line is on a new line and all lines align with block indent.
70     Block,
71 }
72
73 configuration_option_enum! { Density:
74     // Fit as much on one line as possible.
75     Compressed,
76     // Use more lines.
77     Tall,
78     // Try to compress if the body is empty.
79     CompressedIfEmpty,
80     // Place every item on a separate line.
81     Vertical,
82 }
83
84 configuration_option_enum! { TypeDensity:
85     // No spaces around "=" and "+"
86     Compressed,
87     // Spaces around " = " and " + "
88     Wide,
89 }
90
91
92 impl Density {
93     pub fn to_list_tactic(self) -> ListTactic {
94         match self {
95             Density::Compressed => ListTactic::Mixed,
96             Density::Tall |
97             Density::CompressedIfEmpty => ListTactic::HorizontalVertical,
98             Density::Vertical => ListTactic::Vertical,
99         }
100     }
101 }
102
103 configuration_option_enum! { LicensePolicy:
104     // Do not place license text at top of files
105     NoLicense,
106     // Use the text in "license" field as the license
107     TextLicense,
108     // Use a text file as the license text
109     FileLicense,
110 }
111
112 configuration_option_enum! { MultilineStyle:
113     // Use horizontal layout if it fits in one line, fall back to vertical
114     PreferSingle,
115     // Use vertical layout
116     ForceMulti,
117 }
118
119 impl MultilineStyle {
120     pub fn to_list_tactic(self) -> ListTactic {
121         match self {
122             MultilineStyle::PreferSingle => ListTactic::HorizontalVertical,
123             MultilineStyle::ForceMulti => ListTactic::Vertical,
124         }
125     }
126 }
127
128 configuration_option_enum! { ReportTactic:
129     Always,
130     Unnumbered,
131     Never,
132 }
133
134 configuration_option_enum! { WriteMode:
135     // Backs the original file up and overwrites the original.
136     Replace,
137     // Overwrites original file without backup.
138     Overwrite,
139     // Writes the output to stdout.
140     Display,
141     // Writes the diff to stdout.
142     Diff,
143     // Displays how much of the input file was processed
144     Coverage,
145     // Unfancy stdout
146     Plain,
147     // Outputs a checkstyle XML file.
148     Checkstyle,
149 }
150
151 /// Trait for types that can be used in `Config`.
152 pub trait ConfigType: Sized {
153     /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a
154     /// pipe-separated list of variants; for other types it returns "<type>".
155     fn doc_hint() -> String;
156 }
157
158 impl ConfigType for bool {
159     fn doc_hint() -> String {
160         String::from("<boolean>")
161     }
162 }
163
164 impl ConfigType for usize {
165     fn doc_hint() -> String {
166         String::from("<unsigned integer>")
167     }
168 }
169
170 impl ConfigType for isize {
171     fn doc_hint() -> String {
172         String::from("<signed integer>")
173     }
174 }
175
176 impl ConfigType for String {
177     fn doc_hint() -> String {
178         String::from("<string>")
179     }
180 }
181
182 impl ConfigType for FileLines {
183     fn doc_hint() -> String {
184         String::from("<json>")
185     }
186 }
187
188 pub struct ConfigHelpItem {
189     option_name: &'static str,
190     doc_string: &'static str,
191     variant_names: String,
192     default: &'static str,
193 }
194
195 impl ConfigHelpItem {
196     pub fn option_name(&self) -> &'static str {
197         self.option_name
198     }
199
200     pub fn doc_string(&self) -> &'static str {
201         self.doc_string
202     }
203
204     pub fn variant_names(&self) -> &String {
205         &self.variant_names
206     }
207
208     pub fn default(&self) -> &'static str {
209         self.default
210     }
211 }
212
213 macro_rules! create_config {
214     ($($i:ident: $ty:ty, $def:expr, $( $dstring:expr ),+ );+ $(;)*) => (
215         #[derive(Clone)]
216         pub struct Config {
217             // For each config item, we store a bool indicating whether it has
218             // been accessed and the value.
219             $($i: (Cell<bool>, $ty)),+
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         // specity 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         struct PartialConfig {
229             $(pub $i: Option<$ty>),+
230         }
231
232         // Macro hygiene won't allow us to make `set_$i()` methods on Config
233         // for each item, so this struct is used to give the API to set values:
234         // `config.get().option(false)`. It's pretty ugly. Consider replacing
235         // with `config.set_option(false)` if we ever get a stable/usable
236         // `concat_idents!()`.
237         pub struct ConfigSetter<'a>(&'a mut Config);
238
239         impl<'a> ConfigSetter<'a> {
240             $(
241             pub fn $i(&mut self, value: $ty) {
242                 (self.0).$i.1 = value;
243             }
244             )+
245         }
246
247         impl Config {
248
249             $(
250             pub fn $i(&self) -> $ty {
251                 self.$i.0.set(true);
252                 self.$i.1.clone()
253             }
254             )+
255
256             pub fn set<'a>(&'a mut self) -> ConfigSetter<'a> {
257                 ConfigSetter(self)
258             }
259
260             fn fill_from_parsed_config(mut self, parsed: PartialConfig) -> Config {
261             $(
262                 if let Some(val) = parsed.$i {
263                     self.$i.1 = val;
264                 }
265             )+
266                 self
267             }
268
269             pub fn from_toml(toml: &str) -> Result<Config, String> {
270                 let parsed: toml::Value =
271                     toml.parse().map_err(|e| format!("Could not parse TOML: {}", e))?;
272                 let mut err: String = String::new();
273                 {
274                     let table = parsed
275                         .as_table()
276                         .ok_or(String::from("Parsed config was not table"))?;
277                     for (key, _) in table {
278                         match &**key {
279                             $(
280                                 stringify!($i) => (),
281                             )+
282                                 _ => {
283                                     let msg =
284                                         &format!("Warning: Unknown configuration option `{}`\n",
285                                                  key);
286                                     err.push_str(msg)
287                                 }
288                         }
289                     }
290                 }
291                 match parsed.try_into() {
292                     Ok(parsed_config) =>
293                         Ok(Config::default().fill_from_parsed_config(parsed_config)),
294                     Err(e) => {
295                         err.push_str("Error: Decoding config file failed:\n");
296                         err.push_str(format!("{}\n", e).as_str());
297                         err.push_str("Please check your config file.\n");
298                         Err(err)
299                     }
300                 }
301             }
302
303             pub fn used_to_toml(&self) -> Result<String, String> {
304                 let mut partial = PartialConfig {
305                     $(
306                         $i: if self.$i.0.get() {
307                                 Some(self.$i.1.clone())
308                             } else {
309                                 None
310                             },
311                     )+
312                 };
313
314                 // file_lines is special and can't be specified in toml.
315                 partial.file_lines = None;
316
317                 toml::to_string(&partial)
318                     .map_err(|e| format!("Could not output config: {}", e.to_string()))
319             }
320
321             pub fn to_toml(&self) -> Result<String, String> {
322                 let mut partial = PartialConfig {
323                     $(
324                         $i: Some(self.$i.1.clone()),
325                     )+
326                 };
327
328                 // file_lines is special and can't be specified in toml.
329                 partial.file_lines = None;
330
331                 toml::to_string(&partial)
332                     .map_err(|e| format!("Could not output config: {}", e.to_string()))
333             }
334
335             pub fn override_value(&mut self, key: &str, val: &str)
336             {
337                 match key {
338                     $(
339                         stringify!($i) => {
340                             self.$i.1 = val.parse::<$ty>()
341                                 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
342                                                  stringify!($i),
343                                                  val,
344                                                  stringify!($ty)));
345                         }
346                     )+
347                     _ => panic!("Unknown config key in override: {}", key)
348                 }
349             }
350
351             pub fn print_docs() {
352                 use std::cmp;
353                 let max = 0;
354                 $( let max = cmp::max(max, stringify!($i).len()+1); )+
355                 let mut space_str = String::with_capacity(max);
356                 for _ in 0..max {
357                     space_str.push(' ');
358                 }
359                 println!("Configuration Options:");
360                 $(
361                     let name_raw = stringify!($i);
362                     let mut name_out = String::with_capacity(max);
363                     for _ in name_raw.len()..max-1 {
364                         name_out.push(' ')
365                     }
366                     name_out.push_str(name_raw);
367                     name_out.push(' ');
368                     println!("{}{} Default: {:?}",
369                              name_out,
370                              <$ty>::doc_hint(),
371                              $def);
372                     $(
373                         println!("{}{}", space_str, $dstring);
374                     )+
375                     println!("");
376                 )+
377             }
378         }
379
380         // Template for the default configuration
381         impl Default for Config {
382             fn default() -> Config {
383                 Config {
384                     $(
385                         $i: (Cell::new(false), $def),
386                     )+
387                 }
388             }
389         }
390     )
391 }
392
393 create_config! {
394     verbose: bool, false, "Use verbose output";
395     disable_all_formatting: bool, false, "Don't reformat anything";
396     skip_children: bool, false, "Don't reformat out of line modules";
397     file_lines: FileLines, FileLines::all(),
398         "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
399          via the --file-lines option";
400     max_width: usize, 100, "Maximum width of each line";
401     error_on_line_overflow: bool, true, "Error if unable to get all lines within max_width";
402     tab_spaces: usize, 4, "Number of spaces per tab";
403     fn_call_width: usize, 60,
404         "Maximum width of the args of a function call before falling back to vertical formatting";
405     struct_lit_width: usize, 18,
406         "Maximum width in the body of a struct lit before falling back to vertical formatting";
407     struct_variant_width: usize, 35,
408         "Maximum width in the body of a struct variant before falling back to vertical formatting";
409     force_explicit_abi: bool, true, "Always print the abi for extern items";
410     newline_style: NewlineStyle, NewlineStyle::Unix, "Unix or Windows line endings";
411     fn_brace_style: BraceStyle, BraceStyle::SameLineWhere, "Brace style for functions";
412     item_brace_style: BraceStyle, BraceStyle::SameLineWhere, "Brace style for structs and enums";
413     control_style: Style, Style::Default, "Indent style for control flow statements";
414     control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine,
415         "Brace style for control flow constructs";
416     impl_empty_single_line: bool, true, "Put empty-body implementations on a single line";
417     trailing_comma: SeparatorTactic, SeparatorTactic::Vertical,
418         "How to handle trailing commas for lists";
419     fn_empty_single_line: bool, true, "Put empty-body functions on a single line";
420     fn_single_line: bool, false, "Put single-expression functions on a single line";
421     fn_return_indent: ReturnIndent, ReturnIndent::WithArgs,
422         "Location of return type in function declaration";
423     fn_args_paren_newline: bool, true, "If function argument parenthesis goes on a newline";
424     fn_args_density: Density, Density::Tall, "Argument density in functions";
425     fn_args_layout: IndentStyle, IndentStyle::Visual,
426         "Layout of function arguments and tuple structs";
427     array_layout: IndentStyle, IndentStyle::Visual, "Indent on arrays";
428     array_width: usize, 60,
429         "Maximum width of an array literal before falling back to vertical formatting";
430     type_punctuation_density: TypeDensity, TypeDensity::Wide,
431         "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
432     where_style: Style, Style::Default, "Overall strategy for where clauses";
433     // TODO:
434     // 1. Should we at least try to put the where clause on the same line as the rest of the
435     // function decl?
436     // 2. Currently options `Tall` and `Vertical` produce the same output.
437     where_density: Density, Density::CompressedIfEmpty, "Density of a where clause";
438     where_layout: ListTactic, ListTactic::Vertical, "Element layout inside a where clause";
439     where_pred_indent: IndentStyle, IndentStyle::Visual,
440         "Indentation style of a where predicate";
441     generics_indent: IndentStyle, IndentStyle::Visual, "Indentation of generics";
442     struct_lit_style: IndentStyle, IndentStyle::Block, "Style of struct definition";
443     struct_lit_multiline_style: MultilineStyle, MultilineStyle::PreferSingle,
444         "Multiline style on literal structs";
445     fn_call_style: IndentStyle, IndentStyle::Visual, "Indentation for function calls, etc.";
446     report_todo: ReportTactic, ReportTactic::Never,
447         "Report all, none or unnumbered occurrences of TODO in source file comments";
448     report_fixme: ReportTactic, ReportTactic::Never,
449         "Report all, none or unnumbered occurrences of FIXME in source file comments";
450     chain_indent: IndentStyle, IndentStyle::Block, "Indentation of chain";
451     chain_one_line_max: usize, 60, "Maximum length of a chain to fit on a single line";
452     reorder_imports: bool, false, "Reorder import statements alphabetically";
453     reorder_imported_names: bool, false,
454         "Reorder lists of names in import statements alphabetically";
455     single_line_if_else_max_width: usize, 50, "Maximum line length for single line if-else \
456                                                 expressions. A value of zero means always break \
457                                                 if-else expressions.";
458     format_strings: bool, false, "Format string literals where necessary";
459     force_format_strings: bool, false, "Always format string literals";
460     take_source_hints: bool, false, "Retain some formatting characteristics from the source code";
461     hard_tabs: bool, false, "Use tab characters for indentation, spaces for alignment";
462     wrap_comments: bool, false, "Break comments to fit on the line";
463     comment_width: usize, 80, "Maximum length of comments. No effect unless wrap_comments = true";
464     normalize_comments: bool, false, "Convert /* */ comments to // comments where possible";
465     wrap_match_arms: bool, true, "Wrap multiline match arms in blocks";
466     match_block_trailing_comma: bool, false,
467         "Put a trailing comma after a block based match arm (non-block arms are not affected)";
468     indent_match_arms: bool, true, "Indent match arms instead of keeping them at the same \
469                                     indentation level as the match keyword";
470     closure_block_indent_threshold: isize, 7, "How many lines a closure must have before it is \
471                                                block indented. -1 means never use block indent.";
472     space_before_type_annotation: bool, false,
473         "Leave a space before the colon in a type annotation";
474     space_after_type_annotation_colon: bool, true,
475         "Leave a space after the colon in a type annotation";
476     space_before_bound: bool, false, "Leave a space before the colon in a trait or lifetime bound";
477     space_after_bound_colon: bool, true,
478         "Leave a space after the colon in a trait or lifetime bound";
479     spaces_around_ranges: bool, false, "Put spaces around the  .. and ... range operators";
480     spaces_within_angle_brackets: bool, false, "Put spaces within non-empty generic arguments";
481     spaces_within_square_brackets: bool, false, "Put spaces within non-empty square brackets";
482     spaces_within_parens: bool, false, "Put spaces within non-empty parentheses";
483     use_try_shorthand: bool, false, "Replace uses of the try! macro by the ? shorthand";
484     write_mode: WriteMode, WriteMode::Replace,
485         "What Write Mode to use when none is supplied: Replace, Overwrite, Display, Diff, Coverage";
486     condense_wildcard_suffices: bool, false, "Replace strings of _ wildcards by a single .. in \
487                                               tuple patterns"
488 }
489
490 #[cfg(test)]
491 mod test {
492     use super::Config;
493
494     #[test]
495     fn test_config_tracking() {
496         let config = Config::default();
497         assert!(!config.verbose.0.get());
498         config.verbose();
499         config.skip_children();
500         assert!(config.verbose.0.get());
501         assert!(config.skip_children.0.get());
502         assert!(!config.disable_all_formatting.0.get());
503     }
504
505     #[test]
506     fn test_config_set() {
507         let mut config = Config::default();
508         config.set().verbose(false);
509         assert_eq!(config.verbose(), false);
510         config.set().verbose(true);
511         assert_eq!(config.verbose(), true);
512     }
513 }