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.
15 use std::default::Default;
17 use std::io::{Error, ErrorKind, Read};
18 use std::path::{Path, PathBuf};
20 use file_lines::FileLines;
21 use lists::{ListTactic, SeparatorPlace, SeparatorTactic};
25 macro_rules! is_nightly_channel {
27 env::var("CFG_RELEASE_CHANNEL")
28 .map(|c| c == "nightly")
33 macro_rules! configuration_option_enum{
34 ($e:ident: $( $x:ident ),+ $(,)*) => {
35 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
40 impl_enum_serialize_and_deserialize!($e, $( $x ),+);
44 configuration_option_enum! { NewlineStyle:
47 Native, // \r\n in Windows, \n on other platforms
50 configuration_option_enum! { BraceStyle:
53 // Prefer same line except where there is a where clause, in which case force
54 // the brace to the next line.
58 configuration_option_enum! { ControlBraceStyle:
59 // K&R style, Rust community default
67 configuration_option_enum! { IndentStyle:
68 // First line on the same line as the opening brace, all lines aligned with
71 // First line is on a new line and all lines align with block indent.
75 configuration_option_enum! { Density:
76 // Fit as much on one line as possible.
80 // Try to compress if the body is empty.
82 // Place every item on a separate line.
86 configuration_option_enum! { TypeDensity:
87 // No spaces around "=" and "+"
89 // Spaces around " = " and " + "
95 pub fn to_list_tactic(self) -> ListTactic {
97 Density::Compressed => ListTactic::Mixed,
98 Density::Tall | Density::CompressedIfEmpty => ListTactic::HorizontalVertical,
99 Density::Vertical => ListTactic::Vertical,
104 configuration_option_enum! { ReportTactic:
110 configuration_option_enum! { WriteMode:
111 // Backs the original file up and overwrites the original.
113 // Overwrites original file without backup.
115 // Writes the output to stdout.
117 // Writes the diff to stdout.
119 // Displays how much of the input file was processed
123 // Outputs a checkstyle XML file.
127 configuration_option_enum! { Color:
128 // Always use color, whether it is a piped or terminal output
132 // Automatically use color, if supported by terminal
136 #[derive(Deserialize, Serialize, Clone, Debug)]
137 pub struct WidthHeuristics {
138 // Maximum width of the args of a function call before falling back
139 // to vertical formatting.
140 pub fn_call_width: usize,
141 // Maximum width in the body of a struct lit before falling back to
142 // vertical formatting.
143 pub struct_lit_width: usize,
144 // Maximum width in the body of a struct variant before falling back
145 // to vertical formatting.
146 pub struct_variant_width: usize,
147 // Maximum width of an array literal before falling back to vertical
149 pub array_width: usize,
150 // Maximum length of a chain to fit on a single line.
151 pub chain_width: usize,
152 // Maximum line length for single line if-else expressions. A value
153 // of zero means always break if-else expressions.
154 pub single_line_if_else_max_width: usize,
157 impl WidthHeuristics {
158 // Using this WidthHeuristics means we ignore heuristics.
159 fn null() -> WidthHeuristics {
161 fn_call_width: usize::max_value(),
163 struct_variant_width: 0,
164 array_width: usize::max_value(),
165 chain_width: usize::max_value(),
166 single_line_if_else_max_width: 0,
171 impl Default for WidthHeuristics {
172 fn default() -> WidthHeuristics {
175 struct_lit_width: 18,
176 struct_variant_width: 35,
179 single_line_if_else_max_width: 50,
184 impl ::std::str::FromStr for WidthHeuristics {
185 type Err = &'static str;
187 fn from_str(_: &str) -> Result<Self, Self::Err> {
188 Err("WidthHeuristics is not parsable")
192 impl ::config::ConfigType for WidthHeuristics {
193 fn doc_hint() -> String {
198 /// Trait for types that can be used in `Config`.
199 pub trait ConfigType: Sized {
200 /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a
201 /// pipe-separated list of variants; for other types it returns "<type>".
202 fn doc_hint() -> String;
205 impl ConfigType for bool {
206 fn doc_hint() -> String {
207 String::from("<boolean>")
211 impl ConfigType for usize {
212 fn doc_hint() -> String {
213 String::from("<unsigned integer>")
217 impl ConfigType for isize {
218 fn doc_hint() -> String {
219 String::from("<signed integer>")
223 impl ConfigType for String {
224 fn doc_hint() -> String {
225 String::from("<string>")
229 impl ConfigType for FileLines {
230 fn doc_hint() -> String {
231 String::from("<json>")
235 pub struct ConfigHelpItem {
236 option_name: &'static str,
237 doc_string: &'static str,
238 variant_names: String,
239 default: &'static str,
242 impl ConfigHelpItem {
243 pub fn option_name(&self) -> &'static str {
247 pub fn doc_string(&self) -> &'static str {
251 pub fn variant_names(&self) -> &String {
255 pub fn default(&self) -> &'static str {
260 macro_rules! create_config {
261 ($($i:ident: $ty:ty, $def:expr, $stb:expr, $( $dstring:expr ),+ );+ $(;)*) => (
264 // For each config item, we store a bool indicating whether it has
265 // been accessed and the value, and a bool whether the option was
266 // manually initialised, or taken from the default,
267 $($i: (Cell<bool>, bool, $ty, bool)),+
270 // Just like the Config struct but with each property wrapped
271 // as Option<T>. This is used to parse a rustfmt.toml that doesn't
272 // specify all properties of `Config`.
273 // We first parse into `PartialConfig`, then create a default `Config`
274 // and overwrite the properties with corresponding values from `PartialConfig`.
275 #[derive(Deserialize, Serialize, Clone)]
276 pub struct PartialConfig {
277 $(pub $i: Option<$ty>),+
281 pub fn to_toml(&self) -> Result<String, String> {
282 // Non-user-facing options can't be specified in TOML
283 let mut cloned = self.clone();
284 cloned.file_lines = None;
285 cloned.verbose = None;
286 cloned.width_heuristics = None;
288 toml::to_string(&cloned)
289 .map_err(|e| format!("Could not output config: {}", e.to_string()))
293 // Macro hygiene won't allow us to make `set_$i()` methods on Config
294 // for each item, so this struct is used to give the API to set values:
295 // `config.get().option(false)`. It's pretty ugly. Consider replacing
296 // with `config.set_option(false)` if we ever get a stable/usable
297 // `concat_idents!()`.
298 pub struct ConfigSetter<'a>(&'a mut Config);
300 impl<'a> ConfigSetter<'a> {
302 pub fn $i(&mut self, value: $ty) {
303 (self.0).$i.2 = value;
304 if stringify!($i) == "use_small_heuristics" {
305 self.0.set_heuristics();
311 // Query each option, returns true if the user set the option, false if
312 // a default was used.
313 pub struct ConfigWasSet<'a>(&'a Config);
315 impl<'a> ConfigWasSet<'a> {
317 pub fn $i(&self) -> bool {
324 pub fn version_meets_requirement(&self, error_summary: &mut Summary) -> bool {
325 if self.was_set().required_version() {
326 let version = env!("CARGO_PKG_VERSION");
327 let required_version = self.required_version();
328 if version != required_version {
330 "Error: rustfmt version ({}) doesn't match the required version ({})",
334 error_summary.add_formatting_error();
343 pub fn $i(&self) -> $ty {
349 pub fn set<'a>(&'a mut self) -> ConfigSetter<'a> {
353 pub fn was_set<'a>(&'a self) -> ConfigWasSet<'a> {
357 fn fill_from_parsed_config(mut self, parsed: PartialConfig) -> Config {
359 if let Some(val) = parsed.$i {
364 if is_nightly_channel!() {
368 println!("Warning: can't set some features as unstable \
369 features are only available in nightly channel.");
374 self.set_heuristics();
378 pub fn from_toml(toml: &str) -> Result<Config, String> {
379 let parsed: toml::Value =
380 toml.parse().map_err(|e| format!("Could not parse TOML: {}", e))?;
381 let mut err: String = String::new();
385 .ok_or(String::from("Parsed config was not table"))?;
386 for key in table.keys() {
389 stringify!($i) => (),
393 &format!("Warning: Unknown configuration option `{}`\n",
400 match parsed.try_into() {
402 Ok(Config::default().fill_from_parsed_config(parsed_config)),
404 err.push_str("Error: Decoding config file failed:\n");
405 err.push_str(format!("{}\n", e).as_str());
406 err.push_str("Please check your config file.\n");
412 pub fn used_options(&self) -> PartialConfig {
415 $i: if self.$i.0.get() {
416 Some(self.$i.2.clone())
424 pub fn all_options(&self) -> PartialConfig {
427 $i: Some(self.$i.2.clone()),
432 pub fn override_value(&mut self, key: &str, val: &str)
437 self.$i.2 = val.parse::<$ty>()
438 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
444 _ => panic!("Unknown config key in override: {}", key)
447 if key == "use_small_heuristics" {
448 self.set_heuristics();
452 /// Construct a `Config` from the toml file specified at `file_path`.
454 /// This method only looks at the provided path, for a method that
455 /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
457 /// Return a `Config` if the config could be read and parsed from
458 /// the file, Error otherwise.
459 pub fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
460 let mut file = File::open(&file_path)?;
461 let mut toml = String::new();
462 file.read_to_string(&mut toml)?;
463 Config::from_toml(&toml).map_err(|err| Error::new(ErrorKind::InvalidData, err))
466 /// Resolve the config for input in `dir`.
468 /// Searches for `rustfmt.toml` beginning with `dir`, and
469 /// recursively checking parents of `dir` if no config file is found.
470 /// If no config file exists in `dir` or in any parent, a
471 /// default `Config` will be returned (and the returned path will be empty).
473 /// Returns the `Config` to use, and the path of the project file if there was
475 pub fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
477 /// Try to find a project file in the given directory and its parents.
478 /// Returns the path of a the nearest project file if one exists,
479 /// or `None` if no project file was found.
480 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
481 let mut current = if dir.is_relative() {
482 env::current_dir()?.join(dir)
487 current = fs::canonicalize(current)?;
490 match get_toml_path(¤t) {
491 Ok(Some(path)) => return Ok(Some(path)),
492 Err(e) => return Err(e),
496 // If the current directory has no parent, we're done searching.
503 match resolve_project_file(dir)? {
504 None => Ok((Config::default(), None)),
505 Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
510 pub fn print_docs() {
513 $( let max = cmp::max(max, stringify!($i).len()+1); )+
514 let mut space_str = String::with_capacity(max);
518 println!("Configuration Options:");
520 let name_raw = stringify!($i);
521 let mut name_out = String::with_capacity(max);
522 for _ in name_raw.len()..max-1 {
525 name_out.push_str(name_raw);
527 println!("{}{} Default: {:?}",
532 println!("{}{}", space_str, $dstring);
538 fn set_heuristics(&mut self) {
539 if self.use_small_heuristics.2 {
540 self.set().width_heuristics(WidthHeuristics::default());
542 self.set().width_heuristics(WidthHeuristics::null());
547 // Template for the default configuration
548 impl Default for Config {
549 fn default() -> Config {
552 $i: (Cell::new(false), false, $def, $stb),
560 /// Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
562 /// Return the path if a config file exists, empty if no file exists, and Error for IO errors
563 pub fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
564 const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
565 for config_file_name in &CONFIG_FILE_NAMES {
566 let config_file = dir.join(config_file_name);
567 match fs::metadata(&config_file) {
568 // Only return if it's a file to handle the unlikely situation of a directory named
570 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
571 // Return the error if it's something other than `NotFound`; otherwise we didn't
572 // find the project file yet, and continue searching.
573 Err(e) => if e.kind() != ErrorKind::NotFound {
586 max_width: usize, 100, true, "Maximum width of each line";
587 hard_tabs: bool, false, true, "Use tab characters for indentation, spaces for alignment";
588 tab_spaces: usize, 4, true, "Number of spaces per tab";
589 newline_style: NewlineStyle, NewlineStyle::Unix, true, "Unix or Windows line endings";
590 indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items.";
591 use_small_heuristics: bool, true, false, "Whether to use different formatting for items and\
592 expressions if they satisfy a heuristic notion of 'small'.";
594 // strings and comments
595 format_strings: bool, false, false, "Format string literals where necessary";
596 wrap_comments: bool, false, true, "Break comments to fit on the line";
597 comment_width: usize, 80, false,
598 "Maximum length of comments. No effect unless wrap_comments = true";
599 normalize_comments: bool, false, true, "Convert /* */ comments to // comments where possible";
601 // Single line expressions and items.
602 struct_lit_single_line: bool, true, false,
603 "Put small struct literals on a single line";
604 impl_empty_single_line: bool, true, false, "Put empty-body implementations on a single line";
605 fn_empty_single_line: bool, true, false, "Put empty-body functions on a single line";
606 fn_single_line: bool, false, false, "Put single-expression functions on a single line";
607 where_single_line: bool, false, false, "To force single line where layout";
610 imports_indent: IndentStyle, IndentStyle::Visual, false, "Indent of imports";
611 imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
614 reorder_extern_crates: bool, true, false, "Reorder extern crate statements alphabetically";
615 reorder_extern_crates_in_group: bool, true, false, "Reorder extern crate statements in group";
616 reorder_imports: bool, false, false, "Reorder import statements alphabetically";
617 reorder_imports_in_group: bool, false, false, "Reorder import statements in group";
618 reorder_imported_names: bool, true, false,
619 "Reorder lists of names in import statements alphabetically";
622 wrap_match_arms: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \
623 the same line with the pattern of arms";
624 match_block_trailing_comma: bool, false, false,
625 "Put a trailing comma after a block based match arm (non-block arms are not affected)";
627 // Spaces around punctuation
628 binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
629 "Where to put a binary operator when a binary expression goes multiline.";
630 type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
631 "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
632 space_before_colon: bool, false, false, "Leave a space before the colon";
633 space_after_colon: bool, true, false, "Leave a space after the colon";
634 spaces_around_ranges: bool, false, false, "Put spaces around the .. and ... range operators";
635 spaces_within_parens_and_brackets: bool, false, false,
636 "Put spaces within non-empty parentheses or brackets";
639 combine_control_expr: bool, true, false, "Combine control expressions with function calls.";
640 struct_field_align_threshold: usize, 0, false, "Align struct fields if their diffs fits within \
642 remove_blank_lines_at_start_or_end_of_block: bool, true, false,
643 "Remove blank lines at start or end of a block";
644 same_line_attributes: bool, true, false,
645 "Try to put attributes on the same line as fields and variants.";
646 force_multiline_blocks: bool, false, false,
647 "Force multiline closure bodies and match arms to be wrapped in a block";
648 fn_args_density: Density, Density::Tall, false, "Argument density in functions";
649 brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items";
650 control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false,
651 "Brace style for control flow constructs";
652 trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
653 "How to handle trailing commas for lists";
654 trailing_semicolon: bool, true, false,
655 "Add trailing semicolon after break, continue and return";
657 // Options that can change the source code beyond whitespace/blocks (somewhat linty things)
658 merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one";
659 use_try_shorthand: bool, false, false, "Replace uses of the try! macro by the ? shorthand";
660 condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
662 force_explicit_abi: bool, true, true, "Always print the abi for extern items";
664 // Control options (changes the operation of rustfmt, rather than the formatting)
665 write_mode: WriteMode, WriteMode::Overwrite, false,
666 "What Write Mode to use when none is supplied: \
667 Replace, Overwrite, Display, Plain, Diff, Coverage";
668 color: Color, Color::Auto, false,
669 "What Color option to use when none is supplied: Always, Never, Auto";
670 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
671 "Require a specific version of rustfmt.";
672 unstable_features: bool, false, true,
673 "Enables unstable features. Only available on nightly channel";
674 disable_all_formatting: bool, false, false, "Don't reformat anything";
675 skip_children: bool, false, false, "Don't reformat out of line modules";
676 error_on_line_overflow: bool, true, false, "Error if unable to get all lines within max_width";
677 error_on_line_overflow_comments: bool, true, false,
678 "Error if unable to get comments within max_width";
679 report_todo: ReportTactic, ReportTactic::Never, false,
680 "Report all, none or unnumbered occurrences of TODO in source file comments";
681 report_fixme: ReportTactic, ReportTactic::Never, false,
682 "Report all, none or unnumbered occurrences of FIXME in source file comments";
685 verbose: bool, false, false, "Use verbose output";
686 file_lines: FileLines, FileLines::all(), false,
687 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
688 via the --file-lines option";
689 width_heuristics: WidthHeuristics, WidthHeuristics::default(), false,
690 "'small' heuristic values";
698 fn test_config_set() {
699 let mut config = Config::default();
700 config.set().verbose(false);
701 assert_eq!(config.verbose(), false);
702 config.set().verbose(true);
703 assert_eq!(config.verbose(), true);
707 fn test_config_used_to_toml() {
708 let config = Config::default();
710 let merge_derives = config.merge_derives();
711 let skip_children = config.skip_children();
713 let used_options = config.used_options();
714 let toml = used_options.to_toml().unwrap();
718 "merge_derives = {}\nskip_children = {}\n",
727 let config = Config::from_toml("hard_tabs = true").unwrap();
729 assert_eq!(config.was_set().hard_tabs(), true);
730 assert_eq!(config.was_set().verbose(), false);
733 // FIXME(#2183) these tests cannot be run in parallel because they use env vars
735 // fn test_as_not_nightly_channel() {
736 // let mut config = Config::default();
737 // assert_eq!(config.was_set().unstable_features(), false);
738 // config.set().unstable_features(true);
739 // assert_eq!(config.was_set().unstable_features(), false);
743 // fn test_as_nightly_channel() {
744 // let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
745 // ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
746 // let mut config = Config::default();
747 // config.set().unstable_features(true);
748 // assert_eq!(config.was_set().unstable_features(), false);
749 // config.set().unstable_features(true);
750 // assert_eq!(config.unstable_features(), true);
751 // ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
755 // fn test_unstable_from_toml() {
756 // let mut config = Config::from_toml("unstable_features = true").unwrap();
757 // assert_eq!(config.was_set().unstable_features(), false);
758 // let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
759 // ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
760 // config = Config::from_toml("unstable_features = true").unwrap();
761 // assert_eq!(config.was_set().unstable_features(), true);
762 // assert_eq!(config.unstable_features(), true);
763 // ::std::env::set_var("CFG_RELEASE_CHANNEL", v);