diff options
Diffstat (limited to 'src/tools/rustfmt/src/config')
-rw-r--r-- | src/tools/rustfmt/src/config/config_type.rs | 426 | ||||
-rw-r--r-- | src/tools/rustfmt/src/config/file_lines.rs | 440 | ||||
-rw-r--r-- | src/tools/rustfmt/src/config/lists.rs | 92 | ||||
-rw-r--r-- | src/tools/rustfmt/src/config/mod.rs | 924 | ||||
-rw-r--r-- | src/tools/rustfmt/src/config/options.rs | 464 |
5 files changed, 2346 insertions, 0 deletions
diff --git a/src/tools/rustfmt/src/config/config_type.rs b/src/tools/rustfmt/src/config/config_type.rs new file mode 100644 index 000000000..e37ed798c --- /dev/null +++ b/src/tools/rustfmt/src/config/config_type.rs @@ -0,0 +1,426 @@ +use crate::config::file_lines::FileLines; +use crate::config::options::{IgnoreList, WidthHeuristics}; + +/// Trait for types that can be used in `Config`. +pub(crate) trait ConfigType: Sized { + /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a + /// pipe-separated list of variants; for other types it returns "<type>". + fn doc_hint() -> String; +} + +impl ConfigType for bool { + fn doc_hint() -> String { + String::from("<boolean>") + } +} + +impl ConfigType for usize { + fn doc_hint() -> String { + String::from("<unsigned integer>") + } +} + +impl ConfigType for isize { + fn doc_hint() -> String { + String::from("<signed integer>") + } +} + +impl ConfigType for String { + fn doc_hint() -> String { + String::from("<string>") + } +} + +impl ConfigType for FileLines { + fn doc_hint() -> String { + String::from("<json>") + } +} + +impl ConfigType for WidthHeuristics { + fn doc_hint() -> String { + String::new() + } +} + +impl ConfigType for IgnoreList { + fn doc_hint() -> String { + String::from("[<string>,..]") + } +} + +macro_rules! create_config { + ($($i:ident: $ty:ty, $def:expr, $stb:expr, $( $dstring:expr ),+ );+ $(;)*) => ( + #[cfg(test)] + use std::collections::HashSet; + use std::io::Write; + + use serde::{Deserialize, Serialize}; + + #[derive(Clone)] + #[allow(unreachable_pub)] + pub struct Config { + // For each config item, we store a bool indicating whether it has + // been accessed and the value, and a bool whether the option was + // manually initialised, or taken from the default, + $($i: (Cell<bool>, bool, $ty, bool)),+ + } + + // Just like the Config struct but with each property wrapped + // as Option<T>. This is used to parse a rustfmt.toml that doesn't + // specify all properties of `Config`. + // We first parse into `PartialConfig`, then create a default `Config` + // and overwrite the properties with corresponding values from `PartialConfig`. + #[derive(Deserialize, Serialize, Clone)] + #[allow(unreachable_pub)] + pub struct PartialConfig { + $(pub $i: Option<$ty>),+ + } + + // Macro hygiene won't allow us to make `set_$i()` methods on Config + // for each item, so this struct is used to give the API to set values: + // `config.set().option(false)`. It's pretty ugly. Consider replacing + // with `config.set_option(false)` if we ever get a stable/usable + // `concat_idents!()`. + #[allow(unreachable_pub)] + pub struct ConfigSetter<'a>(&'a mut Config); + + impl<'a> ConfigSetter<'a> { + $( + #[allow(unreachable_pub)] + pub fn $i(&mut self, value: $ty) { + (self.0).$i.2 = value; + match stringify!($i) { + "max_width" + | "use_small_heuristics" + | "fn_call_width" + | "single_line_if_else_max_width" + | "attr_fn_like_width" + | "struct_lit_width" + | "struct_variant_width" + | "array_width" + | "chain_width" => self.0.set_heuristics(), + "merge_imports" => self.0.set_merge_imports(), + &_ => (), + } + } + )+ + } + + // Query each option, returns true if the user set the option, false if + // a default was used. + #[allow(unreachable_pub)] + pub struct ConfigWasSet<'a>(&'a Config); + + impl<'a> ConfigWasSet<'a> { + $( + #[allow(unreachable_pub)] + pub fn $i(&self) -> bool { + (self.0).$i.1 + } + )+ + } + + impl Config { + $( + #[allow(unreachable_pub)] + pub fn $i(&self) -> $ty { + self.$i.0.set(true); + self.$i.2.clone() + } + )+ + + #[allow(unreachable_pub)] + pub fn set(&mut self) -> ConfigSetter<'_> { + ConfigSetter(self) + } + + #[allow(unreachable_pub)] + pub fn was_set(&self) -> ConfigWasSet<'_> { + ConfigWasSet(self) + } + + fn fill_from_parsed_config(mut self, parsed: PartialConfig, dir: &Path) -> Config { + $( + if let Some(val) = parsed.$i { + if self.$i.3 { + self.$i.1 = true; + self.$i.2 = val; + } else { + if crate::is_nightly_channel!() { + self.$i.1 = true; + self.$i.2 = val; + } else { + eprintln!("Warning: can't set `{} = {:?}`, unstable features are only \ + available in nightly channel.", stringify!($i), val); + } + } + } + )+ + self.set_heuristics(); + self.set_ignore(dir); + self.set_merge_imports(); + self + } + + /// Returns a hash set initialized with every user-facing config option name. + #[cfg(test)] + pub(crate) fn hash_set() -> HashSet<String> { + let mut hash_set = HashSet::new(); + $( + hash_set.insert(stringify!($i).to_owned()); + )+ + hash_set + } + + pub(crate) fn is_valid_name(name: &str) -> bool { + match name { + $( + stringify!($i) => true, + )+ + _ => false, + } + } + + #[allow(unreachable_pub)] + pub fn is_valid_key_val(key: &str, val: &str) -> bool { + match key { + $( + stringify!($i) => val.parse::<$ty>().is_ok(), + )+ + _ => false, + } + } + + #[allow(unreachable_pub)] + pub fn used_options(&self) -> PartialConfig { + PartialConfig { + $( + $i: if self.$i.0.get() { + Some(self.$i.2.clone()) + } else { + None + }, + )+ + } + } + + #[allow(unreachable_pub)] + pub fn all_options(&self) -> PartialConfig { + PartialConfig { + $( + $i: Some(self.$i.2.clone()), + )+ + } + } + + #[allow(unreachable_pub)] + pub fn override_value(&mut self, key: &str, val: &str) + { + match key { + $( + stringify!($i) => { + self.$i.1 = true; + self.$i.2 = val.parse::<$ty>() + .expect(&format!("Failed to parse override for {} (\"{}\") as a {}", + stringify!($i), + val, + stringify!($ty))); + } + )+ + _ => panic!("Unknown config key in override: {}", key) + } + + match key { + "max_width" + | "use_small_heuristics" + | "fn_call_width" + | "single_line_if_else_max_width" + | "attr_fn_like_width" + | "struct_lit_width" + | "struct_variant_width" + | "array_width" + | "chain_width" => self.set_heuristics(), + "merge_imports" => self.set_merge_imports(), + &_ => (), + } + } + + #[allow(unreachable_pub)] + pub fn is_hidden_option(name: &str) -> bool { + const HIDE_OPTIONS: [&str; 5] = + ["verbose", "verbose_diff", "file_lines", "width_heuristics", "merge_imports"]; + HIDE_OPTIONS.contains(&name) + } + + #[allow(unreachable_pub)] + pub fn print_docs(out: &mut dyn Write, include_unstable: bool) { + use std::cmp; + let max = 0; + $( let max = cmp::max(max, stringify!($i).len()+1); )+ + let space_str = " ".repeat(max); + writeln!(out, "Configuration Options:").unwrap(); + $( + if $stb || include_unstable { + let name_raw = stringify!($i); + + if !Config::is_hidden_option(name_raw) { + let mut name_out = String::with_capacity(max); + for _ in name_raw.len()..max-1 { + name_out.push(' ') + } + name_out.push_str(name_raw); + name_out.push(' '); + let mut default_str = format!("{}", $def); + if default_str.is_empty() { + default_str = String::from("\"\""); + } + writeln!(out, + "{}{} Default: {}{}", + name_out, + <$ty>::doc_hint(), + default_str, + if !$stb { " (unstable)" } else { "" }).unwrap(); + $( + writeln!(out, "{}{}", space_str, $dstring).unwrap(); + )+ + writeln!(out).unwrap(); + } + } + )+ + } + + fn set_width_heuristics(&mut self, heuristics: WidthHeuristics) { + let max_width = self.max_width.2; + let get_width_value = | + was_set: bool, + override_value: usize, + heuristic_value: usize, + config_key: &str, + | -> usize { + if !was_set { + return heuristic_value; + } + if override_value > max_width { + eprintln!( + "`{0}` cannot have a value that exceeds `max_width`. \ + `{0}` will be set to the same value as `max_width`", + config_key, + ); + return max_width; + } + override_value + }; + + let fn_call_width = get_width_value( + self.was_set().fn_call_width(), + self.fn_call_width.2, + heuristics.fn_call_width, + "fn_call_width", + ); + self.fn_call_width.2 = fn_call_width; + + let attr_fn_like_width = get_width_value( + self.was_set().attr_fn_like_width(), + self.attr_fn_like_width.2, + heuristics.attr_fn_like_width, + "attr_fn_like_width", + ); + self.attr_fn_like_width.2 = attr_fn_like_width; + + let struct_lit_width = get_width_value( + self.was_set().struct_lit_width(), + self.struct_lit_width.2, + heuristics.struct_lit_width, + "struct_lit_width", + ); + self.struct_lit_width.2 = struct_lit_width; + + let struct_variant_width = get_width_value( + self.was_set().struct_variant_width(), + self.struct_variant_width.2, + heuristics.struct_variant_width, + "struct_variant_width", + ); + self.struct_variant_width.2 = struct_variant_width; + + let array_width = get_width_value( + self.was_set().array_width(), + self.array_width.2, + heuristics.array_width, + "array_width", + ); + self.array_width.2 = array_width; + + let chain_width = get_width_value( + self.was_set().chain_width(), + self.chain_width.2, + heuristics.chain_width, + "chain_width", + ); + self.chain_width.2 = chain_width; + + let single_line_if_else_max_width = get_width_value( + self.was_set().single_line_if_else_max_width(), + self.single_line_if_else_max_width.2, + heuristics.single_line_if_else_max_width, + "single_line_if_else_max_width", + ); + self.single_line_if_else_max_width.2 = single_line_if_else_max_width; + } + + fn set_heuristics(&mut self) { + let max_width = self.max_width.2; + match self.use_small_heuristics.2 { + Heuristics::Default => + self.set_width_heuristics(WidthHeuristics::scaled(max_width)), + Heuristics::Max => self.set_width_heuristics(WidthHeuristics::set(max_width)), + Heuristics::Off => self.set_width_heuristics(WidthHeuristics::null()), + }; + } + + fn set_ignore(&mut self, dir: &Path) { + self.ignore.2.add_prefix(dir); + } + + fn set_merge_imports(&mut self) { + if self.was_set().merge_imports() { + eprintln!( + "Warning: the `merge_imports` option is deprecated. \ + Use `imports_granularity=\"Crate\"` instead" + ); + if !self.was_set().imports_granularity() { + self.imports_granularity.2 = if self.merge_imports() { + ImportGranularity::Crate + } else { + ImportGranularity::Preserve + }; + } + } + } + + #[allow(unreachable_pub)] + /// Returns `true` if the config key was explicitly set and is the default value. + pub fn is_default(&self, key: &str) -> bool { + $( + if let stringify!($i) = key { + return self.$i.1 && self.$i.2 == $def; + } + )+ + false + } + } + + // Template for the default configuration + impl Default for Config { + fn default() -> Config { + Config { + $( + $i: (Cell::new(false), false, $def, $stb), + )+ + } + } + } + ) +} diff --git a/src/tools/rustfmt/src/config/file_lines.rs b/src/tools/rustfmt/src/config/file_lines.rs new file mode 100644 index 000000000..e4e51a3f3 --- /dev/null +++ b/src/tools/rustfmt/src/config/file_lines.rs @@ -0,0 +1,440 @@ +//! This module contains types and functions to support formatting specific line ranges. + +use itertools::Itertools; +use std::collections::HashMap; +use std::path::PathBuf; +use std::{cmp, fmt, iter, str}; + +use rustc_data_structures::sync::Lrc; +use rustc_span::{self, SourceFile}; +use serde::{ser, Deserialize, Deserializer, Serialize, Serializer}; +use serde_json as json; +use thiserror::Error; + +/// A range of lines in a file, inclusive of both ends. +pub struct LineRange { + pub(crate) file: Lrc<SourceFile>, + pub(crate) lo: usize, + pub(crate) hi: usize, +} + +/// Defines the name of an input - either a file or stdin. +#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)] +pub enum FileName { + Real(PathBuf), + Stdin, +} + +impl From<rustc_span::FileName> for FileName { + fn from(name: rustc_span::FileName) -> FileName { + match name { + rustc_span::FileName::Real(rustc_span::RealFileName::LocalPath(p)) => FileName::Real(p), + rustc_span::FileName::Custom(ref f) if f == "stdin" => FileName::Stdin, + _ => unreachable!(), + } + } +} + +impl fmt::Display for FileName { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + FileName::Real(p) => write!(f, "{}", p.to_str().unwrap()), + FileName::Stdin => write!(f, "<stdin>"), + } + } +} + +impl<'de> Deserialize<'de> for FileName { + fn deserialize<D>(deserializer: D) -> Result<FileName, D::Error> + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + if s == "stdin" { + Ok(FileName::Stdin) + } else { + Ok(FileName::Real(s.into())) + } + } +} + +impl Serialize for FileName { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + let s = match self { + FileName::Stdin => Ok("stdin"), + FileName::Real(path) => path + .to_str() + .ok_or_else(|| ser::Error::custom("path can't be serialized as UTF-8 string")), + }; + + s.and_then(|s| serializer.serialize_str(s)) + } +} + +impl LineRange { + pub(crate) fn file_name(&self) -> FileName { + self.file.name.clone().into() + } +} + +/// A range that is inclusive of both ends. +#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord, Deserialize)] +pub struct Range { + lo: usize, + hi: usize, +} + +impl<'a> From<&'a LineRange> for Range { + fn from(range: &'a LineRange) -> Range { + Range::new(range.lo, range.hi) + } +} + +impl fmt::Display for Range { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}..{}", self.lo, self.hi) + } +} + +impl Range { + pub fn new(lo: usize, hi: usize) -> Range { + Range { lo, hi } + } + + fn is_empty(self) -> bool { + self.lo > self.hi + } + + #[allow(dead_code)] + fn contains(self, other: Range) -> bool { + if other.is_empty() { + true + } else { + !self.is_empty() && self.lo <= other.lo && self.hi >= other.hi + } + } + + fn intersects(self, other: Range) -> bool { + if self.is_empty() || other.is_empty() { + false + } else { + (self.lo <= other.hi && other.hi <= self.hi) + || (other.lo <= self.hi && self.hi <= other.hi) + } + } + + fn adjacent_to(self, other: Range) -> bool { + if self.is_empty() || other.is_empty() { + false + } else { + self.hi + 1 == other.lo || other.hi + 1 == self.lo + } + } + + /// Returns a new `Range` with lines from `self` and `other` if they were adjacent or + /// intersect; returns `None` otherwise. + fn merge(self, other: Range) -> Option<Range> { + if self.adjacent_to(other) || self.intersects(other) { + Some(Range::new( + cmp::min(self.lo, other.lo), + cmp::max(self.hi, other.hi), + )) + } else { + None + } + } +} + +/// A set of lines in files. +/// +/// It is represented as a multimap keyed on file names, with values a collection of +/// non-overlapping ranges sorted by their start point. An inner `None` is interpreted to mean all +/// lines in all files. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FileLines(Option<HashMap<FileName, Vec<Range>>>); + +impl fmt::Display for FileLines { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.0 { + None => write!(f, "None")?, + Some(map) => { + for (file_name, ranges) in map.iter() { + write!(f, "{}: ", file_name)?; + write!(f, "{}\n", ranges.iter().format(", "))?; + } + } + }; + Ok(()) + } +} + +/// Normalizes the ranges so that the invariants for `FileLines` hold: ranges are non-overlapping, +/// and ordered by their start point. +fn normalize_ranges(ranges: &mut HashMap<FileName, Vec<Range>>) { + for ranges in ranges.values_mut() { + ranges.sort(); + let mut result = vec![]; + let mut iter = ranges.iter_mut().peekable(); + while let Some(next) = iter.next() { + let mut next = *next; + while let Some(&&mut peek) = iter.peek() { + if let Some(merged) = next.merge(peek) { + iter.next().unwrap(); + next = merged; + } else { + break; + } + } + result.push(next) + } + *ranges = result; + } +} + +impl FileLines { + /// Creates a `FileLines` that contains all lines in all files. + pub(crate) fn all() -> FileLines { + FileLines(None) + } + + /// Returns `true` if this `FileLines` contains all lines in all files. + pub(crate) fn is_all(&self) -> bool { + self.0.is_none() + } + + pub fn from_ranges(mut ranges: HashMap<FileName, Vec<Range>>) -> FileLines { + normalize_ranges(&mut ranges); + FileLines(Some(ranges)) + } + + /// Returns an iterator over the files contained in `self`. + pub fn files(&self) -> Files<'_> { + Files(self.0.as_ref().map(HashMap::keys)) + } + + /// Returns JSON representation as accepted by the `--file-lines JSON` arg. + pub fn to_json_spans(&self) -> Vec<JsonSpan> { + match &self.0 { + None => vec![], + Some(file_ranges) => file_ranges + .iter() + .flat_map(|(file, ranges)| ranges.iter().map(move |r| (file, r))) + .map(|(file, range)| JsonSpan { + file: file.to_owned(), + range: (range.lo, range.hi), + }) + .collect(), + } + } + + /// Returns `true` if `self` includes all lines in all files. Otherwise runs `f` on all ranges + /// in the designated file (if any) and returns true if `f` ever does. + fn file_range_matches<F>(&self, file_name: &FileName, f: F) -> bool + where + F: FnMut(&Range) -> bool, + { + let map = match self.0 { + // `None` means "all lines in all files". + None => return true, + Some(ref map) => map, + }; + + match canonicalize_path_string(file_name).and_then(|file| map.get(&file)) { + Some(ranges) => ranges.iter().any(f), + None => false, + } + } + + /// Returns `true` if `range` is fully contained in `self`. + #[allow(dead_code)] + pub(crate) fn contains(&self, range: &LineRange) -> bool { + self.file_range_matches(&range.file_name(), |r| r.contains(Range::from(range))) + } + + /// Returns `true` if any lines in `range` are in `self`. + pub(crate) fn intersects(&self, range: &LineRange) -> bool { + self.file_range_matches(&range.file_name(), |r| r.intersects(Range::from(range))) + } + + /// Returns `true` if `line` from `file_name` is in `self`. + pub(crate) fn contains_line(&self, file_name: &FileName, line: usize) -> bool { + self.file_range_matches(file_name, |r| r.lo <= line && r.hi >= line) + } + + /// Returns `true` if all the lines between `lo` and `hi` from `file_name` are in `self`. + pub(crate) fn contains_range(&self, file_name: &FileName, lo: usize, hi: usize) -> bool { + self.file_range_matches(file_name, |r| r.contains(Range::new(lo, hi))) + } +} + +/// `FileLines` files iterator. +pub struct Files<'a>(Option<::std::collections::hash_map::Keys<'a, FileName, Vec<Range>>>); + +impl<'a> iter::Iterator for Files<'a> { + type Item = &'a FileName; + + fn next(&mut self) -> Option<&'a FileName> { + self.0.as_mut().and_then(Iterator::next) + } +} + +fn canonicalize_path_string(file: &FileName) -> Option<FileName> { + match *file { + FileName::Real(ref path) => path.canonicalize().ok().map(FileName::Real), + _ => Some(file.clone()), + } +} + +#[derive(Error, Debug)] +pub enum FileLinesError { + #[error("{0}")] + Json(json::Error), + #[error("Can't canonicalize {0}")] + CannotCanonicalize(FileName), +} + +// This impl is needed for `Config::override_value` to work for use in tests. +impl str::FromStr for FileLines { + type Err = FileLinesError; + + fn from_str(s: &str) -> Result<FileLines, Self::Err> { + let v: Vec<JsonSpan> = json::from_str(s).map_err(FileLinesError::Json)?; + let mut m = HashMap::new(); + for js in v { + let (s, r) = JsonSpan::into_tuple(js)?; + m.entry(s).or_insert_with(Vec::new).push(r); + } + Ok(FileLines::from_ranges(m)) + } +} + +// For JSON decoding. +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)] +pub struct JsonSpan { + file: FileName, + range: (usize, usize), +} + +impl JsonSpan { + fn into_tuple(self) -> Result<(FileName, Range), FileLinesError> { + let (lo, hi) = self.range; + let canonical = canonicalize_path_string(&self.file) + .ok_or(FileLinesError::CannotCanonicalize(self.file))?; + Ok((canonical, Range::new(lo, hi))) + } +} + +// This impl is needed for inclusion in the `Config` struct. We don't have a toml representation +// for `FileLines`, so it will just panic instead. +impl<'de> ::serde::de::Deserialize<'de> for FileLines { + fn deserialize<D>(_: D) -> Result<Self, D::Error> + where + D: ::serde::de::Deserializer<'de>, + { + panic!( + "FileLines cannot be deserialized from a project rustfmt.toml file: please \ + specify it via the `--file-lines` option instead" + ); + } +} + +// We also want to avoid attempting to serialize a FileLines to toml. The +// `Config` struct should ensure this impl is never reached. +impl ::serde::ser::Serialize for FileLines { + fn serialize<S>(&self, _: S) -> Result<S::Ok, S::Error> + where + S: ::serde::ser::Serializer, + { + unreachable!("FileLines cannot be serialized. This is a rustfmt bug."); + } +} + +#[cfg(test)] +mod test { + use super::Range; + + #[test] + fn test_range_intersects() { + assert!(Range::new(1, 2).intersects(Range::new(1, 1))); + assert!(Range::new(1, 2).intersects(Range::new(2, 2))); + assert!(!Range::new(1, 2).intersects(Range::new(0, 0))); + assert!(!Range::new(1, 2).intersects(Range::new(3, 10))); + assert!(!Range::new(1, 3).intersects(Range::new(5, 5))); + } + + #[test] + fn test_range_adjacent_to() { + assert!(!Range::new(1, 2).adjacent_to(Range::new(1, 1))); + assert!(!Range::new(1, 2).adjacent_to(Range::new(2, 2))); + assert!(Range::new(1, 2).adjacent_to(Range::new(0, 0))); + assert!(Range::new(1, 2).adjacent_to(Range::new(3, 10))); + assert!(!Range::new(1, 3).adjacent_to(Range::new(5, 5))); + } + + #[test] + fn test_range_contains() { + assert!(Range::new(1, 2).contains(Range::new(1, 1))); + assert!(Range::new(1, 2).contains(Range::new(2, 2))); + assert!(!Range::new(1, 2).contains(Range::new(0, 0))); + assert!(!Range::new(1, 2).contains(Range::new(3, 10))); + } + + #[test] + fn test_range_merge() { + assert_eq!(None, Range::new(1, 3).merge(Range::new(5, 5))); + assert_eq!(None, Range::new(4, 7).merge(Range::new(0, 1))); + assert_eq!( + Some(Range::new(3, 7)), + Range::new(3, 5).merge(Range::new(4, 7)) + ); + assert_eq!( + Some(Range::new(3, 7)), + Range::new(3, 5).merge(Range::new(5, 7)) + ); + assert_eq!( + Some(Range::new(3, 7)), + Range::new(3, 5).merge(Range::new(6, 7)) + ); + assert_eq!( + Some(Range::new(3, 7)), + Range::new(3, 7).merge(Range::new(4, 5)) + ); + } + + use super::json::{self, json}; + use super::{FileLines, FileName}; + use std::{collections::HashMap, path::PathBuf}; + + #[test] + fn file_lines_to_json() { + let ranges: HashMap<FileName, Vec<Range>> = [ + ( + FileName::Real(PathBuf::from("src/main.rs")), + vec![Range::new(1, 3), Range::new(5, 7)], + ), + ( + FileName::Real(PathBuf::from("src/lib.rs")), + vec![Range::new(1, 7)], + ), + ] + .iter() + .cloned() + .collect(); + + let file_lines = FileLines::from_ranges(ranges); + let mut spans = file_lines.to_json_spans(); + spans.sort(); + let json = json::to_value(&spans).unwrap(); + assert_eq!( + json, + json! {[ + {"file": "src/lib.rs", "range": [1, 7]}, + {"file": "src/main.rs", "range": [1, 3]}, + {"file": "src/main.rs", "range": [5, 7]}, + ]} + ); + } +} diff --git a/src/tools/rustfmt/src/config/lists.rs b/src/tools/rustfmt/src/config/lists.rs new file mode 100644 index 000000000..11cb17068 --- /dev/null +++ b/src/tools/rustfmt/src/config/lists.rs @@ -0,0 +1,92 @@ +//! Configuration options related to rewriting a list. + +use rustfmt_config_proc_macro::config_type; + +use crate::config::IndentStyle; + +/// The definitive formatting tactic for lists. +#[derive(Eq, PartialEq, Debug, Copy, Clone)] +pub enum DefinitiveListTactic { + Vertical, + Horizontal, + Mixed, + /// Special case tactic for `format!()`, `write!()` style macros. + SpecialMacro(usize), +} + +impl DefinitiveListTactic { + pub fn ends_with_newline(&self, indent_style: IndentStyle) -> bool { + match indent_style { + IndentStyle::Block => *self != DefinitiveListTactic::Horizontal, + IndentStyle::Visual => false, + } + } +} + +/// Formatting tactic for lists. This will be cast down to a +/// `DefinitiveListTactic` depending on the number and length of the items and +/// their comments. +#[config_type] +pub enum ListTactic { + /// One item per row. + Vertical, + /// All items on one row. + Horizontal, + /// Try Horizontal layout, if that fails then vertical. + HorizontalVertical, + /// HorizontalVertical with a soft limit of n characters. + LimitedHorizontalVertical(usize), + /// Pack as many items as possible per row over (possibly) many rows. + Mixed, +} + +#[config_type] +pub enum SeparatorTactic { + Always, + Never, + Vertical, +} + +impl SeparatorTactic { + pub fn from_bool(b: bool) -> SeparatorTactic { + if b { + SeparatorTactic::Always + } else { + SeparatorTactic::Never + } + } +} + +/// Where to put separator. +#[config_type] +pub enum SeparatorPlace { + Front, + Back, +} + +impl SeparatorPlace { + pub fn is_front(self) -> bool { + self == SeparatorPlace::Front + } + + pub fn is_back(self) -> bool { + self == SeparatorPlace::Back + } + + pub fn from_tactic( + default: SeparatorPlace, + tactic: DefinitiveListTactic, + sep: &str, + ) -> SeparatorPlace { + match tactic { + DefinitiveListTactic::Vertical => default, + _ => { + if sep == "," { + SeparatorPlace::Back + } else { + default + } + } + } + } +} diff --git a/src/tools/rustfmt/src/config/mod.rs b/src/tools/rustfmt/src/config/mod.rs new file mode 100644 index 000000000..f49c18d3a --- /dev/null +++ b/src/tools/rustfmt/src/config/mod.rs @@ -0,0 +1,924 @@ +use std::cell::Cell; +use std::default::Default; +use std::fs::File; +use std::io::{Error, ErrorKind, Read}; +use std::path::{Path, PathBuf}; +use std::{env, fs}; + +use thiserror::Error; + +use crate::config::config_type::ConfigType; +#[allow(unreachable_pub)] +pub use crate::config::file_lines::{FileLines, FileName, Range}; +#[allow(unreachable_pub)] +pub use crate::config::lists::*; +#[allow(unreachable_pub)] +pub use crate::config::options::*; + +#[macro_use] +pub(crate) mod config_type; +#[macro_use] +pub(crate) mod options; + +pub(crate) mod file_lines; +pub(crate) mod lists; + +// This macro defines configuration options used in rustfmt. Each option +// is defined as follows: +// +// `name: value type, default value, is stable, description;` +create_config! { + // Fundamental stuff + max_width: usize, 100, true, "Maximum width of each line"; + hard_tabs: bool, false, true, "Use tab characters for indentation, spaces for alignment"; + tab_spaces: usize, 4, true, "Number of spaces per tab"; + newline_style: NewlineStyle, NewlineStyle::Auto, true, "Unix or Windows line endings"; + indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items"; + + // Width Heuristics + use_small_heuristics: Heuristics, Heuristics::Default, true, "Whether to use different \ + formatting for items and expressions if they satisfy a heuristic notion of 'small'"; + width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false, + "'small' heuristic values"; + fn_call_width: usize, 60, true, "Maximum width of the args of a function call before \ + falling back to vertical formatting."; + attr_fn_like_width: usize, 70, true, "Maximum width of the args of a function-like \ + attributes before falling back to vertical formatting."; + struct_lit_width: usize, 18, true, "Maximum width in the body of a struct lit before \ + falling back to vertical formatting."; + struct_variant_width: usize, 35, true, "Maximum width in the body of a struct variant before \ + falling back to vertical formatting."; + array_width: usize, 60, true, "Maximum width of an array literal before falling \ + back to vertical formatting."; + chain_width: usize, 60, true, "Maximum length of a chain to fit on a single line."; + single_line_if_else_max_width: usize, 50, true, "Maximum line length for single line if-else \ + expressions. A value of zero means always break if-else expressions."; + + // Comments. macros, and strings + wrap_comments: bool, false, false, "Break comments to fit on the line"; + format_code_in_doc_comments: bool, false, false, "Format the code snippet in doc comments."; + doc_comment_code_block_width: usize, 100, false, "Maximum width for code snippets in doc \ + comments. No effect unless format_code_in_doc_comments = true"; + comment_width: usize, 80, false, + "Maximum length of comments. No effect unless wrap_comments = true"; + normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible"; + normalize_doc_attributes: bool, false, false, "Normalize doc attributes as doc comments"; + format_strings: bool, false, false, "Format string literals where necessary"; + format_macro_matchers: bool, false, false, + "Format the metavariable matching patterns in macros"; + format_macro_bodies: bool, true, false, "Format the bodies of macros"; + hex_literal_case: HexLiteralCase, HexLiteralCase::Preserve, false, + "Format hexadecimal integer literals"; + + // Single line expressions and items + empty_item_single_line: bool, true, false, + "Put empty-body functions and impls on a single line"; + struct_lit_single_line: bool, true, false, + "Put small struct literals on a single line"; + fn_single_line: bool, false, false, "Put single-expression functions on a single line"; + where_single_line: bool, false, false, "Force where-clauses to be on a single line"; + + // Imports + imports_indent: IndentStyle, IndentStyle::Block, false, "Indent of imports"; + imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block"; + imports_granularity: ImportGranularity, ImportGranularity::Preserve, false, + "Merge or split imports to the provided granularity"; + group_imports: GroupImportsTactic, GroupImportsTactic::Preserve, false, + "Controls the strategy for how imports are grouped together"; + merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)"; + + // Ordering + reorder_imports: bool, true, true, "Reorder import and extern crate statements alphabetically"; + reorder_modules: bool, true, true, "Reorder module statements alphabetically in group"; + reorder_impl_items: bool, false, false, "Reorder impl items"; + + // Spaces around punctuation + type_punctuation_density: TypeDensity, TypeDensity::Wide, false, + "Determines if '+' or '=' are wrapped in spaces in the punctuation of types"; + space_before_colon: bool, false, false, "Leave a space before the colon"; + space_after_colon: bool, true, false, "Leave a space after the colon"; + spaces_around_ranges: bool, false, false, "Put spaces around the .. and ..= range operators"; + binop_separator: SeparatorPlace, SeparatorPlace::Front, false, + "Where to put a binary operator when a binary expression goes multiline"; + + // Misc. + remove_nested_parens: bool, true, true, "Remove nested parens"; + combine_control_expr: bool, true, false, "Combine control expressions with function calls"; + short_array_element_width_threshold: usize, 10, true, + "Width threshold for an array element to be considered short"; + overflow_delimited_expr: bool, false, false, + "Allow trailing bracket/brace delimited expressions to overflow"; + struct_field_align_threshold: usize, 0, false, + "Align struct fields if their diffs fits within threshold"; + enum_discrim_align_threshold: usize, 0, false, + "Align enum variants discrims, if their diffs fit within threshold"; + match_arm_blocks: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \ + the same line with the pattern of arms"; + match_arm_leading_pipes: MatchArmLeadingPipe, MatchArmLeadingPipe::Never, true, + "Determines whether leading pipes are emitted on match arms"; + force_multiline_blocks: bool, false, false, + "Force multiline closure bodies and match arms to be wrapped in a block"; + fn_args_layout: Density, Density::Tall, true, + "Control the layout of arguments in a function"; + brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items"; + control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false, + "Brace style for control flow constructs"; + trailing_semicolon: bool, true, false, + "Add trailing semicolon after break, continue and return"; + trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false, + "How to handle trailing commas for lists"; + match_block_trailing_comma: bool, false, true, + "Put a trailing comma after a block based match arm (non-block arms are not affected)"; + blank_lines_upper_bound: usize, 1, false, + "Maximum number of blank lines which can be put between items"; + blank_lines_lower_bound: usize, 0, false, + "Minimum number of blank lines which must be put between items"; + edition: Edition, Edition::Edition2015, true, "The edition of the parser (RFC 2052)"; + version: Version, Version::One, false, "Version of formatting rules"; + inline_attribute_width: usize, 0, false, + "Write an item and its attribute on the same line \ + if their combined width is below a threshold"; + format_generated_files: bool, true, false, "Format generated files"; + + // Options that can change the source code beyond whitespace/blocks (somewhat linty things) + merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one"; + use_try_shorthand: bool, false, true, "Replace uses of the try! macro by the ? shorthand"; + use_field_init_shorthand: bool, false, true, "Use field initialization shorthand if possible"; + force_explicit_abi: bool, true, true, "Always print the abi for extern items"; + condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \ + in tuple patterns"; + + // Control options (changes the operation of rustfmt, rather than the formatting) + color: Color, Color::Auto, false, + "What Color option to use when none is supplied: Always, Never, Auto"; + required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false, + "Require a specific version of rustfmt"; + unstable_features: bool, false, false, + "Enables unstable features. Only available on nightly channel"; + disable_all_formatting: bool, false, true, "Don't reformat anything"; + skip_children: bool, false, false, "Don't reformat out of line modules"; + hide_parse_errors: bool, false, false, "Hide errors from the parser"; + error_on_line_overflow: bool, false, false, "Error if unable to get all lines within max_width"; + error_on_unformatted: bool, false, false, + "Error if unable to get comments or string literals within max_width, \ + or they are left with trailing whitespaces"; + ignore: IgnoreList, IgnoreList::default(), false, + "Skip formatting the specified files and directories"; + + // Not user-facing + verbose: Verbosity, Verbosity::Normal, false, "How much to information to emit to the user"; + file_lines: FileLines, FileLines::all(), false, + "Lines to format; this is not supported in rustfmt.toml, and can only be specified \ + via the --file-lines option"; + emit_mode: EmitMode, EmitMode::Files, false, + "What emit Mode to use when none is supplied"; + make_backup: bool, false, false, "Backup changed files"; + print_misformatted_file_names: bool, false, true, + "Prints the names of mismatched files that were formatted. Prints the names of \ + files that would be formated when used with `--check` mode. "; +} + +#[derive(Error, Debug)] +#[error("Could not output config: {0}")] +pub struct ToTomlError(toml::ser::Error); + +impl PartialConfig { + pub fn to_toml(&self) -> Result<String, ToTomlError> { + // Non-user-facing options can't be specified in TOML + let mut cloned = self.clone(); + cloned.file_lines = None; + cloned.verbose = None; + cloned.width_heuristics = None; + cloned.print_misformatted_file_names = None; + cloned.merge_imports = None; + + ::toml::to_string(&cloned).map_err(ToTomlError) + } +} + +impl Config { + pub(crate) fn version_meets_requirement(&self) -> bool { + if self.was_set().required_version() { + let version = env!("CARGO_PKG_VERSION"); + let required_version = self.required_version(); + if version != required_version { + println!( + "Error: rustfmt version ({}) doesn't match the required version ({})", + version, required_version, + ); + return false; + } + } + + true + } + + /// Constructs a `Config` from the toml file specified at `file_path`. + /// + /// This method only looks at the provided path, for a method that + /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`. + /// + /// Returns a `Config` if the config could be read and parsed from + /// the file, otherwise errors. + pub(super) fn from_toml_path(file_path: &Path) -> Result<Config, Error> { + let mut file = File::open(&file_path)?; + let mut toml = String::new(); + file.read_to_string(&mut toml)?; + Config::from_toml(&toml, file_path.parent().unwrap()) + .map_err(|err| Error::new(ErrorKind::InvalidData, err)) + } + + /// Resolves the config for input in `dir`. + /// + /// Searches for `rustfmt.toml` beginning with `dir`, and + /// recursively checking parents of `dir` if no config file is found. + /// If no config file exists in `dir` or in any parent, a + /// default `Config` will be returned (and the returned path will be empty). + /// + /// Returns the `Config` to use, and the path of the project file if there was + /// one. + pub(super) fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> { + /// Try to find a project file in the given directory and its parents. + /// Returns the path of a the nearest project file if one exists, + /// or `None` if no project file was found. + fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> { + let mut current = if dir.is_relative() { + env::current_dir()?.join(dir) + } else { + dir.to_path_buf() + }; + + current = fs::canonicalize(current)?; + + loop { + match get_toml_path(¤t) { + Ok(Some(path)) => return Ok(Some(path)), + Err(e) => return Err(e), + _ => (), + } + + // If the current directory has no parent, we're done searching. + if !current.pop() { + break; + } + } + + // If nothing was found, check in the home directory. + if let Some(home_dir) = dirs::home_dir() { + if let Some(path) = get_toml_path(&home_dir)? { + return Ok(Some(path)); + } + } + + // If none was found ther either, check in the user's configuration directory. + if let Some(mut config_dir) = dirs::config_dir() { + config_dir.push("rustfmt"); + if let Some(path) = get_toml_path(&config_dir)? { + return Ok(Some(path)); + } + } + + Ok(None) + } + + match resolve_project_file(dir)? { + None => Ok((Config::default(), None)), + Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))), + } + } + + pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> { + let parsed: ::toml::Value = toml + .parse() + .map_err(|e| format!("Could not parse TOML: {}", e))?; + let mut err = String::new(); + let table = parsed + .as_table() + .ok_or_else(|| String::from("Parsed config was not table"))?; + for key in table.keys() { + if !Config::is_valid_name(key) { + let msg = &format!("Warning: Unknown configuration option `{}`\n", key); + err.push_str(msg) + } + } + match parsed.try_into() { + Ok(parsed_config) => { + if !err.is_empty() { + eprint!("{}", err); + } + Ok(Config::default().fill_from_parsed_config(parsed_config, dir)) + } + Err(e) => { + err.push_str("Error: Decoding config file failed:\n"); + err.push_str(format!("{}\n", e).as_str()); + err.push_str("Please check your config file."); + Err(err) + } + } + } +} + +/// Loads a config by checking the client-supplied options and if appropriate, the +/// file system (including searching the file system for overrides). +pub fn load_config<O: CliOptions>( + file_path: Option<&Path>, + options: Option<O>, +) -> Result<(Config, Option<PathBuf>), Error> { + let over_ride = match options { + Some(ref opts) => config_path(opts)?, + None => None, + }; + + let result = if let Some(over_ride) = over_ride { + Config::from_toml_path(over_ride.as_ref()).map(|p| (p, Some(over_ride.to_owned()))) + } else if let Some(file_path) = file_path { + Config::from_resolved_toml_path(file_path) + } else { + Ok((Config::default(), None)) + }; + + result.map(|(mut c, p)| { + if let Some(options) = options { + options.apply_to(&mut c); + } + (c, p) + }) +} + +// Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir` +// +// Return the path if a config file exists, empty if no file exists, and Error for IO errors +fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> { + const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"]; + for config_file_name in &CONFIG_FILE_NAMES { + let config_file = dir.join(config_file_name); + match fs::metadata(&config_file) { + // Only return if it's a file to handle the unlikely situation of a directory named + // `rustfmt.toml`. + Ok(ref md) if md.is_file() => return Ok(Some(config_file)), + // Return the error if it's something other than `NotFound`; otherwise we didn't + // find the project file yet, and continue searching. + Err(e) => { + if e.kind() != ErrorKind::NotFound { + let ctx = format!("Failed to get metadata for config file {:?}", &config_file); + let err = anyhow::Error::new(e).context(ctx); + return Err(Error::new(ErrorKind::Other, err)); + } + } + _ => {} + } + } + Ok(None) +} + +fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> { + let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> { + Err(Error::new( + ErrorKind::NotFound, + format!( + "Error: unable to find a config file for the given path: `{}`", + path + ), + )) + }; + + // Read the config_path and convert to parent dir if a file is provided. + // If a config file cannot be found from the given path, return error. + match options.config_path() { + Some(path) if !path.exists() => config_path_not_found(path.to_str().unwrap()), + Some(path) if path.is_dir() => { + let config_file_path = get_toml_path(path)?; + if config_file_path.is_some() { + Ok(config_file_path) + } else { + config_path_not_found(path.to_str().unwrap()) + } + } + path => Ok(path.map(ToOwned::to_owned)), + } +} + +#[cfg(test)] +mod test { + use super::*; + use std::str; + + use rustfmt_config_proc_macro::{nightly_only_test, stable_only_test}; + + #[allow(dead_code)] + mod mock { + use super::super::*; + + create_config! { + // Options that are used by the generated functions + max_width: usize, 100, true, "Maximum width of each line"; + required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false, + "Require a specific version of rustfmt."; + ignore: IgnoreList, IgnoreList::default(), false, + "Skip formatting the specified files and directories."; + verbose: Verbosity, Verbosity::Normal, false, + "How much to information to emit to the user"; + file_lines: FileLines, FileLines::all(), false, + "Lines to format; this is not supported in rustfmt.toml, and can only be specified \ + via the --file-lines option"; + + // merge_imports deprecation + imports_granularity: ImportGranularity, ImportGranularity::Preserve, false, + "Merge imports"; + merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)"; + + // Width Heuristics + use_small_heuristics: Heuristics, Heuristics::Default, true, + "Whether to use different formatting for items and \ + expressions if they satisfy a heuristic notion of 'small'."; + width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false, + "'small' heuristic values"; + + fn_call_width: usize, 60, true, "Maximum width of the args of a function call before \ + falling back to vertical formatting."; + attr_fn_like_width: usize, 70, true, "Maximum width of the args of a function-like \ + attributes before falling back to vertical formatting."; + struct_lit_width: usize, 18, true, "Maximum width in the body of a struct lit before \ + falling back to vertical formatting."; + struct_variant_width: usize, 35, true, "Maximum width in the body of a struct \ + variant before falling back to vertical formatting."; + array_width: usize, 60, true, "Maximum width of an array literal before falling \ + back to vertical formatting."; + chain_width: usize, 60, true, "Maximum length of a chain to fit on a single line."; + single_line_if_else_max_width: usize, 50, true, "Maximum line length for single \ + line if-else expressions. A value of zero means always break if-else expressions."; + + // Options that are used by the tests + stable_option: bool, false, true, "A stable option"; + unstable_option: bool, false, false, "An unstable option"; + } + } + + #[test] + fn test_config_set() { + let mut config = Config::default(); + config.set().verbose(Verbosity::Quiet); + assert_eq!(config.verbose(), Verbosity::Quiet); + config.set().verbose(Verbosity::Normal); + assert_eq!(config.verbose(), Verbosity::Normal); + } + + #[test] + fn test_config_used_to_toml() { + let config = Config::default(); + + let merge_derives = config.merge_derives(); + let skip_children = config.skip_children(); + + let used_options = config.used_options(); + let toml = used_options.to_toml().unwrap(); + assert_eq!( + toml, + format!( + "merge_derives = {}\nskip_children = {}\n", + merge_derives, skip_children, + ) + ); + } + + #[test] + fn test_was_set() { + let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap(); + + assert_eq!(config.was_set().hard_tabs(), true); + assert_eq!(config.was_set().verbose(), false); + } + + #[test] + fn test_print_docs_exclude_unstable() { + use self::mock::Config; + + let mut output = Vec::new(); + Config::print_docs(&mut output, false); + + let s = str::from_utf8(&output).unwrap(); + + assert_eq!(s.contains("stable_option"), true); + assert_eq!(s.contains("unstable_option"), false); + assert_eq!(s.contains("(unstable)"), false); + } + + #[test] + fn test_print_docs_include_unstable() { + use self::mock::Config; + + let mut output = Vec::new(); + Config::print_docs(&mut output, true); + + let s = str::from_utf8(&output).unwrap(); + assert_eq!(s.contains("stable_option"), true); + assert_eq!(s.contains("unstable_option"), true); + assert_eq!(s.contains("(unstable)"), true); + } + + #[test] + fn test_dump_default_config() { + let default_config = format!( + r#"max_width = 100 +hard_tabs = false +tab_spaces = 4 +newline_style = "Auto" +indent_style = "Block" +use_small_heuristics = "Default" +fn_call_width = 60 +attr_fn_like_width = 70 +struct_lit_width = 18 +struct_variant_width = 35 +array_width = 60 +chain_width = 60 +single_line_if_else_max_width = 50 +wrap_comments = false +format_code_in_doc_comments = false +doc_comment_code_block_width = 100 +comment_width = 80 +normalize_comments = false +normalize_doc_attributes = false +format_strings = false +format_macro_matchers = false +format_macro_bodies = true +hex_literal_case = "Preserve" +empty_item_single_line = true +struct_lit_single_line = true +fn_single_line = false +where_single_line = false +imports_indent = "Block" +imports_layout = "Mixed" +imports_granularity = "Preserve" +group_imports = "Preserve" +reorder_imports = true +reorder_modules = true +reorder_impl_items = false +type_punctuation_density = "Wide" +space_before_colon = false +space_after_colon = true +spaces_around_ranges = false +binop_separator = "Front" +remove_nested_parens = true +combine_control_expr = true +short_array_element_width_threshold = 10 +overflow_delimited_expr = false +struct_field_align_threshold = 0 +enum_discrim_align_threshold = 0 +match_arm_blocks = true +match_arm_leading_pipes = "Never" +force_multiline_blocks = false +fn_args_layout = "Tall" +brace_style = "SameLineWhere" +control_brace_style = "AlwaysSameLine" +trailing_semicolon = true +trailing_comma = "Vertical" +match_block_trailing_comma = false +blank_lines_upper_bound = 1 +blank_lines_lower_bound = 0 +edition = "2015" +version = "One" +inline_attribute_width = 0 +format_generated_files = true +merge_derives = true +use_try_shorthand = false +use_field_init_shorthand = false +force_explicit_abi = true +condense_wildcard_suffixes = false +color = "Auto" +required_version = "{}" +unstable_features = false +disable_all_formatting = false +skip_children = false +hide_parse_errors = false +error_on_line_overflow = false +error_on_unformatted = false +ignore = [] +emit_mode = "Files" +make_backup = false +"#, + env!("CARGO_PKG_VERSION") + ); + let toml = Config::default().all_options().to_toml().unwrap(); + assert_eq!(&toml, &default_config); + } + + #[stable_only_test] + #[test] + fn test_as_not_nightly_channel() { + let mut config = Config::default(); + assert_eq!(config.was_set().unstable_features(), false); + config.set().unstable_features(true); + assert_eq!(config.was_set().unstable_features(), false); + } + + #[nightly_only_test] + #[test] + fn test_as_nightly_channel() { + let mut config = Config::default(); + config.set().unstable_features(true); + // When we don't set the config from toml or command line options it + // doesn't get marked as set by the user. + assert_eq!(config.was_set().unstable_features(), false); + config.set().unstable_features(true); + assert_eq!(config.unstable_features(), true); + } + + #[nightly_only_test] + #[test] + fn test_unstable_from_toml() { + let config = Config::from_toml("unstable_features = true", Path::new("")).unwrap(); + assert_eq!(config.was_set().unstable_features(), true); + assert_eq!(config.unstable_features(), true); + } + + #[cfg(test)] + mod deprecated_option_merge_imports { + use super::*; + + #[nightly_only_test] + #[test] + fn test_old_option_set() { + let toml = r#" + unstable_features = true + merge_imports = true + "#; + let config = Config::from_toml(toml, Path::new("")).unwrap(); + assert_eq!(config.imports_granularity(), ImportGranularity::Crate); + } + + #[nightly_only_test] + #[test] + fn test_both_set() { + let toml = r#" + unstable_features = true + merge_imports = true + imports_granularity = "Preserve" + "#; + let config = Config::from_toml(toml, Path::new("")).unwrap(); + assert_eq!(config.imports_granularity(), ImportGranularity::Preserve); + } + + #[nightly_only_test] + #[test] + fn test_new_overridden() { + let toml = r#" + unstable_features = true + merge_imports = true + "#; + let mut config = Config::from_toml(toml, Path::new("")).unwrap(); + config.override_value("imports_granularity", "Preserve"); + assert_eq!(config.imports_granularity(), ImportGranularity::Preserve); + } + + #[nightly_only_test] + #[test] + fn test_old_overridden() { + let toml = r#" + unstable_features = true + imports_granularity = "Module" + "#; + let mut config = Config::from_toml(toml, Path::new("")).unwrap(); + config.override_value("merge_imports", "true"); + // no effect: the new option always takes precedence + assert_eq!(config.imports_granularity(), ImportGranularity::Module); + } + } + + #[cfg(test)] + mod use_small_heuristics { + use super::*; + + #[test] + fn test_default_sets_correct_widths() { + let toml = r#" + use_small_heuristics = "Default" + max_width = 200 + "#; + let config = Config::from_toml(toml, Path::new("")).unwrap(); + assert_eq!(config.array_width(), 120); + assert_eq!(config.attr_fn_like_width(), 140); + assert_eq!(config.chain_width(), 120); + assert_eq!(config.fn_call_width(), 120); + assert_eq!(config.single_line_if_else_max_width(), 100); + assert_eq!(config.struct_lit_width(), 36); + assert_eq!(config.struct_variant_width(), 70); + } + + #[test] + fn test_max_sets_correct_widths() { + let toml = r#" + use_small_heuristics = "Max" + max_width = 120 + "#; + let config = Config::from_toml(toml, Path::new("")).unwrap(); + assert_eq!(config.array_width(), 120); + assert_eq!(config.attr_fn_like_width(), 120); + assert_eq!(config.chain_width(), 120); + assert_eq!(config.fn_call_width(), 120); + assert_eq!(config.single_line_if_else_max_width(), 120); + assert_eq!(config.struct_lit_width(), 120); + assert_eq!(config.struct_variant_width(), 120); + } + + #[test] + fn test_off_sets_correct_widths() { + let toml = r#" + use_small_heuristics = "Off" + max_width = 100 + "#; + let config = Config::from_toml(toml, Path::new("")).unwrap(); + assert_eq!(config.array_width(), usize::max_value()); + assert_eq!(config.attr_fn_like_width(), usize::max_value()); + assert_eq!(config.chain_width(), usize::max_value()); + assert_eq!(config.fn_call_width(), usize::max_value()); + assert_eq!(config.single_line_if_else_max_width(), 0); + assert_eq!(config.struct_lit_width(), 0); + assert_eq!(config.struct_variant_width(), 0); + } + + #[test] + fn test_override_works_with_default() { + let toml = r#" + use_small_heuristics = "Default" + array_width = 20 + attr_fn_like_width = 40 + chain_width = 20 + fn_call_width = 90 + single_line_if_else_max_width = 40 + struct_lit_width = 30 + struct_variant_width = 34 + "#; + let config = Config::from_toml(toml, Path::new("")).unwrap(); + assert_eq!(config.array_width(), 20); + assert_eq!(config.attr_fn_like_width(), 40); + assert_eq!(config.chain_width(), 20); + assert_eq!(config.fn_call_width(), 90); + assert_eq!(config.single_line_if_else_max_width(), 40); + assert_eq!(config.struct_lit_width(), 30); + assert_eq!(config.struct_variant_width(), 34); + } + + #[test] + fn test_override_with_max() { + let toml = r#" + use_small_heuristics = "Max" + array_width = 20 + attr_fn_like_width = 40 + chain_width = 20 + fn_call_width = 90 + single_line_if_else_max_width = 40 + struct_lit_width = 30 + struct_variant_width = 34 + "#; + let config = Config::from_toml(toml, Path::new("")).unwrap(); + assert_eq!(config.array_width(), 20); + assert_eq!(config.attr_fn_like_width(), 40); + assert_eq!(config.chain_width(), 20); + assert_eq!(config.fn_call_width(), 90); + assert_eq!(config.single_line_if_else_max_width(), 40); + assert_eq!(config.struct_lit_width(), 30); + assert_eq!(config.struct_variant_width(), 34); + } + + #[test] + fn test_override_with_off() { + let toml = r#" + use_small_heuristics = "Off" + array_width = 20 + attr_fn_like_width = 40 + chain_width = 20 + fn_call_width = 90 + single_line_if_else_max_width = 40 + struct_lit_width = 30 + struct_variant_width = 34 + "#; + let config = Config::from_toml(toml, Path::new("")).unwrap(); + assert_eq!(config.array_width(), 20); + assert_eq!(config.attr_fn_like_width(), 40); + assert_eq!(config.chain_width(), 20); + assert_eq!(config.fn_call_width(), 90); + assert_eq!(config.single_line_if_else_max_width(), 40); + assert_eq!(config.struct_lit_width(), 30); + assert_eq!(config.struct_variant_width(), 34); + } + + #[test] + fn test_fn_call_width_config_exceeds_max_width() { + let toml = r#" + max_width = 90 + fn_call_width = 95 + "#; + let config = Config::from_toml(toml, Path::new("")).unwrap(); + assert_eq!(config.fn_call_width(), 90); + } + + #[test] + fn test_attr_fn_like_width_config_exceeds_max_width() { + let toml = r#" + max_width = 80 + attr_fn_like_width = 90 + "#; + let config = Config::from_toml(toml, Path::new("")).unwrap(); + assert_eq!(config.attr_fn_like_width(), 80); + } + + #[test] + fn test_struct_lit_config_exceeds_max_width() { + let toml = r#" + max_width = 78 + struct_lit_width = 90 + "#; + let config = Config::from_toml(toml, Path::new("")).unwrap(); + assert_eq!(config.struct_lit_width(), 78); + } + + #[test] + fn test_struct_variant_width_config_exceeds_max_width() { + let toml = r#" + max_width = 80 + struct_variant_width = 90 + "#; + let config = Config::from_toml(toml, Path::new("")).unwrap(); + assert_eq!(config.struct_variant_width(), 80); + } + + #[test] + fn test_array_width_config_exceeds_max_width() { + let toml = r#" + max_width = 60 + array_width = 80 + "#; + let config = Config::from_toml(toml, Path::new("")).unwrap(); + assert_eq!(config.array_width(), 60); + } + + #[test] + fn test_chain_width_config_exceeds_max_width() { + let toml = r#" + max_width = 80 + chain_width = 90 + "#; + let config = Config::from_toml(toml, Path::new("")).unwrap(); + assert_eq!(config.chain_width(), 80); + } + + #[test] + fn test_single_line_if_else_max_width_config_exceeds_max_width() { + let toml = r#" + max_width = 70 + single_line_if_else_max_width = 90 + "#; + let config = Config::from_toml(toml, Path::new("")).unwrap(); + assert_eq!(config.single_line_if_else_max_width(), 70); + } + + #[test] + fn test_override_fn_call_width_exceeds_max_width() { + let mut config = Config::default(); + config.override_value("fn_call_width", "101"); + assert_eq!(config.fn_call_width(), 100); + } + + #[test] + fn test_override_attr_fn_like_width_exceeds_max_width() { + let mut config = Config::default(); + config.override_value("attr_fn_like_width", "101"); + assert_eq!(config.attr_fn_like_width(), 100); + } + + #[test] + fn test_override_struct_lit_exceeds_max_width() { + let mut config = Config::default(); + config.override_value("struct_lit_width", "101"); + assert_eq!(config.struct_lit_width(), 100); + } + + #[test] + fn test_override_struct_variant_width_exceeds_max_width() { + let mut config = Config::default(); + config.override_value("struct_variant_width", "101"); + assert_eq!(config.struct_variant_width(), 100); + } + + #[test] + fn test_override_array_width_exceeds_max_width() { + let mut config = Config::default(); + config.override_value("array_width", "101"); + assert_eq!(config.array_width(), 100); + } + + #[test] + fn test_override_chain_width_exceeds_max_width() { + let mut config = Config::default(); + config.override_value("chain_width", "101"); + assert_eq!(config.chain_width(), 100); + } + + #[test] + fn test_override_single_line_if_else_max_width_exceeds_max_width() { + let mut config = Config::default(); + config.override_value("single_line_if_else_max_width", "101"); + assert_eq!(config.single_line_if_else_max_width(), 100); + } + } +} diff --git a/src/tools/rustfmt/src/config/options.rs b/src/tools/rustfmt/src/config/options.rs new file mode 100644 index 000000000..257a17b27 --- /dev/null +++ b/src/tools/rustfmt/src/config/options.rs @@ -0,0 +1,464 @@ +use std::collections::{hash_set, HashSet}; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; + +use itertools::Itertools; +use rustfmt_config_proc_macro::config_type; +use serde::de::{SeqAccess, Visitor}; +use serde::ser::SerializeSeq; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +use crate::config::lists::*; +use crate::config::Config; + +#[config_type] +pub enum NewlineStyle { + /// Auto-detect based on the raw source input. + Auto, + /// Force CRLF (`\r\n`). + Windows, + /// Force CR (`\n). + Unix, + /// `\r\n` in Windows, `\n` on other platforms. + Native, +} + +#[config_type] +/// Where to put the opening brace of items (`fn`, `impl`, etc.). +pub enum BraceStyle { + /// Put the opening brace on the next line. + AlwaysNextLine, + /// Put the opening brace on the same line, if possible. + PreferSameLine, + /// Prefer the same line except where there is a where-clause, in which + /// case force the brace to be put on the next line. + SameLineWhere, +} + +#[config_type] +/// Where to put the opening brace of conditional expressions (`if`, `match`, etc.). +pub enum ControlBraceStyle { + /// K&R style, Rust community default + AlwaysSameLine, + /// Stroustrup style + ClosingNextLine, + /// Allman style + AlwaysNextLine, +} + +#[config_type] +/// How to indent. +pub enum IndentStyle { + /// First line on the same line as the opening brace, all lines aligned with + /// the first line. + Visual, + /// First line is on a new line and all lines align with **block** indent. + Block, +} + +#[config_type] +/// How to place a list-like items. +/// FIXME: Issue-3581: this should be renamed to ItemsLayout when publishing 2.0 +pub enum Density { + /// Fit as much on one line as possible. + Compressed, + /// Items are placed horizontally if sufficient space, vertically otherwise. + Tall, + /// Place every item on a separate line. + Vertical, +} + +#[config_type] +/// Spacing around type combinators. +pub enum TypeDensity { + /// No spaces around "=" and "+" + Compressed, + /// Spaces around " = " and " + " + Wide, +} + +#[config_type] +/// Heuristic settings that can be used to simply +/// the configuration of the granular width configurations +/// like `struct_lit_width`, `array_width`, etc. +pub enum Heuristics { + /// Turn off any heuristics + Off, + /// Turn on max heuristics + Max, + /// Use scaled values based on the value of `max_width` + Default, +} + +impl Density { + pub fn to_list_tactic(self, len: usize) -> ListTactic { + match self { + Density::Compressed => ListTactic::Mixed, + Density::Tall => ListTactic::HorizontalVertical, + Density::Vertical if len == 1 => ListTactic::Horizontal, + Density::Vertical => ListTactic::Vertical, + } + } +} + +#[config_type] +/// Configuration for import groups, i.e. sets of imports separated by newlines. +pub enum GroupImportsTactic { + /// Keep groups as they are. + Preserve, + /// Discard existing groups, and create new groups for + /// 1. `std` / `core` / `alloc` imports + /// 2. other imports + /// 3. `self` / `crate` / `super` imports + StdExternalCrate, + /// Discard existing groups, and create a single group for everything + One, +} + +#[config_type] +/// How to merge imports. +pub enum ImportGranularity { + /// Do not merge imports. + Preserve, + /// Use one `use` statement per crate. + Crate, + /// Use one `use` statement per module. + Module, + /// Use one `use` statement per imported item. + Item, + /// Use one `use` statement including all items. + One, +} + +/// Controls how rustfmt should handle case in hexadecimal literals. +#[config_type] +pub enum HexLiteralCase { + /// Leave the literal as-is + Preserve, + /// Ensure all literals use uppercase lettering + Upper, + /// Ensure all literals use lowercase lettering + Lower, +} + +#[config_type] +pub enum ReportTactic { + Always, + Unnumbered, + Never, +} + +/// What Rustfmt should emit. Mostly corresponds to the `--emit` command line +/// option. +#[config_type] +pub enum EmitMode { + /// Emits to files. + Files, + /// Writes the output to stdout. + Stdout, + /// Displays how much of the input file was processed + Coverage, + /// Unfancy stdout + Checkstyle, + /// Writes the resulting diffs in a JSON format. Returns an empty array + /// `[]` if there were no diffs. + Json, + /// Output the changed lines (for internal value only) + ModifiedLines, + /// Checks if a diff can be generated. If so, rustfmt outputs a diff and + /// quits with exit code 1. + /// This option is designed to be run in CI where a non-zero exit signifies + /// non-standard code formatting. Used for `--check`. + Diff, +} + +/// Client-preference for coloured output. +#[config_type] +pub enum Color { + /// Always use color, whether it is a piped or terminal output + Always, + /// Never use color + Never, + /// Automatically use color, if supported by terminal + Auto, +} + +#[config_type] +/// rustfmt format style version. +pub enum Version { + /// 1.x.y. When specified, rustfmt will format in the same style as 1.0.0. + One, + /// 2.x.y. When specified, rustfmt will format in the the latest style. + Two, +} + +impl Color { + /// Whether we should use a coloured terminal. + pub fn use_colored_tty(self) -> bool { + match self { + Color::Always | Color::Auto => true, + Color::Never => false, + } + } +} + +/// How chatty should Rustfmt be? +#[config_type] +pub enum Verbosity { + /// Emit more. + Verbose, + /// Default. + Normal, + /// Emit as little as possible. + Quiet, +} + +#[derive(Deserialize, Serialize, Clone, Debug, PartialEq)] +pub struct WidthHeuristics { + // Maximum width of the args of a function call before falling back + // to vertical formatting. + pub(crate) fn_call_width: usize, + // Maximum width of the args of a function-like attributes before falling + // back to vertical formatting. + pub(crate) attr_fn_like_width: usize, + // Maximum width in the body of a struct lit before falling back to + // vertical formatting. + pub(crate) struct_lit_width: usize, + // Maximum width in the body of a struct variant before falling back + // to vertical formatting. + pub(crate) struct_variant_width: usize, + // Maximum width of an array literal before falling back to vertical + // formatting. + pub(crate) array_width: usize, + // Maximum length of a chain to fit on a single line. + pub(crate) chain_width: usize, + // Maximum line length for single line if-else expressions. A value + // of zero means always break if-else expressions. + pub(crate) single_line_if_else_max_width: usize, +} + +impl fmt::Display for WidthHeuristics { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}", self) + } +} + +impl WidthHeuristics { + // Using this WidthHeuristics means we ignore heuristics. + pub fn null() -> WidthHeuristics { + WidthHeuristics { + fn_call_width: usize::max_value(), + attr_fn_like_width: usize::max_value(), + struct_lit_width: 0, + struct_variant_width: 0, + array_width: usize::max_value(), + chain_width: usize::max_value(), + single_line_if_else_max_width: 0, + } + } + + pub fn set(max_width: usize) -> WidthHeuristics { + WidthHeuristics { + fn_call_width: max_width, + attr_fn_like_width: max_width, + struct_lit_width: max_width, + struct_variant_width: max_width, + array_width: max_width, + chain_width: max_width, + single_line_if_else_max_width: max_width, + } + } + + // scale the default WidthHeuristics according to max_width + pub fn scaled(max_width: usize) -> WidthHeuristics { + const DEFAULT_MAX_WIDTH: usize = 100; + let max_width_ratio = if max_width > DEFAULT_MAX_WIDTH { + let ratio = max_width as f32 / DEFAULT_MAX_WIDTH as f32; + // round to the closest 0.1 + (ratio * 10.0).round() / 10.0 + } else { + 1.0 + }; + WidthHeuristics { + fn_call_width: (60.0 * max_width_ratio).round() as usize, + attr_fn_like_width: (70.0 * max_width_ratio).round() as usize, + struct_lit_width: (18.0 * max_width_ratio).round() as usize, + struct_variant_width: (35.0 * max_width_ratio).round() as usize, + array_width: (60.0 * max_width_ratio).round() as usize, + chain_width: (60.0 * max_width_ratio).round() as usize, + single_line_if_else_max_width: (50.0 * max_width_ratio).round() as usize, + } + } +} + +impl ::std::str::FromStr for WidthHeuristics { + type Err = &'static str; + + fn from_str(_: &str) -> Result<Self, Self::Err> { + Err("WidthHeuristics is not parsable") + } +} + +impl Default for EmitMode { + fn default() -> EmitMode { + EmitMode::Files + } +} + +/// A set of directories, files and modules that rustfmt should ignore. +#[derive(Default, Clone, Debug, PartialEq)] +pub struct IgnoreList { + /// A set of path specified in rustfmt.toml. + path_set: HashSet<PathBuf>, + /// A path to rustfmt.toml. + rustfmt_toml_path: PathBuf, +} + +impl fmt::Display for IgnoreList { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "[{}]", + self.path_set + .iter() + .format_with(", ", |path, f| f(&format_args!( + "{}", + path.to_string_lossy() + ))) + ) + } +} + +impl Serialize for IgnoreList { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + let mut seq = serializer.serialize_seq(Some(self.path_set.len()))?; + for e in &self.path_set { + seq.serialize_element(e)?; + } + seq.end() + } +} + +impl<'de> Deserialize<'de> for IgnoreList { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + struct HashSetVisitor; + impl<'v> Visitor<'v> for HashSetVisitor { + type Value = HashSet<PathBuf>; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("a sequence of path") + } + + fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> + where + A: SeqAccess<'v>, + { + let mut path_set = HashSet::new(); + while let Some(elem) = seq.next_element()? { + path_set.insert(elem); + } + Ok(path_set) + } + } + Ok(IgnoreList { + path_set: deserializer.deserialize_seq(HashSetVisitor)?, + rustfmt_toml_path: PathBuf::new(), + }) + } +} + +impl<'a> IntoIterator for &'a IgnoreList { + type Item = &'a PathBuf; + type IntoIter = hash_set::Iter<'a, PathBuf>; + + fn into_iter(self) -> Self::IntoIter { + self.path_set.iter() + } +} + +impl IgnoreList { + pub fn add_prefix(&mut self, dir: &Path) { + self.rustfmt_toml_path = dir.to_path_buf(); + } + + pub fn rustfmt_toml_path(&self) -> &Path { + &self.rustfmt_toml_path + } +} + +impl FromStr for IgnoreList { + type Err = &'static str; + + fn from_str(_: &str) -> Result<Self, Self::Err> { + Err("IgnoreList is not parsable") + } +} + +/// Maps client-supplied options to Rustfmt's internals, mostly overriding +/// values in a config with values from the command line. +pub trait CliOptions { + fn apply_to(self, config: &mut Config); + fn config_path(&self) -> Option<&Path>; +} + +/// The edition of the syntax and semntics of code (RFC 2052). +#[config_type] +pub enum Edition { + #[value = "2015"] + #[doc_hint = "2015"] + /// Edition 2015. + Edition2015, + #[value = "2018"] + #[doc_hint = "2018"] + /// Edition 2018. + Edition2018, + #[value = "2021"] + #[doc_hint = "2021"] + /// Edition 2021. + Edition2021, + #[value = "2024"] + #[doc_hint = "2024"] + /// Edition 2024. + Edition2024, +} + +impl Default for Edition { + fn default() -> Edition { + Edition::Edition2015 + } +} + +impl From<Edition> for rustc_span::edition::Edition { + fn from(edition: Edition) -> Self { + match edition { + Edition::Edition2015 => Self::Edition2015, + Edition::Edition2018 => Self::Edition2018, + Edition::Edition2021 => Self::Edition2021, + Edition::Edition2024 => Self::Edition2024, + } + } +} + +impl PartialOrd for Edition { + fn partial_cmp(&self, other: &Edition) -> Option<std::cmp::Ordering> { + rustc_span::edition::Edition::partial_cmp(&(*self).into(), &(*other).into()) + } +} + +/// Controls how rustfmt should handle leading pipes on match arms. +#[config_type] +pub enum MatchArmLeadingPipe { + /// Place leading pipes on all match arms + Always, + /// Never emit leading pipes on match arms + Never, + /// Preserve any existing leading pipes + Preserve, +} |