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.
16 use std::io::{Error, ErrorKind, Read};
17 use std::path::{Path, PathBuf};
19 use file_lines::FileLines;
20 use lists::{ListTactic, SeparatorPlace, SeparatorTactic};
24 macro_rules! is_nightly_channel {
26 env::var("CFG_RELEASE_CHANNEL")
27 .map(|c| c == "nightly")
32 macro_rules! configuration_option_enum{
33 ($e:ident: $( $x:ident ),+ $(,)*) => {
34 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
39 impl_enum_serialize_and_deserialize!($e, $( $x ),+);
43 configuration_option_enum! { NewlineStyle:
46 Native, // \r\n in Windows, \n on other platforms
49 configuration_option_enum! { BraceStyle:
52 // Prefer same line except where there is a where clause, in which case force
53 // the brace to the next line.
57 configuration_option_enum! { ControlBraceStyle:
58 // K&R style, Rust community default
66 // How to indent a function's return type.
67 configuration_option_enum! { ReturnIndent:
68 // Aligned with the arguments
70 // Aligned with the where clause
74 configuration_option_enum! { IndentStyle:
75 // First line on the same line as the opening brace, all lines aligned with
78 // First line is on a new line and all lines align with block indent.
82 configuration_option_enum! { Density:
83 // Fit as much on one line as possible.
87 // Try to compress if the body is empty.
89 // Place every item on a separate line.
93 configuration_option_enum! { TypeDensity:
94 // No spaces around "=" and "+"
96 // Spaces around " = " and " + "
102 pub fn to_list_tactic(self) -> ListTactic {
104 Density::Compressed => ListTactic::Mixed,
105 Density::Tall | Density::CompressedIfEmpty => ListTactic::HorizontalVertical,
106 Density::Vertical => ListTactic::Vertical,
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 configuration_option_enum! { Color:
151 // Always use color, whether it is a piped or terminal output
155 // Automatically use color, if supported by terminal
159 /// Trait for types that can be used in `Config`.
160 pub trait ConfigType: Sized {
161 /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a
162 /// pipe-separated list of variants; for other types it returns "<type>".
163 fn doc_hint() -> String;
166 impl ConfigType for bool {
167 fn doc_hint() -> String {
168 String::from("<boolean>")
172 impl ConfigType for usize {
173 fn doc_hint() -> String {
174 String::from("<unsigned integer>")
178 impl ConfigType for isize {
179 fn doc_hint() -> String {
180 String::from("<signed integer>")
184 impl ConfigType for String {
185 fn doc_hint() -> String {
186 String::from("<string>")
190 impl ConfigType for FileLines {
191 fn doc_hint() -> String {
192 String::from("<json>")
196 pub struct ConfigHelpItem {
197 option_name: &'static str,
198 doc_string: &'static str,
199 variant_names: String,
200 default: &'static str,
203 impl ConfigHelpItem {
204 pub fn option_name(&self) -> &'static str {
208 pub fn doc_string(&self) -> &'static str {
212 pub fn variant_names(&self) -> &String {
216 pub fn default(&self) -> &'static str {
221 macro_rules! create_config {
222 ($($i:ident: $ty:ty, $def:expr, $stb:expr, $( $dstring:expr ),+ );+ $(;)*) => (
225 // For each config item, we store a bool indicating whether it has
226 // been accessed and the value, and a bool whether the option was
227 // manually initialised, or taken from the default,
228 $($i: (Cell<bool>, bool, $ty, bool)),+
231 // Just like the Config struct but with each property wrapped
232 // as Option<T>. This is used to parse a rustfmt.toml that doesn't
233 // specify all properties of `Config`.
234 // We first parse into `PartialConfig`, then create a default `Config`
235 // and overwrite the properties with corresponding values from `PartialConfig`.
236 #[derive(Deserialize, Serialize, Clone)]
237 pub struct PartialConfig {
238 $(pub $i: Option<$ty>),+
242 pub fn to_toml(&self) -> Result<String, String> {
243 // file_lines can't be specified in TOML
244 let mut cloned = self.clone();
245 cloned.file_lines = None;
247 toml::to_string(&cloned)
248 .map_err(|e| format!("Could not output config: {}", e.to_string()))
252 // Macro hygiene won't allow us to make `set_$i()` methods on Config
253 // for each item, so this struct is used to give the API to set values:
254 // `config.get().option(false)`. It's pretty ugly. Consider replacing
255 // with `config.set_option(false)` if we ever get a stable/usable
256 // `concat_idents!()`.
257 pub struct ConfigSetter<'a>(&'a mut Config);
259 impl<'a> ConfigSetter<'a> {
261 pub fn $i(&mut self, value: $ty) {
262 (self.0).$i.2 = value;
267 // Query each option, returns true if the user set the option, false if
268 // a default was used.
269 pub struct ConfigWasSet<'a>(&'a Config);
271 impl<'a> ConfigWasSet<'a> {
273 pub fn $i(&self) -> bool {
280 pub fn version_meets_requirement(&self, error_summary: &mut Summary) -> bool {
281 if self.was_set().required_version() {
282 let version = env!("CARGO_PKG_VERSION");
283 let required_version = self.required_version();
284 if version != required_version {
286 "Error: rustfmt version ({}) doesn't match the required version ({})",
290 error_summary.add_formatting_error();
299 pub fn $i(&self) -> $ty {
305 pub fn set<'a>(&'a mut self) -> ConfigSetter<'a> {
309 pub fn was_set<'a>(&'a self) -> ConfigWasSet<'a> {
313 fn fill_from_parsed_config(mut self, parsed: PartialConfig) -> Config {
315 if let Some(val) = parsed.$i {
320 if is_nightly_channel!() {
324 println!("Warning: can't set some features as unstable \
325 features are only available in nightly channel.");
333 pub fn from_toml(toml: &str) -> Result<Config, String> {
334 let parsed: toml::Value =
335 toml.parse().map_err(|e| format!("Could not parse TOML: {}", e))?;
336 let mut err: String = String::new();
340 .ok_or(String::from("Parsed config was not table"))?;
341 for key in table.keys() {
344 stringify!($i) => (),
348 &format!("Warning: Unknown configuration option `{}`\n",
355 match parsed.try_into() {
357 Ok(Config::default().fill_from_parsed_config(parsed_config)),
359 err.push_str("Error: Decoding config file failed:\n");
360 err.push_str(format!("{}\n", e).as_str());
361 err.push_str("Please check your config file.\n");
367 pub fn used_options(&self) -> PartialConfig {
370 $i: if self.$i.0.get() {
371 Some(self.$i.2.clone())
379 pub fn all_options(&self) -> PartialConfig {
382 $i: Some(self.$i.2.clone()),
387 pub fn override_value(&mut self, key: &str, val: &str)
392 self.$i.2 = val.parse::<$ty>()
393 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
399 _ => panic!("Unknown config key in override: {}", key)
403 /// Construct a `Config` from the toml file specified at `file_path`.
405 /// This method only looks at the provided path, for a method that
406 /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
408 /// Return a `Config` if the config could be read and parsed from
409 /// the file, Error otherwise.
410 pub fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
411 let mut file = File::open(&file_path)?;
412 let mut toml = String::new();
413 file.read_to_string(&mut toml)?;
414 Config::from_toml(&toml).map_err(|err| Error::new(ErrorKind::InvalidData, err))
417 /// Resolve the config for input in `dir`.
419 /// Searches for `rustfmt.toml` beginning with `dir`, and
420 /// recursively checking parents of `dir` if no config file is found.
421 /// If no config file exists in `dir` or in any parent, a
422 /// default `Config` will be returned (and the returned path will be empty).
424 /// Returns the `Config` to use, and the path of the project file if there was
426 pub fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
428 /// Try to find a project file in the given directory and its parents.
429 /// Returns the path of a the nearest project file if one exists,
430 /// or `None` if no project file was found.
431 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
432 let mut current = if dir.is_relative() {
433 env::current_dir()?.join(dir)
438 current = fs::canonicalize(current)?;
441 match get_toml_path(¤t) {
442 Ok(Some(path)) => return Ok(Some(path)),
443 Err(e) => return Err(e),
447 // If the current directory has no parent, we're done searching.
454 match resolve_project_file(dir)? {
455 None => Ok((Config::default(), None)),
456 Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
461 pub fn print_docs() {
464 $( let max = cmp::max(max, stringify!($i).len()+1); )+
465 let mut space_str = String::with_capacity(max);
469 println!("Configuration Options:");
471 let name_raw = stringify!($i);
472 let mut name_out = String::with_capacity(max);
473 for _ in name_raw.len()..max-1 {
476 name_out.push_str(name_raw);
478 println!("{}{} Default: {:?}",
483 println!("{}{}", space_str, $dstring);
490 // Template for the default configuration
491 impl Default for Config {
492 fn default() -> Config {
495 $i: (Cell::new(false), false, $def, $stb),
503 /// Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
505 /// Return the path if a config file exists, empty if no file exists, and Error for IO errors
506 pub fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
507 const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
508 for config_file_name in &CONFIG_FILE_NAMES {
509 let config_file = dir.join(config_file_name);
510 match fs::metadata(&config_file) {
511 // Only return if it's a file to handle the unlikely situation of a directory named
513 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
514 // Return the error if it's something other than `NotFound`; otherwise we didn't
515 // find the project file yet, and continue searching.
516 Err(e) => if e.kind() != ErrorKind::NotFound {
528 indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items.";
529 unstable_features: bool, false, true,
530 "Enables unstable features. Only available on nightly channel";
531 verbose: bool, false, false, "Use verbose output";
532 disable_all_formatting: bool, false, false, "Don't reformat anything";
533 skip_children: bool, false, false, "Don't reformat out of line modules";
534 file_lines: FileLines, FileLines::all(), false,
535 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
536 via the --file-lines option";
537 max_width: usize, 100, false, "Maximum width of each line";
538 error_on_line_overflow: bool, true, false, "Error if unable to get all lines within max_width";
539 error_on_line_overflow_comments: bool, true, false,
540 "Error if unable to get comments within max_width";
541 tab_spaces: usize, 4, false, "Number of spaces per tab";
542 fn_call_width: usize, 60, false,
543 "Maximum width of the args of a function call before falling back to vertical formatting";
544 struct_lit_width: usize, 18, false,
545 "Maximum width in the body of a struct lit before falling back to vertical formatting";
546 struct_variant_width: usize, 35, false,
547 "Maximum width in the body of a struct variant before falling back to vertical formatting";
548 force_explicit_abi: bool, true, false, "Always print the abi for extern items";
549 newline_style: NewlineStyle, NewlineStyle::Unix, false, "Unix or Windows line endings";
550 brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items";
551 control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false,
552 "Brace style for control flow constructs";
553 impl_empty_single_line: bool, true, false, "Put empty-body implementations on a single line";
554 trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
555 "How to handle trailing commas for lists";
556 trailing_semicolon: bool, true, false,
557 "Add trailing semicolon after break, continue and return";
558 fn_empty_single_line: bool, true, false, "Put empty-body functions on a single line";
559 fn_single_line: bool, false, false, "Put single-expression functions on a single line";
560 fn_return_indent: ReturnIndent, ReturnIndent::WithArgs, false,
561 "Location of return type in function declaration";
562 fn_args_paren_newline: bool, false, false, "If function argument parenthesis goes on a newline";
563 fn_args_density: Density, Density::Tall, false, "Argument density in functions";
564 array_width: usize, 60, false,
565 "Maximum width of an array literal before falling back to vertical formatting";
566 array_horizontal_layout_threshold: usize, 0, false,
567 "How many elements array must have before rustfmt uses horizontal layout.";
568 type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
569 "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
571 // 1. Should we at least try to put the where clause on the same line as the rest of the
573 // 2. Currently options `Tall` and `Vertical` produce the same output.
574 where_density: Density, Density::Vertical, false, "Density of a where clause";
575 where_single_line: bool, false, false, "To force single line where layout";
576 where_layout: ListTactic, ListTactic::Vertical, false, "Element layout inside a where clause";
577 struct_lit_multiline_style: MultilineStyle, MultilineStyle::PreferSingle, false,
578 "Multiline style on literal structs";
579 report_todo: ReportTactic, ReportTactic::Never, false,
580 "Report all, none or unnumbered occurrences of TODO in source file comments";
581 report_fixme: ReportTactic, ReportTactic::Never, false,
582 "Report all, none or unnumbered occurrences of FIXME in source file comments";
583 chain_width: usize, 60, false, "Maximum length of a chain to fit on a single line";
584 chain_split_single_child: bool, false, false, "Split a chain with a single child if its length \
585 exceeds `chain_width`";
586 imports_indent: IndentStyle, IndentStyle::Visual, false, "Indent of imports";
587 imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
588 reorder_extern_crates: bool, true, false, "Reorder extern crate statements alphabetically";
589 reorder_extern_crates_in_group: bool, true, false, "Reorder extern crate statements in group";
590 reorder_imports: bool, false, false, "Reorder import statements alphabetically";
591 reorder_imports_in_group: bool, false, false, "Reorder import statements in group";
592 reorder_imported_names: bool, true, false,
593 "Reorder lists of names in import statements alphabetically";
594 single_line_if_else_max_width: usize, 50, false, "Maximum line length for single line if-else \
595 expressions. A value of zero means always break \
596 if-else expressions.";
597 format_strings: bool, false, false, "Format string literals where necessary";
598 force_format_strings: bool, false, false, "Always format string literals";
599 take_source_hints: bool, false, false,
600 "Retain some formatting characteristics from the source code";
601 hard_tabs: bool, false, false, "Use tab characters for indentation, spaces for alignment";
602 wrap_comments: bool, false, false, "Break comments to fit on the line";
603 comment_width: usize, 80, false,
604 "Maximum length of comments. No effect unless wrap_comments = true";
605 normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible";
606 wrap_match_arms: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \
607 the same line with the pattern of arms";
608 match_block_trailing_comma: bool, false, false,
609 "Put a trailing comma after a block based match arm (non-block arms are not affected)";
610 match_arm_forces_newline: bool, false, false,
611 "Force match arm bodies to be in a new lines";
612 indent_match_arms: bool, true, false, "Indent match arms instead of keeping them at the same \
613 indentation level as the match keyword";
614 match_pattern_separator_break_point: SeparatorPlace, SeparatorPlace::Front, false,
615 "Put a match sub-patterns' separator in front or back.";
616 space_before_colon: bool, false, false, "Leave a space before the colon";
617 space_after_colon: bool, true, false, "Leave a space after the colon";
618 spaces_around_ranges: bool, false, false, "Put spaces around the .. and ... range operators";
619 spaces_within_parens_and_brackets: bool, false, false,
620 "Put spaces within non-empty parentheses or brackets";
621 use_try_shorthand: bool, false, false, "Replace uses of the try! macro by the ? shorthand";
622 write_mode: WriteMode, WriteMode::Overwrite, false,
623 "What Write Mode to use when none is supplied: \
624 Replace, Overwrite, Display, Plain, Diff, Coverage";
625 color: Color, Color::Auto, false,
626 "What Color option to use when none is supplied: Always, Never, Auto";
627 condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
629 combine_control_expr: bool, true, false, "Combine control expressions with function calls.";
630 struct_field_align_threshold: usize, 0, false, "Align struct fields if their diffs fits within \
632 remove_blank_lines_at_start_or_end_of_block: bool, true, false,
633 "Remove blank lines at start or end of a block";
634 attributes_on_same_line_as_field: bool, true, false,
635 "Try to put attributes on the same line as fields.";
636 attributes_on_same_line_as_variant: bool, true, false,
637 "Try to put attributes on the same line as variants in enum declarations.";
638 multiline_closure_forces_block: bool, false, false,
639 "Force multiline closure bodies to be wrapped in a block";
640 multiline_match_arm_forces_block: bool, false, false,
641 "Force multiline match arm bodies to be wrapped in a block";
642 merge_derives: bool, true, false, "Merge multiple `#[derive(...)]` into a single one";
643 binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
644 "Where to put a binary operator when a binary expression goes multiline.";
645 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
646 "Require a specific version of rustfmt."
654 fn test_config_set() {
655 let mut config = Config::default();
656 config.set().verbose(false);
657 assert_eq!(config.verbose(), false);
658 config.set().verbose(true);
659 assert_eq!(config.verbose(), true);
663 fn test_config_used_to_toml() {
664 let config = Config::default();
666 let verbose = config.verbose();
667 let skip_children = config.skip_children();
669 let used_options = config.used_options();
670 let toml = used_options.to_toml().unwrap();
673 format!("verbose = {}\nskip_children = {}\n", verbose, skip_children)
679 let config = Config::from_toml("hard_tabs = true").unwrap();
681 assert_eq!(config.was_set().hard_tabs(), true);
682 assert_eq!(config.was_set().verbose(), false);
686 fn test_as_not_nightly_channel() {
687 let mut config = Config::default();
688 assert_eq!(config.was_set().unstable_features(), false);
689 config.set().unstable_features(true);
690 assert_eq!(config.was_set().unstable_features(), false);
694 fn test_as_nightly_channel() {
695 let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
696 ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
697 let mut config = Config::default();
698 config.set().unstable_features(true);
699 assert_eq!(config.was_set().unstable_features(), false);
700 config.set().unstable_features(true);
701 assert_eq!(config.unstable_features(), true);
702 ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
706 fn test_unstable_from_toml() {
707 let mut config = Config::from_toml("unstable_features = true").unwrap();
708 assert_eq!(config.was_set().unstable_features(), false);
709 let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
710 ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
711 config = Config::from_toml("unstable_features = true").unwrap();
712 assert_eq!(config.was_set().unstable_features(), true);
713 assert_eq!(config.unstable_features(), true);
714 ::std::env::set_var("CFG_RELEASE_CHANNEL", v);