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! { NewlineStyle:
31 Native, // \r\n in Windows, \n on other platforms
34 configuration_option_enum! { BraceStyle:
37 // Prefer same line except where there is a where clause, in which case force
38 // the brace to the next line.
42 configuration_option_enum! { ControlBraceStyle:
43 // K&R style, Rust community default
51 // How to indent a function's return type.
52 configuration_option_enum! { ReturnIndent:
53 // Aligned with the arguments
55 // Aligned with the where clause
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
64 // First line is on a new line and all lines align with block indent.
66 // FIXME Maybe we should also have an option to align types.
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
74 // Put args on one line if they fit, or start a new line with block indent.
76 // First line is on a new line and all lines align with block indent.
80 configuration_option_enum! { BlockIndentStyle:
81 // Same level as parent.
83 // One level deeper than parent.
85 // Aligned with block open.
89 configuration_option_enum! { Density:
90 // Fit as much on one line as possible.
94 // Try to compress if the body is empty.
96 // Place every item on a separate line.
100 configuration_option_enum! { TypeDensity:
101 // No spaces around "=" and "+"
103 // Spaces around " = " and " + "
109 pub fn to_list_tactic(self) -> ListTactic {
111 Density::Compressed => ListTactic::Mixed,
113 Density::CompressedIfEmpty => ListTactic::HorizontalVertical,
114 Density::Vertical => ListTactic::Vertical,
119 configuration_option_enum! { LicensePolicy:
120 // Do not place license text at top of files
122 // Use the text in "license" field as the license
124 // Use a text file as the license text
128 configuration_option_enum! { MultilineStyle:
129 // Use horizontal layout if it fits in one line, fall back to vertical
131 // Use vertical layout
135 impl MultilineStyle {
136 pub fn to_list_tactic(self) -> ListTactic {
138 MultilineStyle::PreferSingle => ListTactic::HorizontalVertical,
139 MultilineStyle::ForceMulti => ListTactic::Vertical,
144 configuration_option_enum! { ReportTactic:
150 configuration_option_enum! { WriteMode:
151 // Backs the original file up and overwrites the original.
153 // Overwrites original file without backup.
155 // Writes the output to stdout.
157 // Writes the diff to stdout.
159 // Displays how much of the input file was processed
163 // Outputs a checkstyle XML file.
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;
174 impl ConfigType for bool {
175 fn doc_hint() -> String {
176 String::from("<boolean>")
180 impl ConfigType for usize {
181 fn doc_hint() -> String {
182 String::from("<unsigned integer>")
186 impl ConfigType for isize {
187 fn doc_hint() -> String {
188 String::from("<signed integer>")
192 impl ConfigType for String {
193 fn doc_hint() -> String {
194 String::from("<string>")
198 impl ConfigType for FileLines {
199 fn doc_hint() -> String {
200 String::from("<json>")
204 pub struct ConfigHelpItem {
205 option_name: &'static str,
206 doc_string: &'static str,
207 variant_names: String,
208 default: &'static str,
211 impl ConfigHelpItem {
212 pub fn option_name(&self) -> &'static str {
216 pub fn doc_string(&self) -> &'static str {
220 pub fn variant_names(&self) -> &String {
224 pub fn default(&self) -> &'static str {
229 macro_rules! create_config {
230 ($($i:ident: $ty:ty, $def:expr, $( $dstring:expr ),+ );+ $(;)*) => (
231 #[derive(RustcDecodable, Clone)]
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>),+
248 fn fill_from_parsed_config(mut self, parsed: ParsedConfig) -> Config {
250 if let Some(val) = parsed.$i {
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,
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);
268 Config::default().fill_from_parsed_config(parsed_config)
271 pub fn override_value(&mut self, key: &str, val: &str) {
275 self.$i = val.parse::<$ty>()
276 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
282 _ => panic!("Unknown config key in override: {}", key)
286 pub fn print_docs() {
289 $( let max = cmp::max(max, stringify!($i).len()+1); )+
290 let mut space_str = String::with_capacity(max);
294 println!("Configuration Options:");
296 let name_raw = stringify!($i);
297 let mut name_out = String::with_capacity(max);
298 for _ in name_raw.len()..max-1 {
301 name_out.push_str(name_raw);
303 println!("{}{} Default: {:?}",
308 println!("{}{}", space_str, $dstring);
315 // Template for the default configuration
316 impl Default for Config {
317 fn default() -> 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
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 \