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.
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.
15 use file_lines::FileLines;
16 use lists::{SeparatorTactic, ListTactic};
18 macro_rules! configuration_option_enum{
19 ($e:ident: $( $x:ident ),+ $(,)*) => {
20 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
25 impl_enum_serialize_and_deserialize!($e, $( $x ),+);
29 configuration_option_enum! { Style:
30 Rfc, // Follow the style RFCs style.
31 Default, // Follow the traditional Rustfmt style.
34 configuration_option_enum! { NewlineStyle:
37 Native, // \r\n in Windows, \n on other platforms
40 configuration_option_enum! { BraceStyle:
43 // Prefer same line except where there is a where clause, in which case force
44 // the brace to the next line.
48 configuration_option_enum! { ControlBraceStyle:
49 // K&R style, Rust community default
57 // How to indent a function's return type.
58 configuration_option_enum! { ReturnIndent:
59 // Aligned with the arguments
61 // Aligned with the where clause
65 configuration_option_enum! { IndentStyle:
66 // First line on the same line as the opening brace, all lines aligned with
69 // First line is on a new line and all lines align with block indent.
73 configuration_option_enum! { Density:
74 // Fit as much on one line as possible.
78 // Try to compress if the body is empty.
80 // Place every item on a separate line.
84 configuration_option_enum! { TypeDensity:
85 // No spaces around "=" and "+"
87 // Spaces around " = " and " + "
93 pub fn to_list_tactic(self) -> ListTactic {
95 Density::Compressed => ListTactic::Mixed,
97 Density::CompressedIfEmpty => ListTactic::HorizontalVertical,
98 Density::Vertical => ListTactic::Vertical,
103 configuration_option_enum! { LicensePolicy:
104 // Do not place license text at top of files
106 // Use the text in "license" field as the license
108 // Use a text file as the license text
112 configuration_option_enum! { MultilineStyle:
113 // Use horizontal layout if it fits in one line, fall back to vertical
115 // Use vertical layout
119 impl MultilineStyle {
120 pub fn to_list_tactic(self) -> ListTactic {
122 MultilineStyle::PreferSingle => ListTactic::HorizontalVertical,
123 MultilineStyle::ForceMulti => ListTactic::Vertical,
128 configuration_option_enum! { ReportTactic:
134 configuration_option_enum! { WriteMode:
135 // Backs the original file up and overwrites the original.
137 // Overwrites original file without backup.
139 // Writes the output to stdout.
141 // Writes the diff to stdout.
143 // Displays how much of the input file was processed
147 // Outputs a checkstyle XML file.
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;
158 impl ConfigType for bool {
159 fn doc_hint() -> String {
160 String::from("<boolean>")
164 impl ConfigType for usize {
165 fn doc_hint() -> String {
166 String::from("<unsigned integer>")
170 impl ConfigType for isize {
171 fn doc_hint() -> String {
172 String::from("<signed integer>")
176 impl ConfigType for String {
177 fn doc_hint() -> String {
178 String::from("<string>")
182 impl ConfigType for FileLines {
183 fn doc_hint() -> String {
184 String::from("<json>")
188 pub struct ConfigHelpItem {
189 option_name: &'static str,
190 doc_string: &'static str,
191 variant_names: String,
192 default: &'static str,
195 impl ConfigHelpItem {
196 pub fn option_name(&self) -> &'static str {
200 pub fn doc_string(&self) -> &'static str {
204 pub fn variant_names(&self) -> &String {
208 pub fn default(&self) -> &'static str {
213 macro_rules! create_config {
214 ($($i:ident: $ty:ty, $def:expr, $( $dstring:expr ),+ );+ $(;)*) => (
217 // For each config item, we store a bool indicating whether it has
218 // been accessed and the value.
219 $($i: (Cell<bool>, $ty)),+
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>),+
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;
238 toml::to_string(&cloned)
239 .map_err(|e| format!("Could not output config: {}", e.to_string()))
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);
250 impl<'a> ConfigSetter<'a> {
252 pub fn $i(&mut self, value: $ty) {
253 (self.0).$i.1 = value;
261 pub fn $i(&self) -> $ty {
267 pub fn set<'a>(&'a mut self) -> ConfigSetter<'a> {
271 fn fill_from_parsed_config(mut self, parsed: PartialConfig) -> Config {
273 if let Some(val) = parsed.$i {
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();
287 .ok_or(String::from("Parsed config was not table"))?;
288 for (key, _) in table {
291 stringify!($i) => (),
295 &format!("Warning: Unknown configuration option `{}`\n",
302 match parsed.try_into() {
304 Ok(Config::default().fill_from_parsed_config(parsed_config)),
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");
314 pub fn used_options(&self) -> PartialConfig {
317 $i: if self.$i.0.get() {
318 Some(self.$i.1.clone())
326 pub fn all_options(&self) -> PartialConfig {
329 $i: Some(self.$i.1.clone()),
334 pub fn override_value(&mut self, key: &str, val: &str)
339 self.$i.1 = val.parse::<$ty>()
340 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
346 _ => panic!("Unknown config key in override: {}", key)
350 pub fn print_docs() {
353 $( let max = cmp::max(max, stringify!($i).len()+1); )+
354 let mut space_str = String::with_capacity(max);
358 println!("Configuration Options:");
360 let name_raw = stringify!($i);
361 let mut name_out = String::with_capacity(max);
362 for _ in name_raw.len()..max-1 {
365 name_out.push_str(name_raw);
367 println!("{}{} Default: {:?}",
372 println!("{}{}", space_str, $dstring);
379 // Template for the default configuration
380 impl Default for Config {
381 fn default() -> Config {
384 $i: (Cell::new(false), $def),
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";
433 // 1. Should we at least try to put the where clause on the same line as the rest of the
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 \
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);
504 fn test_config_used_to_toml() {
505 let config = Config::default();
507 let verbose = config.verbose();
508 let skip_children = config.skip_children();
510 let used_options = config.used_options();
511 let toml = used_options.to_toml().unwrap();
513 format!("verbose = {}\nskip_children = {}\n", verbose, skip_children));