]> git.lizzy.rs Git - rust.git/blob - src/config.rs
Fix weird indentaion in chain
[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         pub struct PartialConfig {
229             $(pub $i: Option<$ty>),+
230         }
231
232         impl PartialConfig {
233             pub fn to_toml(&self) -> Result<String, String> {
234                 // file_lines can't be specified in TOML
235                 let mut cloned = self.clone();
236                 cloned.file_lines = None;
237
238                 toml::to_string(&cloned)
239                     .map_err(|e| format!("Could not output config: {}", e.to_string()))
240             }
241         }
242
243         // Macro hygiene won't allow us to make `set_$i()` methods on Config
244         // for each item, so this struct is used to give the API to set values:
245         // `config.get().option(false)`. It's pretty ugly. Consider replacing
246         // with `config.set_option(false)` if we ever get a stable/usable
247         // `concat_idents!()`.
248         pub struct ConfigSetter<'a>(&'a mut Config);
249
250         impl<'a> ConfigSetter<'a> {
251             $(
252             pub fn $i(&mut self, value: $ty) {
253                 (self.0).$i.1 = value;
254             }
255             )+
256         }
257
258         impl Config {
259
260             $(
261             pub fn $i(&self) -> $ty {
262                 self.$i.0.set(true);
263                 self.$i.1.clone()
264             }
265             )+
266
267             pub fn set<'a>(&'a mut self) -> ConfigSetter<'a> {
268                 ConfigSetter(self)
269             }
270
271             fn fill_from_parsed_config(mut self, parsed: PartialConfig) -> Config {
272             $(
273                 if let Some(val) = parsed.$i {
274                     self.$i.1 = val;
275                 }
276             )+
277                 self
278             }
279
280             pub fn from_toml(toml: &str) -> Result<Config, String> {
281                 let parsed: toml::Value =
282                     toml.parse().map_err(|e| format!("Could not parse TOML: {}", e))?;
283                 let mut err: String = String::new();
284                 {
285                     let table = parsed
286                         .as_table()
287                         .ok_or(String::from("Parsed config was not table"))?;
288                     for (key, _) in table {
289                         match &**key {
290                             $(
291                                 stringify!($i) => (),
292                             )+
293                                 _ => {
294                                     let msg =
295                                         &format!("Warning: Unknown configuration option `{}`\n",
296                                                  key);
297                                     err.push_str(msg)
298                                 }
299                         }
300                     }
301                 }
302                 match parsed.try_into() {
303                     Ok(parsed_config) =>
304                         Ok(Config::default().fill_from_parsed_config(parsed_config)),
305                     Err(e) => {
306                         err.push_str("Error: Decoding config file failed:\n");
307                         err.push_str(format!("{}\n", e).as_str());
308                         err.push_str("Please check your config file.\n");
309                         Err(err)
310                     }
311                 }
312             }
313
314             pub fn used_options(&self) -> PartialConfig {
315                 PartialConfig {
316                     $(
317                         $i: if self.$i.0.get() {
318                                 Some(self.$i.1.clone())
319                             } else {
320                                 None
321                             },
322                     )+
323                 }
324             }
325
326             pub fn all_options(&self) -> PartialConfig {
327                 PartialConfig {
328                     $(
329                         $i: Some(self.$i.1.clone()),
330                     )+
331                 }
332             }
333
334             pub fn override_value(&mut self, key: &str, val: &str)
335             {
336                 match key {
337                     $(
338                         stringify!($i) => {
339                             self.$i.1 = val.parse::<$ty>()
340                                 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
341                                                  stringify!($i),
342                                                  val,
343                                                  stringify!($ty)));
344                         }
345                     )+
346                     _ => panic!("Unknown config key in override: {}", key)
347                 }
348             }
349
350             pub fn print_docs() {
351                 use std::cmp;
352                 let max = 0;
353                 $( let max = cmp::max(max, stringify!($i).len()+1); )+
354                 let mut space_str = String::with_capacity(max);
355                 for _ in 0..max {
356                     space_str.push(' ');
357                 }
358                 println!("Configuration Options:");
359                 $(
360                     let name_raw = stringify!($i);
361                     let mut name_out = String::with_capacity(max);
362                     for _ in name_raw.len()..max-1 {
363                         name_out.push(' ')
364                     }
365                     name_out.push_str(name_raw);
366                     name_out.push(' ');
367                     println!("{}{} Default: {:?}",
368                              name_out,
369                              <$ty>::doc_hint(),
370                              $def);
371                     $(
372                         println!("{}{}", space_str, $dstring);
373                     )+
374                     println!("");
375                 )+
376             }
377         }
378
379         // Template for the default configuration
380         impl Default for Config {
381             fn default() -> Config {
382                 Config {
383                     $(
384                         $i: (Cell::new(false), $def),
385                     )+
386                 }
387             }
388         }
389     )
390 }
391
392 create_config! {
393     verbose: bool, false, "Use verbose output";
394     disable_all_formatting: bool, false, "Don't reformat anything";
395     skip_children: bool, false, "Don't reformat out of line modules";
396     file_lines: FileLines, FileLines::all(),
397         "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
398          via the --file-lines option";
399     max_width: usize, 100, "Maximum width of each line";
400     error_on_line_overflow: bool, true, "Error if unable to get all lines within max_width";
401     tab_spaces: usize, 4, "Number of spaces per tab";
402     fn_call_width: usize, 60,
403         "Maximum width of the args of a function call before falling back to vertical formatting";
404     struct_lit_width: usize, 18,
405         "Maximum width in the body of a struct lit before falling back to vertical formatting";
406     struct_variant_width: usize, 35,
407         "Maximum width in the body of a struct variant before falling back to vertical formatting";
408     force_explicit_abi: bool, true, "Always print the abi for extern items";
409     newline_style: NewlineStyle, NewlineStyle::Unix, "Unix or Windows line endings";
410     fn_brace_style: BraceStyle, BraceStyle::SameLineWhere, "Brace style for functions";
411     item_brace_style: BraceStyle, BraceStyle::SameLineWhere, "Brace style for structs and enums";
412     control_style: Style, Style::Default, "Indent style for control flow statements";
413     control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine,
414         "Brace style for control flow constructs";
415     impl_empty_single_line: bool, true, "Put empty-body implementations on a single line";
416     trailing_comma: SeparatorTactic, SeparatorTactic::Vertical,
417         "How to handle trailing commas for lists";
418     fn_empty_single_line: bool, true, "Put empty-body functions on a single line";
419     fn_single_line: bool, false, "Put single-expression functions on a single line";
420     fn_return_indent: ReturnIndent, ReturnIndent::WithArgs,
421         "Location of return type in function declaration";
422     fn_args_paren_newline: bool, true, "If function argument parenthesis goes on a newline";
423     fn_args_density: Density, Density::Tall, "Argument density in functions";
424     fn_args_layout: IndentStyle, IndentStyle::Visual,
425         "Layout of function arguments and tuple structs";
426     array_layout: IndentStyle, IndentStyle::Visual, "Indent on arrays";
427     array_width: usize, 60,
428         "Maximum width of an array literal before falling back to vertical formatting";
429     type_punctuation_density: TypeDensity, TypeDensity::Wide,
430         "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
431     where_style: Style, Style::Default, "Overall strategy for where clauses";
432     // TODO:
433     // 1. Should we at least try to put the where clause on the same line as the rest of the
434     // function decl?
435     // 2. Currently options `Tall` and `Vertical` produce the same output.
436     where_density: Density, Density::CompressedIfEmpty, "Density of a where clause";
437     where_layout: ListTactic, ListTactic::Vertical, "Element layout inside a where clause";
438     where_pred_indent: IndentStyle, IndentStyle::Visual,
439         "Indentation style of a where predicate";
440     generics_indent: IndentStyle, IndentStyle::Visual, "Indentation of generics";
441     struct_lit_style: IndentStyle, IndentStyle::Block, "Style of struct definition";
442     struct_lit_multiline_style: MultilineStyle, MultilineStyle::PreferSingle,
443         "Multiline style on literal structs";
444     fn_call_style: IndentStyle, IndentStyle::Visual, "Indentation for function calls, etc.";
445     report_todo: ReportTactic, ReportTactic::Never,
446         "Report all, none or unnumbered occurrences of TODO in source file comments";
447     report_fixme: ReportTactic, ReportTactic::Never,
448         "Report all, none or unnumbered occurrences of FIXME in source file comments";
449     chain_indent: IndentStyle, IndentStyle::Block, "Indentation of chain";
450     chain_one_line_max: usize, 60, "Maximum length of a chain to fit on a single line";
451     reorder_imports: bool, false, "Reorder import statements alphabetically";
452     reorder_imports_in_group: bool, false, "Reorder import statements in group";
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_suffixes: 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_set() {
496         let mut config = Config::default();
497         config.set().verbose(false);
498         assert_eq!(config.verbose(), false);
499         config.set().verbose(true);
500         assert_eq!(config.verbose(), true);
501     }
502
503     #[test]
504     fn test_config_used_to_toml() {
505         let config = Config::default();
506
507         let verbose = config.verbose();
508         let skip_children = config.skip_children();
509
510         let used_options = config.used_options();
511         let toml = used_options.to_toml().unwrap();
512         assert_eq!(toml,
513                    format!("verbose = {}\nskip_children = {}\n", verbose, skip_children));
514     }
515 }