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