]> git.lizzy.rs Git - rust.git/blob - src/config.rs
Coalesce trailing comma options
[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 file_lines::FileLines;
14 use lists::{SeparatorTactic, ListTactic};
15 use std::io::Write;
16
17 macro_rules! configuration_option_enum{
18     ($e:ident: $( $x:ident ),+ $(,)*) => {
19         #[derive(Copy, Clone, Eq, PartialEq, Debug)]
20         pub enum $e {
21             $( $x ),+
22         }
23
24         impl_enum_decodable!($e, $( $x ),+);
25     }
26 }
27
28 configuration_option_enum! { NewlineStyle:
29     Windows, // \r\n
30     Unix, // \n
31     Native, // \r\n in Windows, \n on other platforms
32 }
33
34 configuration_option_enum! { BraceStyle:
35     AlwaysNextLine,
36     PreferSameLine,
37     // Prefer same line except where there is a where clause, in which case force
38     // the brace to the next line.
39     SameLineWhere,
40 }
41
42 configuration_option_enum! { ControlBraceStyle:
43     // K&R style, Rust community default
44     AlwaysSameLine,
45     // Stroustrup style
46     ClosingNextLine,
47     // Allman style
48     AlwaysNextLine,
49 }
50
51 // How to indent a function's return type.
52 configuration_option_enum! { ReturnIndent:
53     // Aligned with the arguments
54     WithArgs,
55     // Aligned with the where clause
56     WithWhereClause,
57 }
58
59 // How to style a struct literal.
60 configuration_option_enum! { StructLitStyle:
61     // First line on the same line as the opening brace, all lines aligned with
62     // the first line.
63     Visual,
64     // First line is on a new line and all lines align with block indent.
65     Block,
66     // FIXME Maybe we should also have an option to align types.
67 }
68
69 // How to style fn args.
70 configuration_option_enum! { FnArgLayoutStyle:
71     // First line on the same line as the opening brace, all lines aligned with
72     // the first line.
73     Visual,
74     // Put args on one line if they fit, or start a new line with block indent.
75     Block,
76     // First line is on a new line and all lines align with block indent.
77     BlockAlways,
78 }
79
80 configuration_option_enum! { BlockIndentStyle:
81     // Same level as parent.
82     Inherit,
83     // One level deeper than parent.
84     Tabbed,
85     // Aligned with block open.
86     Visual,
87 }
88
89 configuration_option_enum! { Density:
90     // Fit as much on one line as possible.
91     Compressed,
92     // Use more lines.
93     Tall,
94     // Try to compress if the body is empty.
95     CompressedIfEmpty,
96     // Place every item on a separate line.
97     Vertical,
98 }
99
100 configuration_option_enum! { TypeDensity:
101     // No spaces around "=" and "+"
102     Compressed,
103     // Spaces around " = " and " + "
104     Wide,
105 }
106
107
108 impl Density {
109     pub fn to_list_tactic(self) -> ListTactic {
110         match self {
111             Density::Compressed => ListTactic::Mixed,
112             Density::Tall |
113             Density::CompressedIfEmpty => ListTactic::HorizontalVertical,
114             Density::Vertical => ListTactic::Vertical,
115         }
116     }
117 }
118
119 configuration_option_enum! { LicensePolicy:
120     // Do not place license text at top of files
121     NoLicense,
122     // Use the text in "license" field as the license
123     TextLicense,
124     // Use a text file as the license text
125     FileLicense,
126 }
127
128 configuration_option_enum! { MultilineStyle:
129     // Use horizontal layout if it fits in one line, fall back to vertical
130     PreferSingle,
131     // Use vertical layout
132     ForceMulti,
133 }
134
135 impl MultilineStyle {
136     pub fn to_list_tactic(self) -> ListTactic {
137         match self {
138             MultilineStyle::PreferSingle => ListTactic::HorizontalVertical,
139             MultilineStyle::ForceMulti => ListTactic::Vertical,
140         }
141     }
142 }
143
144 configuration_option_enum! { ReportTactic:
145     Always,
146     Unnumbered,
147     Never,
148 }
149
150 configuration_option_enum! { WriteMode:
151     // Backs the original file up and overwrites the original.
152     Replace,
153     // Overwrites original file without backup.
154     Overwrite,
155     // Writes the output to stdout.
156     Display,
157     // Writes the diff to stdout.
158     Diff,
159     // Displays how much of the input file was processed
160     Coverage,
161     // Unfancy stdout
162     Plain,
163     // Outputs a checkstyle XML file.
164     Checkstyle,
165 }
166
167 /// Trait for types that can be used in `Config`.
168 pub trait ConfigType: Sized {
169     /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a
170     /// pipe-separated list of variants; for other types it returns "<type>".
171     fn doc_hint() -> String;
172 }
173
174 impl ConfigType for bool {
175     fn doc_hint() -> String {
176         String::from("<boolean>")
177     }
178 }
179
180 impl ConfigType for usize {
181     fn doc_hint() -> String {
182         String::from("<unsigned integer>")
183     }
184 }
185
186 impl ConfigType for isize {
187     fn doc_hint() -> String {
188         String::from("<signed integer>")
189     }
190 }
191
192 impl ConfigType for String {
193     fn doc_hint() -> String {
194         String::from("<string>")
195     }
196 }
197
198 impl ConfigType for FileLines {
199     fn doc_hint() -> String {
200         String::from("<json>")
201     }
202 }
203
204 pub struct ConfigHelpItem {
205     option_name: &'static str,
206     doc_string: &'static str,
207     variant_names: String,
208     default: &'static str,
209 }
210
211 impl ConfigHelpItem {
212     pub fn option_name(&self) -> &'static str {
213         self.option_name
214     }
215
216     pub fn doc_string(&self) -> &'static str {
217         self.doc_string
218     }
219
220     pub fn variant_names(&self) -> &String {
221         &self.variant_names
222     }
223
224     pub fn default(&self) -> &'static str {
225         self.default
226     }
227 }
228
229 macro_rules! create_config {
230     ($($i:ident: $ty:ty, $def:expr, $( $dstring:expr ),+ );+ $(;)*) => (
231         #[derive(RustcDecodable, Clone)]
232         pub struct Config {
233             $(pub $i: $ty),+
234         }
235
236         // Just like the Config struct but with each property wrapped
237         // as Option<T>. This is used to parse a rustfmt.toml that doesn't
238         // specity all properties of `Config`.
239         // We first parse into `ParsedConfig`, then create a default `Config`
240         // and overwrite the properties with corresponding values from `ParsedConfig`
241         #[derive(RustcDecodable, Clone)]
242         pub struct ParsedConfig {
243             $(pub $i: Option<$ty>),+
244         }
245
246         impl Config {
247
248             fn fill_from_parsed_config(mut self, parsed: ParsedConfig) -> Config {
249             $(
250                 if let Some(val) = parsed.$i {
251                     self.$i = val;
252                 }
253             )+
254                 self
255             }
256
257             pub fn from_toml(toml: &str) -> Config {
258                 let parsed = toml.parse().expect("Could not parse TOML");
259                 let parsed_config:ParsedConfig = match toml::decode(parsed) {
260                     Some(decoded) => decoded,
261                     None => {
262                         msg!("Decoding config file failed. Config:\n{}", toml);
263                         let parsed: toml::Value = toml.parse().expect("Could not parse TOML");
264                         msg!("\n\nParsed:\n{:?}", parsed);
265                         panic!();
266                     }
267                 };
268                 Config::default().fill_from_parsed_config(parsed_config)
269             }
270
271             pub fn override_value(&mut self, key: &str, val: &str) {
272                 match key {
273                     $(
274                         stringify!($i) => {
275                             self.$i = val.parse::<$ty>()
276                                 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
277                                                  stringify!($i),
278                                                  val,
279                                                  stringify!($ty)));
280                         }
281                     )+
282                     _ => panic!("Unknown config key in override: {}", key)
283                 }
284             }
285
286             pub fn print_docs() {
287                 use std::cmp;
288                 let max = 0;
289                 $( let max = cmp::max(max, stringify!($i).len()+1); )+
290                 let mut space_str = String::with_capacity(max);
291                 for _ in 0..max {
292                     space_str.push(' ');
293                 }
294                 println!("Configuration Options:");
295                 $(
296                     let name_raw = stringify!($i);
297                     let mut name_out = String::with_capacity(max);
298                     for _ in name_raw.len()..max-1 {
299                         name_out.push(' ')
300                     }
301                     name_out.push_str(name_raw);
302                     name_out.push(' ');
303                     println!("{}{} Default: {:?}",
304                              name_out,
305                              <$ty>::doc_hint(),
306                              $def);
307                     $(
308                         println!("{}{}", space_str, $dstring);
309                     )+
310                     println!("");
311                 )+
312             }
313         }
314
315         // Template for the default configuration
316         impl Default for Config {
317             fn default() -> Config {
318                 Config {
319                     $(
320                         $i: $def,
321                     )+
322                 }
323             }
324         }
325     )
326 }
327
328 create_config! {
329     verbose: bool, false, "Use verbose output";
330     disable_all_formatting: bool, false, "Don't reformat anything";
331     skip_children: bool, false, "Don't reformat out of line modules";
332     file_lines: FileLines, FileLines::all(),
333         "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
334          via the --file-lines option";
335     max_width: usize, 100, "Maximum width of each line";
336     ideal_width: usize, 80, "Ideal width of each line";
337     error_on_line_overflow: bool, true, "Error if unable to get all lines within max_width";
338     tab_spaces: usize, 4, "Number of spaces per tab";
339     fn_call_width: usize, 60,
340         "Maximum width of the args of a function call before falling back to vertical formatting";
341     struct_lit_width: usize, 16,
342         "Maximum width in the body of a struct lit before falling back to vertical formatting";
343     struct_variant_width: usize, 35,
344         "Maximum width in the body of a struct variant before falling back to vertical formatting";
345     force_explicit_abi: bool, true, "Always print the abi for extern items";
346     newline_style: NewlineStyle, NewlineStyle::Unix, "Unix or Windows line endings";
347     fn_brace_style: BraceStyle, BraceStyle::SameLineWhere, "Brace style for functions";
348     item_brace_style: BraceStyle, BraceStyle::SameLineWhere, "Brace style for structs and enums";
349     control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine,
350         "Brace style for control flow constructs";
351     impl_empty_single_line: bool, true, "Put empty-body implementations on a single line";
352     trailing_comma: SeparatorTactic, SeparatorTactic::Vertical,
353         "How to handle trailing commas for lists";
354     fn_empty_single_line: bool, true, "Put empty-body functions on a single line";
355     fn_single_line: bool, false, "Put single-expression functions on a single line";
356     fn_return_indent: ReturnIndent, ReturnIndent::WithArgs,
357         "Location of return type in function declaration";
358     fn_args_paren_newline: bool, true, "If function argument parenthesis goes on a newline";
359     fn_args_density: Density, Density::Tall, "Argument density in functions";
360     fn_args_layout: FnArgLayoutStyle, FnArgLayoutStyle::Visual, "Layout of function arguments";
361     fn_arg_indent: BlockIndentStyle, BlockIndentStyle::Visual, "Indent on function arguments";
362     type_punctuation_density: TypeDensity, TypeDensity::Wide,
363         "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
364     // Should we at least try to put the where clause on the same line as the rest of the
365     // function decl?
366     where_density: Density, Density::CompressedIfEmpty, "Density of a where clause";
367     // Visual will be treated like Tabbed
368     where_indent: BlockIndentStyle, BlockIndentStyle::Tabbed, "Indentation of a where clause";
369     where_layout: ListTactic, ListTactic::Vertical, "Element layout inside a where clause";
370     where_pred_indent: BlockIndentStyle, BlockIndentStyle::Visual,
371         "Indentation style of a where predicate";
372     generics_indent: BlockIndentStyle, BlockIndentStyle::Visual, "Indentation of generics";
373     struct_lit_style: StructLitStyle, StructLitStyle::Block, "Style of struct definition";
374     struct_lit_multiline_style: MultilineStyle, MultilineStyle::PreferSingle,
375         "Multiline style on literal structs";
376     report_todo: ReportTactic, ReportTactic::Never,
377         "Report all, none or unnumbered occurrences of TODO in source file comments";
378     report_fixme: ReportTactic, ReportTactic::Never,
379         "Report all, none or unnumbered occurrences of FIXME in source file comments";
380     chain_indent: BlockIndentStyle, BlockIndentStyle::Tabbed, "Indentation of chain";
381     reorder_imports: bool, false, "Reorder import statements alphabetically";
382     reorder_imported_names: bool, false,
383         "Reorder lists of names in import statements alphabetically";
384     single_line_if_else_max_width: usize, 50, "Maximum line length for single line if-else \
385                                                 expressions. A value of zero means always break \
386                                                 if-else expressions.";
387     format_strings: bool, false, "Format string literals where necessary";
388     force_format_strings: bool, false, "Always format string literals";
389     take_source_hints: bool, true, "Retain some formatting characteristics from the source code";
390     hard_tabs: bool, false, "Use tab characters for indentation, spaces for alignment";
391     wrap_comments: bool, false, "Break comments to fit on the line";
392     normalize_comments: bool, false, "Convert /* */ comments to // comments where possible";
393     wrap_match_arms: bool, true, "Wrap multiline match arms in blocks";
394     match_block_trailing_comma: bool, false,
395         "Put a trailing comma after a block based match arm (non-block arms are not affected)";
396     closure_block_indent_threshold: isize, 5, "How many lines a closure must have before it is \
397                                                block indented. -1 means never use block indent.";
398     space_before_type_annotation: bool, false,
399         "Leave a space before the colon in a type annotation";
400     space_after_type_annotation_colon: bool, true,
401         "Leave a space after the colon in a type annotation";
402     space_before_bound: bool, false, "Leave a space before the colon in a trait or lifetime bound";
403     space_after_bound_colon: bool, true,
404         "Leave a space after the colon in a trait or lifetime bound";
405     spaces_around_ranges: bool, false, "Put spaces around the  .. and ... range operators";
406     spaces_within_angle_brackets: bool, false, "Put spaces within non-empty generic arguments";
407     spaces_within_square_brackets: bool, false, "Put spaces within non-empty square brackets";
408     spaces_within_parens: bool, false, "Put spaces within non-empty parentheses";
409     use_try_shorthand: bool, false, "Replace uses of the try! macro by the ? shorthand";
410     write_mode: WriteMode, WriteMode::Replace,
411         "What Write Mode to use when none is supplied: Replace, Overwrite, Display, Diff, Coverage";
412     condense_wildcard_suffices: bool, false, "Replace strings of _ wildcards by a single .. in \
413                                               tuple patterns"
414 }