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.
13 use file_lines::FileLines;
14 use lists::{SeparatorTactic, ListTactic};
17 macro_rules! configuration_option_enum{
18 ($e:ident: $( $x:ident ),+ $(,)*) => {
19 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
24 impl_enum_decodable!($e, $( $x ),+);
28 configuration_option_enum! { Style:
29 Rfc, // Follow the style RFCs style.
30 Default, // Follow the traditional Rustfmt style.
33 configuration_option_enum! { NewlineStyle:
36 Native, // \r\n in Windows, \n on other platforms
39 configuration_option_enum! { BraceStyle:
42 // Prefer same line except where there is a where clause, in which case force
43 // the brace to the next line.
47 configuration_option_enum! { ControlBraceStyle:
48 // K&R style, Rust community default
56 // How to indent a function's return type.
57 configuration_option_enum! { ReturnIndent:
58 // Aligned with the arguments
60 // Aligned with the where clause
64 configuration_option_enum! { IndentStyle:
65 // First line on the same line as the opening brace, all lines aligned with
68 // First line is on a new line and all lines align with block indent.
72 configuration_option_enum! { Density:
73 // Fit as much on one line as possible.
77 // Try to compress if the body is empty.
79 // Place every item on a separate line.
83 configuration_option_enum! { TypeDensity:
84 // No spaces around "=" and "+"
86 // Spaces around " = " and " + "
92 pub fn to_list_tactic(self) -> ListTactic {
94 Density::Compressed => ListTactic::Mixed,
96 Density::CompressedIfEmpty => ListTactic::HorizontalVertical,
97 Density::Vertical => ListTactic::Vertical,
102 configuration_option_enum! { LicensePolicy:
103 // Do not place license text at top of files
105 // Use the text in "license" field as the license
107 // Use a text file as the license text
111 configuration_option_enum! { MultilineStyle:
112 // Use horizontal layout if it fits in one line, fall back to vertical
114 // Use vertical layout
118 impl MultilineStyle {
119 pub fn to_list_tactic(self) -> ListTactic {
121 MultilineStyle::PreferSingle => ListTactic::HorizontalVertical,
122 MultilineStyle::ForceMulti => ListTactic::Vertical,
127 configuration_option_enum! { ReportTactic:
133 configuration_option_enum! { WriteMode:
134 // Backs the original file up and overwrites the original.
136 // Overwrites original file without backup.
138 // Writes the output to stdout.
140 // Writes the diff to stdout.
142 // Displays how much of the input file was processed
146 // Outputs a checkstyle XML file.
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;
157 impl ConfigType for bool {
158 fn doc_hint() -> String {
159 String::from("<boolean>")
163 impl ConfigType for usize {
164 fn doc_hint() -> String {
165 String::from("<unsigned integer>")
169 impl ConfigType for isize {
170 fn doc_hint() -> String {
171 String::from("<signed integer>")
175 impl ConfigType for String {
176 fn doc_hint() -> String {
177 String::from("<string>")
181 impl ConfigType for FileLines {
182 fn doc_hint() -> String {
183 String::from("<json>")
187 pub struct ConfigHelpItem {
188 option_name: &'static str,
189 doc_string: &'static str,
190 variant_names: String,
191 default: &'static str,
194 impl ConfigHelpItem {
195 pub fn option_name(&self) -> &'static str {
199 pub fn doc_string(&self) -> &'static str {
203 pub fn variant_names(&self) -> &String {
207 pub fn default(&self) -> &'static str {
212 macro_rules! create_config {
213 ($($i:ident: $ty:ty, $def:expr, $( $dstring:expr ),+ );+ $(;)*) => (
214 #[derive(RustcDecodable, Clone)]
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>),+
231 fn fill_from_parsed_config(mut self, parsed: ParsedConfig) -> Config {
233 if let Some(val) = parsed.$i {
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") {
245 stringify!($i) => (),
247 _ => msg!("Warning: Unused configuration option {}", key),
250 let parsed_config:ParsedConfig = match toml::decode(parsed) {
251 Some(decoded) => decoded,
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);
259 Config::default().fill_from_parsed_config(parsed_config)
262 pub fn override_value(&mut self, key: &str, val: &str) {
266 self.$i = val.parse::<$ty>()
267 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
273 _ => panic!("Unknown config key in override: {}", key)
277 pub fn print_docs() {
280 $( let max = cmp::max(max, stringify!($i).len()+1); )+
281 let mut space_str = String::with_capacity(max);
285 println!("Configuration Options:");
287 let name_raw = stringify!($i);
288 let mut name_out = String::with_capacity(max);
289 for _ in name_raw.len()..max-1 {
292 name_out.push_str(name_raw);
294 println!("{}{} Default: {:?}",
299 println!("{}{}", space_str, $dstring);
306 // Template for the default configuration
307 impl Default for Config {
308 fn default() -> 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
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 \