1 // Copyright 2018 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.
11 use syntax::codemap::FileName;
13 use config::config_type::ConfigType;
14 use config::file_lines::FileLines;
17 use {FmtResult, WRITE_MODE_LIST};
22 use std::collections::HashSet;
23 use std::path::{Path, PathBuf};
24 use std::str::FromStr;
26 /// Macro for deriving implementations of Serialize/Deserialize for enums
28 macro_rules! impl_enum_serialize_and_deserialize {
29 ( $e:ident, $( $x:ident ),* ) => {
30 impl ::serde::ser::Serialize for $e {
31 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
32 where S: ::serde::ser::Serializer
34 use serde::ser::Error;
36 // We don't know whether the user of the macro has given us all options.
37 #[allow(unreachable_patterns)]
40 $e::$x => serializer.serialize_str(stringify!($x)),
43 Err(S::Error::custom(format!("Cannot serialize {:?}", self)))
49 impl<'de> ::serde::de::Deserialize<'de> for $e {
50 fn deserialize<D>(d: D) -> Result<Self, D::Error>
51 where D: ::serde::Deserializer<'de> {
52 use serde::de::{Error, Visitor};
53 use std::marker::PhantomData;
55 struct StringOnly<T>(PhantomData<T>);
56 impl<'de, T> Visitor<'de> for StringOnly<T>
57 where T: ::serde::Deserializer<'de> {
59 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
60 formatter.write_str("string")
62 fn visit_str<E>(self, value: &str) -> Result<String, E> {
63 Ok(String::from(value))
66 let s = d.deserialize_string(StringOnly::<D>(PhantomData))?;
68 if stringify!($x).eq_ignore_ascii_case(&s) {
72 static ALLOWED: &'static[&str] = &[$(stringify!($x),)*];
73 Err(D::Error::unknown_variant(&s, ALLOWED))
77 impl ::std::str::FromStr for $e {
78 type Err = &'static str;
80 fn from_str(s: &str) -> Result<Self, Self::Err> {
82 if stringify!($x).eq_ignore_ascii_case(s) {
90 impl ConfigType for $e {
91 fn doc_hint() -> String {
92 let mut variants = Vec::new();
94 variants.push(stringify!($x));
96 format!("[{}]", variants.join("|"))
102 macro_rules! configuration_option_enum{
103 ($e:ident: $( $x:ident ),+ $(,)*) => {
104 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
109 impl_enum_serialize_and_deserialize!($e, $( $x ),+);
113 configuration_option_enum! { NewlineStyle:
116 Native, // \r\n in Windows, \n on other platforms
119 configuration_option_enum! { BraceStyle:
122 // Prefer same line except where there is a where clause, in which case force
123 // the brace to the next line.
127 configuration_option_enum! { ControlBraceStyle:
128 // K&R style, Rust community default
136 configuration_option_enum! { IndentStyle:
137 // First line on the same line as the opening brace, all lines aligned with
140 // First line is on a new line and all lines align with block indent.
144 configuration_option_enum! { Density:
145 // Fit as much on one line as possible.
149 // Place every item on a separate line.
153 configuration_option_enum! { TypeDensity:
154 // No spaces around "=" and "+"
156 // Spaces around " = " and " + "
161 pub fn to_list_tactic(self) -> ListTactic {
163 Density::Compressed => ListTactic::Mixed,
164 Density::Tall => ListTactic::HorizontalVertical,
165 Density::Vertical => ListTactic::Vertical,
170 configuration_option_enum! { ReportTactic:
176 configuration_option_enum! { WriteMode:
177 // Backs the original file up and overwrites the original.
179 // Overwrites original file without backup.
181 // Writes the output to stdout.
183 // Writes the diff to stdout.
185 // Displays how much of the input file was processed
189 // Outputs a checkstyle XML file.
191 // Output the changed lines (for internal value only)
193 // Checks if a diff can be generated. If so, rustfmt outputs a diff and quits with exit code 1.
194 // This option is designed to be run in CI where a non-zero exit signifies non-standard code
197 // Rustfmt shouldn't output anything formatting-like (e.g., emit a help message).
201 configuration_option_enum! { Color:
202 // Always use color, whether it is a piped or terminal output
206 // Automatically use color, if supported by terminal
210 #[derive(Deserialize, Serialize, Clone, Debug)]
211 pub struct WidthHeuristics {
212 // Maximum width of the args of a function call before falling back
213 // to vertical formatting.
214 pub fn_call_width: usize,
215 // Maximum width in the body of a struct lit before falling back to
216 // vertical formatting.
217 pub struct_lit_width: usize,
218 // Maximum width in the body of a struct variant before falling back
219 // to vertical formatting.
220 pub struct_variant_width: usize,
221 // Maximum width of an array literal before falling back to vertical
223 pub array_width: usize,
224 // Maximum length of a chain to fit on a single line.
225 pub chain_width: usize,
226 // Maximum line length for single line if-else expressions. A value
227 // of zero means always break if-else expressions.
228 pub single_line_if_else_max_width: usize,
231 impl WidthHeuristics {
232 // Using this WidthHeuristics means we ignore heuristics.
233 pub fn null() -> WidthHeuristics {
235 fn_call_width: usize::max_value(),
237 struct_variant_width: 0,
238 array_width: usize::max_value(),
239 chain_width: usize::max_value(),
240 single_line_if_else_max_width: 0,
244 // scale the default WidthHeuristics according to max_width
245 pub fn scaled(max_width: usize) -> WidthHeuristics {
246 const DEFAULT_MAX_WIDTH: usize = 100;
247 let max_width_ratio = if max_width > DEFAULT_MAX_WIDTH {
248 let ratio = max_width as f32 / DEFAULT_MAX_WIDTH as f32;
249 // round to the closest 0.1
250 (ratio * 10.0).round() / 10.0
255 fn_call_width: (60.0 * max_width_ratio).round() as usize,
256 struct_lit_width: (18.0 * max_width_ratio).round() as usize,
257 struct_variant_width: (35.0 * max_width_ratio).round() as usize,
258 array_width: (60.0 * max_width_ratio).round() as usize,
259 chain_width: (60.0 * max_width_ratio).round() as usize,
260 single_line_if_else_max_width: (50.0 * max_width_ratio).round() as usize,
265 impl ::std::str::FromStr for WidthHeuristics {
266 type Err = &'static str;
268 fn from_str(_: &str) -> Result<Self, Self::Err> {
269 Err("WidthHeuristics is not parsable")
273 impl Default for WriteMode {
274 fn default() -> WriteMode {
279 /// A set of directories, files and modules that rustfmt should ignore.
280 #[derive(Default, Deserialize, Serialize, Clone, Debug)]
281 pub struct IgnoreList(HashSet<PathBuf>);
284 pub fn add_prefix(&mut self, dir: &Path) {
291 let mut path = PathBuf::from(dir);
299 fn skip_file_inner(&self, file: &Path) -> bool {
300 self.0.iter().any(|path| file.starts_with(path))
303 pub fn skip_file(&self, file: &FileName) -> bool {
304 if let FileName::Real(ref path) = file {
305 self.skip_file_inner(path)
312 impl ::std::str::FromStr for IgnoreList {
313 type Err = &'static str;
315 fn from_str(_: &str) -> Result<Self, Self::Err> {
316 Err("IgnoreList is not parsable")
320 /// Parsed command line options.
321 #[derive(Clone, Debug, Default)]
322 pub struct CliOptions {
323 skip_children: Option<bool>,
326 pub(super) config_path: Option<PathBuf>,
327 write_mode: Option<WriteMode>,
328 color: Option<Color>,
329 file_lines: FileLines, // Default is all lines in all files.
330 unstable_features: bool,
331 error_on_unformatted: Option<bool>,
335 pub fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
336 let mut options = CliOptions::default();
337 options.verbose = matches.opt_present("verbose");
338 options.verbose_diff = matches.opt_present("verbose-diff");
340 let unstable_features = matches.opt_present("unstable-features");
341 let rust_nightly = option_env!("CFG_RELEASE_CHANNEL")
342 .map(|c| c == "nightly")
344 if unstable_features && !rust_nightly {
345 return Err(format_err!(
346 "Unstable features are only available on Nightly channel"
349 options.unstable_features = unstable_features;
352 options.config_path = matches.opt_str("config-path").map(PathBuf::from);
354 if let Some(ref write_mode) = matches.opt_str("write-mode") {
355 if let Ok(write_mode) = WriteMode::from_str(write_mode) {
356 options.write_mode = Some(write_mode);
358 return Err(format_err!(
359 "Invalid write-mode: {}, expected one of {}",
366 if let Some(ref color) = matches.opt_str("color") {
367 match Color::from_str(color) {
368 Ok(color) => options.color = Some(color),
369 _ => return Err(format_err!("Invalid color: {}", color)),
373 if let Some(ref file_lines) = matches.opt_str("file-lines") {
374 options.file_lines = file_lines.parse().map_err(err_msg)?;
377 if matches.opt_present("skip-children") {
378 options.skip_children = Some(true);
380 if matches.opt_present("error-on-unformatted") {
381 options.error_on_unformatted = Some(true);
387 pub fn apply_to(self, config: &mut Config) {
388 config.set().verbose(self.verbose);
389 config.set().verbose_diff(self.verbose_diff);
390 config.set().file_lines(self.file_lines);
391 config.set().unstable_features(self.unstable_features);
392 if let Some(skip_children) = self.skip_children {
393 config.set().skip_children(skip_children);
395 if let Some(error_on_unformatted) = self.error_on_unformatted {
396 config.set().error_on_unformatted(error_on_unformatted);
398 if let Some(write_mode) = self.write_mode {
399 config.set().write_mode(write_mode);
401 if let Some(color) = self.color {
402 config.set().color(color);
406 pub fn verify_file_lines(&self, files: &[PathBuf]) {
407 for f in self.file_lines.files() {
409 FileName::Real(ref f) if files.contains(f) => {}
410 FileName::Real(_) => {
411 eprintln!("Warning: Extra file listed in file_lines option '{}'", f)
413 _ => eprintln!("Warning: Not a file '{}'", f),