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 struct PartialConfig {
229 $(pub $i: Option<$ty>),+
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);
239 impl<'a> ConfigSetter<'a> {
241 pub fn $i(&mut self, value: $ty) {
242 (self.0).$i.1 = value;
250 pub fn $i(&self) -> $ty {
256 pub fn set<'a>(&'a mut self) -> ConfigSetter<'a> {
260 fn fill_from_parsed_config(mut self, parsed: PartialConfig) -> Config {
262 if let Some(val) = parsed.$i {
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();
276 .ok_or(String::from("Parsed config was not table"))?;
277 for (key, _) in table {
280 stringify!($i) => (),
284 &format!("Warning: Unknown configuration option `{}`\n",
291 match parsed.try_into() {
293 Ok(Config::default().fill_from_parsed_config(parsed_config)),
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");
303 pub fn used_to_toml(&self) -> Result<String, String> {
304 let mut partial = PartialConfig {
306 $i: if self.$i.0.get() {
307 Some(self.$i.1.clone())
314 // file_lines is special and can't be specified in toml.
315 partial.file_lines = None;
317 toml::to_string(&partial)
318 .map_err(|e| format!("Could not output config: {}", e.to_string()))
321 pub fn to_toml(&self) -> Result<String, String> {
322 let mut partial = PartialConfig {
324 $i: Some(self.$i.1.clone()),
328 // file_lines is special and can't be specified in toml.
329 partial.file_lines = None;
331 toml::to_string(&partial)
332 .map_err(|e| format!("Could not output config: {}", e.to_string()))
335 pub fn override_value(&mut self, key: &str, val: &str)
340 self.$i.1 = val.parse::<$ty>()
341 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
347 _ => panic!("Unknown config key in override: {}", key)
351 pub fn print_docs() {
354 $( let max = cmp::max(max, stringify!($i).len()+1); )+
355 let mut space_str = String::with_capacity(max);
359 println!("Configuration Options:");
361 let name_raw = stringify!($i);
362 let mut name_out = String::with_capacity(max);
363 for _ in name_raw.len()..max-1 {
366 name_out.push_str(name_raw);
368 println!("{}{} Default: {:?}",
373 println!("{}{}", space_str, $dstring);
380 // Template for the default configuration
381 impl Default for Config {
382 fn default() -> Config {
385 $i: (Cell::new(false), $def),
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";
434 // 1. Should we at least try to put the where clause on the same line as the rest of the
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 \
495 fn test_config_tracking() {
496 let config = Config::default();
497 assert!(!config.verbose.0.get());
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());
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);