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.
17 use std::io::{Error, ErrorKind, Read};
18 use std::path::{Path, PathBuf};
20 use file_lines::FileLines;
21 use lists::{SeparatorTactic, ListTactic};
23 macro_rules! configuration_option_enum{
24 ($e:ident: $( $x:ident ),+ $(,)*) => {
25 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
30 impl_enum_serialize_and_deserialize!($e, $( $x ),+);
34 configuration_option_enum! { Style:
35 Rfc, // Follow the style RFCs style.
36 Legacy, // Follow the traditional Rustfmt style.
39 configuration_option_enum! { NewlineStyle:
42 Native, // \r\n in Windows, \n on other platforms
45 configuration_option_enum! { BraceStyle:
48 // Prefer same line except where there is a where clause, in which case force
49 // the brace to the next line.
53 configuration_option_enum! { ControlBraceStyle:
54 // K&R style, Rust community default
62 // How to indent a function's return type.
63 configuration_option_enum! { ReturnIndent:
64 // Aligned with the arguments
66 // Aligned with the where clause
70 configuration_option_enum! { IndentStyle:
71 // First line on the same line as the opening brace, all lines aligned with
74 // First line is on a new line and all lines align with block indent.
78 configuration_option_enum! { Density:
79 // Fit as much on one line as possible.
83 // Try to compress if the body is empty.
85 // Place every item on a separate line.
89 configuration_option_enum! { TypeDensity:
90 // No spaces around "=" and "+"
92 // Spaces around " = " and " + "
98 pub fn to_list_tactic(self) -> ListTactic {
100 Density::Compressed => ListTactic::Mixed,
102 Density::CompressedIfEmpty => ListTactic::HorizontalVertical,
103 Density::Vertical => ListTactic::Vertical,
108 configuration_option_enum! { LicensePolicy:
109 // Do not place license text at top of files
111 // Use the text in "license" field as the license
113 // Use a text file as the license text
117 configuration_option_enum! { MultilineStyle:
118 // Use horizontal layout if it fits in one line, fall back to vertical
120 // Use vertical layout
124 impl MultilineStyle {
125 pub fn to_list_tactic(self) -> ListTactic {
127 MultilineStyle::PreferSingle => ListTactic::HorizontalVertical,
128 MultilineStyle::ForceMulti => ListTactic::Vertical,
133 configuration_option_enum! { ReportTactic:
139 configuration_option_enum! { WriteMode:
140 // Backs the original file up and overwrites the original.
142 // Overwrites original file without backup.
144 // Writes the output to stdout.
146 // Writes the diff to stdout.
148 // Displays how much of the input file was processed
152 // Outputs a checkstyle XML file.
156 /// Trait for types that can be used in `Config`.
157 pub trait ConfigType: Sized {
158 /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a
159 /// pipe-separated list of variants; for other types it returns "<type>".
160 fn doc_hint() -> String;
163 impl ConfigType for bool {
164 fn doc_hint() -> String {
165 String::from("<boolean>")
169 impl ConfigType for usize {
170 fn doc_hint() -> String {
171 String::from("<unsigned integer>")
175 impl ConfigType for isize {
176 fn doc_hint() -> String {
177 String::from("<signed integer>")
181 impl ConfigType for String {
182 fn doc_hint() -> String {
183 String::from("<string>")
187 impl ConfigType for FileLines {
188 fn doc_hint() -> String {
189 String::from("<json>")
193 pub struct ConfigHelpItem {
194 option_name: &'static str,
195 doc_string: &'static str,
196 variant_names: String,
197 default: &'static str,
200 impl ConfigHelpItem {
201 pub fn option_name(&self) -> &'static str {
205 pub fn doc_string(&self) -> &'static str {
209 pub fn variant_names(&self) -> &String {
213 pub fn default(&self) -> &'static str {
218 macro_rules! create_config {
219 ($($i:ident: $ty:ty, $def:expr, $( $dstring:expr ),+ );+ $(;)*) => (
222 // For each config item, we store a bool indicating whether it has
223 // been accessed and the value.
224 $($i: (Cell<bool>, $ty)),+
227 // Just like the Config struct but with each property wrapped
228 // as Option<T>. This is used to parse a rustfmt.toml that doesn't
229 // specity all properties of `Config`.
230 // We first parse into `PartialConfig`, then create a default `Config`
231 // and overwrite the properties with corresponding values from `PartialConfig`.
232 #[derive(Deserialize, Serialize, Clone)]
233 pub struct PartialConfig {
234 $(pub $i: Option<$ty>),+
238 pub fn to_toml(&self) -> Result<String, String> {
239 // file_lines can't be specified in TOML
240 let mut cloned = self.clone();
241 cloned.file_lines = None;
243 toml::to_string(&cloned)
244 .map_err(|e| format!("Could not output config: {}", e.to_string()))
248 // Macro hygiene won't allow us to make `set_$i()` methods on Config
249 // for each item, so this struct is used to give the API to set values:
250 // `config.get().option(false)`. It's pretty ugly. Consider replacing
251 // with `config.set_option(false)` if we ever get a stable/usable
252 // `concat_idents!()`.
253 pub struct ConfigSetter<'a>(&'a mut Config);
255 impl<'a> ConfigSetter<'a> {
257 pub fn $i(&mut self, value: $ty) {
258 (self.0).$i.1 = value;
266 pub fn $i(&self) -> $ty {
272 pub fn set<'a>(&'a mut self) -> ConfigSetter<'a> {
276 fn fill_from_parsed_config(mut self, parsed: PartialConfig) -> Config {
278 if let Some(val) = parsed.$i {
285 pub fn from_toml(toml: &str) -> Result<Config, String> {
286 let parsed: toml::Value =
287 toml.parse().map_err(|e| format!("Could not parse TOML: {}", e))?;
288 let mut err: String = String::new();
292 .ok_or(String::from("Parsed config was not table"))?;
293 for (key, _) in table {
296 stringify!($i) => (),
300 &format!("Warning: Unknown configuration option `{}`\n",
307 match parsed.try_into() {
309 Ok(Config::default().fill_from_parsed_config(parsed_config)),
311 err.push_str("Error: Decoding config file failed:\n");
312 err.push_str(format!("{}\n", e).as_str());
313 err.push_str("Please check your config file.\n");
319 pub fn used_options(&self) -> PartialConfig {
322 $i: if self.$i.0.get() {
323 Some(self.$i.1.clone())
331 pub fn all_options(&self) -> PartialConfig {
334 $i: Some(self.$i.1.clone()),
339 pub fn override_value(&mut self, key: &str, val: &str)
344 self.$i.1 = val.parse::<$ty>()
345 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
351 _ => panic!("Unknown config key in override: {}", key)
355 /// Construct a `Config` from the toml file specified at `file_path`.
357 /// This method only looks at the provided path, for a method that
358 /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
360 /// Return a `Config` if the config could be read and parsed from
361 /// the file, Error otherwise.
362 pub fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
363 let mut file = File::open(&file_path)?;
364 let mut toml = String::new();
365 file.read_to_string(&mut toml)?;
366 Config::from_toml(&toml).map_err(|err| Error::new(ErrorKind::InvalidData, err))
369 /// Resolve the config for input in `dir`.
371 /// Searches for `rustfmt.toml` beginning with `dir`, and
372 /// recursively checking parents of `dir` if no config file is found.
373 /// If no config file exists in `dir` or in any parent, a
374 /// default `Config` will be returned (and the returned path will be empty).
376 /// Returns the `Config` to use, and the path of the project file if there was
378 pub fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
380 /// Try to find a project file in the given directory and its parents.
381 /// Returns the path of a the nearest project file if one exists,
382 /// or `None` if no project file was found.
383 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
384 let mut current = if dir.is_relative() {
385 env::current_dir()?.join(dir)
390 current = fs::canonicalize(current)?;
393 match get_toml_path(¤t) {
394 Ok(Some(path)) => return Ok(Some(path)),
395 Err(e) => return Err(e),
399 // If the current directory has no parent, we're done searching.
406 match resolve_project_file(dir)? {
407 None => Ok((Config::default(), None)),
408 Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
413 pub fn print_docs() {
416 $( let max = cmp::max(max, stringify!($i).len()+1); )+
417 let mut space_str = String::with_capacity(max);
421 println!("Configuration Options:");
423 let name_raw = stringify!($i);
424 let mut name_out = String::with_capacity(max);
425 for _ in name_raw.len()..max-1 {
428 name_out.push_str(name_raw);
430 println!("{}{} Default: {:?}",
435 println!("{}{}", space_str, $dstring);
442 // Template for the default configuration
443 impl Default for Config {
444 fn default() -> Config {
447 $i: (Cell::new(false), $def),
455 /// Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
457 /// Return the path if a config file exists, empty if no file exists, and Error for IO errors
458 pub fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
459 const CONFIG_FILE_NAMES: [&'static str; 2] = [".rustfmt.toml", "rustfmt.toml"];
460 for config_file_name in &CONFIG_FILE_NAMES {
461 let config_file = dir.join(config_file_name);
462 match fs::metadata(&config_file) {
463 // Only return if it's a file to handle the unlikely situation of a directory named
465 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
466 // Return the error if it's something other than `NotFound`; otherwise we didn't
467 // find the project file yet, and continue searching.
469 if e.kind() != ErrorKind::NotFound {
482 verbose: bool, false, "Use verbose output";
483 disable_all_formatting: bool, false, "Don't reformat anything";
484 skip_children: bool, false, "Don't reformat out of line modules";
485 file_lines: FileLines, FileLines::all(),
486 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
487 via the --file-lines option";
488 max_width: usize, 100, "Maximum width of each line";
489 error_on_line_overflow: bool, true, "Error if unable to get all lines within max_width";
490 tab_spaces: usize, 4, "Number of spaces per tab";
491 fn_call_width: usize, 60,
492 "Maximum width of the args of a function call before falling back to vertical formatting";
493 struct_lit_width: usize, 18,
494 "Maximum width in the body of a struct lit before falling back to vertical formatting";
495 struct_variant_width: usize, 35,
496 "Maximum width in the body of a struct variant before falling back to vertical formatting";
497 force_explicit_abi: bool, true, "Always print the abi for extern items";
498 newline_style: NewlineStyle, NewlineStyle::Unix, "Unix or Windows line endings";
499 fn_brace_style: BraceStyle, BraceStyle::SameLineWhere, "Brace style for functions";
500 item_brace_style: BraceStyle, BraceStyle::SameLineWhere, "Brace style for structs and enums";
501 control_style: Style, Style::Legacy, "Indent style for control flow statements";
502 control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine,
503 "Brace style for control flow constructs";
504 impl_empty_single_line: bool, true, "Put empty-body implementations on a single line";
505 trailing_comma: SeparatorTactic, SeparatorTactic::Vertical,
506 "How to handle trailing commas for lists";
507 fn_empty_single_line: bool, true, "Put empty-body functions on a single line";
508 fn_single_line: bool, false, "Put single-expression functions on a single line";
509 fn_return_indent: ReturnIndent, ReturnIndent::WithArgs,
510 "Location of return type in function declaration";
511 fn_args_paren_newline: bool, true, "If function argument parenthesis goes on a newline";
512 fn_args_density: Density, Density::Tall, "Argument density in functions";
513 fn_args_layout: IndentStyle, IndentStyle::Visual,
514 "Layout of function arguments and tuple structs";
515 array_layout: IndentStyle, IndentStyle::Visual, "Indent on arrays";
516 array_width: usize, 60,
517 "Maximum width of an array literal before falling back to vertical formatting";
518 type_punctuation_density: TypeDensity, TypeDensity::Wide,
519 "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
520 where_style: Style, Style::Legacy, "Overall strategy for where clauses";
522 // 1. Should we at least try to put the where clause on the same line as the rest of the
524 // 2. Currently options `Tall` and `Vertical` produce the same output.
525 where_density: Density, Density::CompressedIfEmpty, "Density of a where clause";
526 where_layout: ListTactic, ListTactic::Vertical, "Element layout inside a where clause";
527 where_pred_indent: IndentStyle, IndentStyle::Visual,
528 "Indentation style of a where predicate";
529 generics_indent: IndentStyle, IndentStyle::Visual, "Indentation of generics";
530 struct_lit_style: IndentStyle, IndentStyle::Block, "Style of struct definition";
531 struct_lit_multiline_style: MultilineStyle, MultilineStyle::PreferSingle,
532 "Multiline style on literal structs";
533 fn_call_style: IndentStyle, IndentStyle::Visual, "Indentation for function calls, etc.";
534 report_todo: ReportTactic, ReportTactic::Never,
535 "Report all, none or unnumbered occurrences of TODO in source file comments";
536 report_fixme: ReportTactic, ReportTactic::Never,
537 "Report all, none or unnumbered occurrences of FIXME in source file comments";
538 chain_indent: IndentStyle, IndentStyle::Block, "Indentation of chain";
539 chain_one_line_max: usize, 60, "Maximum length of a chain to fit on a single line";
540 chain_split_single_child: bool, false, "Split a chain with a single child if its length \
541 exceeds `chain_one_line_max`";
542 reorder_imports: bool, false, "Reorder import statements alphabetically";
543 reorder_imports_in_group: bool, false, "Reorder import statements in group";
544 reorder_imported_names: bool, false,
545 "Reorder lists of names in import statements alphabetically";
546 single_line_if_else_max_width: usize, 50, "Maximum line length for single line if-else \
547 expressions. A value of zero means always break \
548 if-else expressions.";
549 format_strings: bool, false, "Format string literals where necessary";
550 force_format_strings: bool, false, "Always format string literals";
551 take_source_hints: bool, false, "Retain some formatting characteristics from the source code";
552 hard_tabs: bool, false, "Use tab characters for indentation, spaces for alignment";
553 wrap_comments: bool, false, "Break comments to fit on the line";
554 comment_width: usize, 80, "Maximum length of comments. No effect unless wrap_comments = true";
555 normalize_comments: bool, false, "Convert /* */ comments to // comments where possible";
556 wrap_match_arms: bool, true, "Wrap multiline match arms in blocks";
557 match_block_trailing_comma: bool, false,
558 "Put a trailing comma after a block based match arm (non-block arms are not affected)";
559 indent_match_arms: bool, true, "Indent match arms instead of keeping them at the same \
560 indentation level as the match keyword";
561 closure_block_indent_threshold: isize, 7, "How many lines a closure must have before it is \
562 block indented. -1 means never use block indent.";
563 space_before_type_annotation: bool, false,
564 "Leave a space before the colon in a type annotation";
565 space_after_type_annotation_colon: bool, true,
566 "Leave a space after the colon in a type annotation";
567 space_before_struct_lit_field_colon: bool, false,
568 "Leave a space before the colon in a struct literal field";
569 space_after_struct_lit_field_colon: bool, true,
570 "Leave a space after the colon in a struct literal field";
571 space_before_bound: bool, false, "Leave a space before the colon in a trait or lifetime bound";
572 space_after_bound_colon: bool, true,
573 "Leave a space after the colon in a trait or lifetime bound";
574 spaces_around_ranges: bool, false, "Put spaces around the .. and ... range operators";
575 spaces_within_angle_brackets: bool, false, "Put spaces within non-empty generic arguments";
576 spaces_within_square_brackets: bool, false, "Put spaces within non-empty square brackets";
577 spaces_within_parens: bool, false, "Put spaces within non-empty parentheses";
578 use_try_shorthand: bool, false, "Replace uses of the try! macro by the ? shorthand";
579 write_mode: WriteMode, WriteMode::Replace,
580 "What Write Mode to use when none is supplied: Replace, Overwrite, Display, Diff, Coverage";
581 condense_wildcard_suffixes: bool, false, "Replace strings of _ wildcards by a single .. in \
583 combine_control_expr: bool, false, "Combine control expressions with funciton calls."
591 fn test_config_set() {
592 let mut config = Config::default();
593 config.set().verbose(false);
594 assert_eq!(config.verbose(), false);
595 config.set().verbose(true);
596 assert_eq!(config.verbose(), true);
600 fn test_config_used_to_toml() {
601 let config = Config::default();
603 let verbose = config.verbose();
604 let skip_children = config.skip_children();
606 let used_options = config.used_options();
607 let toml = used_options.to_toml().unwrap();
609 format!("verbose = {}\nskip_children = {}\n", verbose, skip_children));