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 /// 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, $stb:expr, $( $dstring:expr ),+ );+ $(;)*) => (
216 // For each config item, we store a bool indicating whether it has
217 // been accessed and the value, and a bool whether the option was
218 // manually initialised, or taken from the default,
219 $($i: (Cell<bool>, bool, $ty, bool)),+
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 // specify 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 pub struct PartialConfig {
229 $(pub $i: Option<$ty>),+
233 pub fn to_toml(&self) -> Result<String, String> {
234 // file_lines can't be specified in TOML
235 let mut cloned = self.clone();
236 cloned.file_lines = None;
238 toml::to_string(&cloned)
239 .map_err(|e| format!("Could not output config: {}", e.to_string()))
243 // Macro hygiene won't allow us to make `set_$i()` methods on Config
244 // for each item, so this struct is used to give the API to set values:
245 // `config.get().option(false)`. It's pretty ugly. Consider replacing
246 // with `config.set_option(false)` if we ever get a stable/usable
247 // `concat_idents!()`.
248 pub struct ConfigSetter<'a>(&'a mut Config);
250 impl<'a> ConfigSetter<'a> {
252 pub fn $i(&mut self, value: $ty) {
253 (self.0).$i.2 = value;
258 // Query each option, returns true if the user set the option, false if
259 // a default was used.
260 pub struct ConfigWasSet<'a>(&'a Config);
262 impl<'a> ConfigWasSet<'a> {
264 pub fn $i(&self) -> bool {
271 pub fn version_meets_requirement(&self, error_summary: &mut Summary) -> bool {
272 if self.was_set().required_version() {
273 let version = env!("CARGO_PKG_VERSION");
274 let required_version = self.required_version();
275 if version != required_version {
277 "Error: rustfmt version ({}) doesn't match the required version ({})",
281 error_summary.add_formatting_error();
290 pub fn $i(&self) -> $ty {
296 pub fn set<'a>(&'a mut self) -> ConfigSetter<'a> {
300 pub fn was_set<'a>(&'a self) -> ConfigWasSet<'a> {
304 fn fill_from_parsed_config(mut self, parsed: PartialConfig) -> Config {
306 if let Some(val) = parsed.$i {
311 if is_nightly_channel!() {
315 println!("Warning: can't set some features as unstable \
316 features are only available in nightly channel.");
324 pub fn from_toml(toml: &str) -> Result<Config, String> {
325 let parsed: toml::Value =
326 toml.parse().map_err(|e| format!("Could not parse TOML: {}", e))?;
327 let mut err: String = String::new();
331 .ok_or(String::from("Parsed config was not table"))?;
332 for key in table.keys() {
335 stringify!($i) => (),
339 &format!("Warning: Unknown configuration option `{}`\n",
346 match parsed.try_into() {
348 Ok(Config::default().fill_from_parsed_config(parsed_config)),
350 err.push_str("Error: Decoding config file failed:\n");
351 err.push_str(format!("{}\n", e).as_str());
352 err.push_str("Please check your config file.\n");
358 pub fn used_options(&self) -> PartialConfig {
361 $i: if self.$i.0.get() {
362 Some(self.$i.2.clone())
370 pub fn all_options(&self) -> PartialConfig {
373 $i: Some(self.$i.2.clone()),
378 pub fn override_value(&mut self, key: &str, val: &str)
383 self.$i.2 = val.parse::<$ty>()
384 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
390 _ => panic!("Unknown config key in override: {}", key)
394 /// Construct a `Config` from the toml file specified at `file_path`.
396 /// This method only looks at the provided path, for a method that
397 /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
399 /// Return a `Config` if the config could be read and parsed from
400 /// the file, Error otherwise.
401 pub fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
402 let mut file = File::open(&file_path)?;
403 let mut toml = String::new();
404 file.read_to_string(&mut toml)?;
405 Config::from_toml(&toml).map_err(|err| Error::new(ErrorKind::InvalidData, err))
408 /// Resolve the config for input in `dir`.
410 /// Searches for `rustfmt.toml` beginning with `dir`, and
411 /// recursively checking parents of `dir` if no config file is found.
412 /// If no config file exists in `dir` or in any parent, a
413 /// default `Config` will be returned (and the returned path will be empty).
415 /// Returns the `Config` to use, and the path of the project file if there was
417 pub fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
419 /// Try to find a project file in the given directory and its parents.
420 /// Returns the path of a the nearest project file if one exists,
421 /// or `None` if no project file was found.
422 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
423 let mut current = if dir.is_relative() {
424 env::current_dir()?.join(dir)
429 current = fs::canonicalize(current)?;
432 match get_toml_path(¤t) {
433 Ok(Some(path)) => return Ok(Some(path)),
434 Err(e) => return Err(e),
438 // If the current directory has no parent, we're done searching.
445 match resolve_project_file(dir)? {
446 None => Ok((Config::default(), None)),
447 Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
452 pub fn print_docs() {
455 $( let max = cmp::max(max, stringify!($i).len()+1); )+
456 let mut space_str = String::with_capacity(max);
460 println!("Configuration Options:");
462 let name_raw = stringify!($i);
463 let mut name_out = String::with_capacity(max);
464 for _ in name_raw.len()..max-1 {
467 name_out.push_str(name_raw);
469 println!("{}{} Default: {:?}",
474 println!("{}{}", space_str, $dstring);
481 // Template for the default configuration
482 impl Default for Config {
483 fn default() -> Config {
486 $i: (Cell::new(false), false, $def, $stb),
494 /// Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
496 /// Return the path if a config file exists, empty if no file exists, and Error for IO errors
497 pub fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
498 const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
499 for config_file_name in &CONFIG_FILE_NAMES {
500 let config_file = dir.join(config_file_name);
501 match fs::metadata(&config_file) {
502 // Only return if it's a file to handle the unlikely situation of a directory named
504 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
505 // Return the error if it's something other than `NotFound`; otherwise we didn't
506 // find the project file yet, and continue searching.
507 Err(e) => if e.kind() != ErrorKind::NotFound {
519 indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items.";
520 unstable_features: bool, false, true,
521 "Enables unstable features. Only available on nightly channel";
522 verbose: bool, false, false, "Use verbose output";
523 disable_all_formatting: bool, false, false, "Don't reformat anything";
524 skip_children: bool, false, false, "Don't reformat out of line modules";
525 file_lines: FileLines, FileLines::all(), false,
526 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
527 via the --file-lines option";
528 max_width: usize, 100, false, "Maximum width of each line";
529 error_on_line_overflow: bool, true, false, "Error if unable to get all lines within max_width";
530 error_on_line_overflow_comments: bool, true, false,
531 "Error if unable to get comments within max_width";
532 tab_spaces: usize, 4, false, "Number of spaces per tab";
533 fn_call_width: usize, 60, false,
534 "Maximum width of the args of a function call before falling back to vertical formatting";
535 struct_lit_width: usize, 18, false,
536 "Maximum width in the body of a struct lit before falling back to vertical formatting";
537 struct_variant_width: usize, 35, false,
538 "Maximum width in the body of a struct variant before falling back to vertical formatting";
539 force_explicit_abi: bool, true, false, "Always print the abi for extern items";
540 newline_style: NewlineStyle, NewlineStyle::Unix, false, "Unix or Windows line endings";
541 fn_brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for functions";
542 item_brace_style: BraceStyle, BraceStyle::SameLineWhere, false,
543 "Brace style for structs and enums";
544 control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false,
545 "Brace style for control flow constructs";
546 impl_empty_single_line: bool, true, false, "Put empty-body implementations on a single line";
547 trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
548 "How to handle trailing commas for lists";
549 trailing_semicolon: bool, true, false,
550 "Add trailing semicolon after break, continue and return";
551 fn_empty_single_line: bool, true, false, "Put empty-body functions on a single line";
552 fn_single_line: bool, false, false, "Put single-expression functions on a single line";
553 fn_return_indent: ReturnIndent, ReturnIndent::WithArgs, false,
554 "Location of return type in function declaration";
555 fn_args_paren_newline: bool, false, false, "If function argument parenthesis goes on a newline";
556 fn_args_density: Density, Density::Tall, false, "Argument density in functions";
557 array_width: usize, 60, false,
558 "Maximum width of an array literal before falling back to vertical formatting";
559 array_horizontal_layout_threshold: usize, 0, false,
560 "How many elements array must have before rustfmt uses horizontal layout.";
561 type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
562 "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
564 // 1. Should we at least try to put the where clause on the same line as the rest of the
566 // 2. Currently options `Tall` and `Vertical` produce the same output.
567 where_density: Density, Density::Vertical, false, "Density of a where clause";
568 where_single_line: bool, false, false, "To force single line where layout";
569 where_layout: ListTactic, ListTactic::Vertical, false, "Element layout inside a where clause";
570 struct_lit_multiline_style: MultilineStyle, MultilineStyle::PreferSingle, false,
571 "Multiline style on literal structs";
572 report_todo: ReportTactic, ReportTactic::Never, false,
573 "Report all, none or unnumbered occurrences of TODO in source file comments";
574 report_fixme: ReportTactic, ReportTactic::Never, false,
575 "Report all, none or unnumbered occurrences of FIXME in source file comments";
576 chain_width: usize, 60, false, "Maximum length of a chain to fit on a single line";
577 chain_split_single_child: bool, false, false, "Split a chain with a single child if its length \
578 exceeds `chain_width`";
579 imports_indent: IndentStyle, IndentStyle::Visual, false, "Indent of imports";
580 imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
581 reorder_extern_crates: bool, true, false, "Reorder extern crate statements alphabetically";
582 reorder_extern_crates_in_group: bool, true, false, "Reorder extern crate statements in group";
583 reorder_imports: bool, false, false, "Reorder import statements alphabetically";
584 reorder_imports_in_group: bool, false, false, "Reorder import statements in group";
585 reorder_imported_names: bool, true, false,
586 "Reorder lists of names in import statements alphabetically";
587 single_line_if_else_max_width: usize, 50, false, "Maximum line length for single line if-else \
588 expressions. A value of zero means always break \
589 if-else expressions.";
590 format_strings: bool, false, false, "Format string literals where necessary";
591 force_format_strings: bool, false, false, "Always format string literals";
592 take_source_hints: bool, false, false,
593 "Retain some formatting characteristics from the source code";
594 hard_tabs: bool, false, false, "Use tab characters for indentation, spaces for alignment";
595 wrap_comments: bool, false, false, "Break comments to fit on the line";
596 comment_width: usize, 80, false,
597 "Maximum length of comments. No effect unless wrap_comments = true";
598 normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible";
599 wrap_match_arms: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \
600 the same line with the pattern of arms";
601 match_block_trailing_comma: bool, false, false,
602 "Put a trailing comma after a block based match arm (non-block arms are not affected)";
603 match_arm_forces_newline: bool, false, false,
604 "Force match arm bodies to be in a new lines";
605 indent_match_arms: bool, true, false, "Indent match arms instead of keeping them at the same \
606 indentation level as the match keyword";
607 match_pattern_separator_break_point: SeparatorPlace, SeparatorPlace::Back, false,
608 "Put a match sub-patterns' separator in front or back.";
609 space_before_type_annotation: bool, false, false,
610 "Leave a space before the colon in a type annotation";
611 space_after_type_annotation_colon: bool, true, false,
612 "Leave a space after the colon in a type annotation";
613 space_before_struct_lit_field_colon: bool, false, false,
614 "Leave a space before the colon in a struct literal field";
615 space_after_struct_lit_field_colon: bool, true, false,
616 "Leave a space after the colon in a struct literal field";
617 space_before_bound: bool, false, false,
618 "Leave a space before the colon in a trait or lifetime bound";
619 space_after_bound_colon: bool, true, false,
620 "Leave a space after the colon in a trait or lifetime bound";
621 spaces_around_ranges: bool, false, false, "Put spaces around the .. and ... range operators";
622 spaces_within_angle_brackets: bool, false, false,
623 "Put spaces within non-empty generic arguments";
624 spaces_within_square_brackets: bool, false, false,
625 "Put spaces within non-empty square brackets";
626 spaces_within_parens: bool, false, false, "Put spaces within non-empty parentheses";
627 use_try_shorthand: bool, false, false, "Replace uses of the try! macro by the ? shorthand";
628 write_mode: WriteMode, WriteMode::Overwrite, false,
629 "What Write Mode to use when none is supplied: \
630 Replace, Overwrite, Display, Plain, Diff, Coverage";
631 condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
633 combine_control_expr: bool, true, false, "Combine control expressions with function calls.";
634 struct_field_align_threshold: usize, 0, false, "Align struct fields if their diffs fits within \
636 remove_blank_lines_at_start_or_end_of_block: bool, true, false,
637 "Remove blank lines at start or end of a block";
638 attributes_on_same_line_as_field: bool, true, false,
639 "Try to put attributes on the same line as fields.";
640 attributes_on_same_line_as_variant: bool, true, false,
641 "Try to put attributes on the same line as variants in enum declarations.";
642 multiline_closure_forces_block: bool, false, false,
643 "Force multiline closure bodies to be wrapped in a block";
644 multiline_match_arm_forces_block: bool, false, false,
645 "Force multiline match arm bodies to be wrapped in a block";
646 merge_derives: bool, true, false, "Merge multiple `#[derive(...)]` into a single one";
647 binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
648 "Where to put a binary operator when a binary expression goes multiline.";
649 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
650 "Require a specific version of rustfmt."
658 fn test_config_set() {
659 let mut config = Config::default();
660 config.set().verbose(false);
661 assert_eq!(config.verbose(), false);
662 config.set().verbose(true);
663 assert_eq!(config.verbose(), true);
667 fn test_config_used_to_toml() {
668 let config = Config::default();
670 let verbose = config.verbose();
671 let skip_children = config.skip_children();
673 let used_options = config.used_options();
674 let toml = used_options.to_toml().unwrap();
677 format!("verbose = {}\nskip_children = {}\n", verbose, skip_children)
683 let config = Config::from_toml("hard_tabs = true").unwrap();
685 assert_eq!(config.was_set().hard_tabs(), true);
686 assert_eq!(config.was_set().verbose(), false);
690 fn test_as_not_nightly_channel() {
691 let mut config = Config::default();
692 assert_eq!(config.was_set().unstable_features(), false);
693 config.set().unstable_features(true);
694 assert_eq!(config.was_set().unstable_features(), false);
698 fn test_as_nightly_channel() {
699 let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
700 ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
701 let mut config = Config::default();
702 config.set().unstable_features(true);
703 assert_eq!(config.was_set().unstable_features(), false);
704 config.set().unstable_features(true);
705 assert_eq!(config.unstable_features(), true);
706 ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
710 fn test_unstable_from_toml() {
711 let mut config = Config::from_toml("unstable_features = true").unwrap();
712 assert_eq!(config.was_set().unstable_features(), false);
713 let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
714 ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
715 config = Config::from_toml("unstable_features = true").unwrap();
716 assert_eq!(config.was_set().unstable_features(), true);
717 assert_eq!(config.unstable_features(), true);
718 ::std::env::set_var("CFG_RELEASE_CHANNEL", v);