diff --git a/Contributing.md b/Contributing.md index 7c66d27da41..730cefdca45 100644 --- a/Contributing.md +++ b/Contributing.md @@ -207,6 +207,6 @@ handling of configuration options is done in [src/config.rs](src/config.rs). Loo `create_config!` macro at the end of the file for all the options. The rest of the file defines a bunch of enums used for options, and the machinery to produce the config struct and parse a config file, etc. Checking an option is done by -accessing the correct field on the config struct, e.g., `config.max_width`. Most +accessing the correct field on the config struct, e.g., `config.max_width()`. Most functions have a `Config`, or one can be accessed via a visitor or context of some kind. diff --git a/Design.md b/Design.md index da52fb23e40..43caa7b81f8 100644 --- a/Design.md +++ b/Design.md @@ -150,7 +150,7 @@ for its configuration. Our visitor keeps track of the desired current indent due to blocks ( `block_indent`). Each `visit_*` method reformats code according to this indent, -`config.comment_width` and `config.max_width`. Most reformatting done in the +`config.comment_width()` and `config.max_width()`. Most reformatting done in the `visit_*` methods is a bit hackey and is meant to be temporary until it can be done properly. diff --git a/src/bin/rustfmt.rs b/src/bin/rustfmt.rs index 2c5cf697362..fac4f9f8714 100644 --- a/src/bin/rustfmt.rs +++ b/src/bin/rustfmt.rs @@ -18,14 +18,12 @@ extern crate env_logger; extern crate getopts; use rustfmt::{run, Input, Summary}; -use rustfmt::file_lines::FileLines; -use rustfmt::config::{Config, WriteMode}; +use rustfmt::config::Config; use std::{env, error}; use std::fs::{self, File}; use std::io::{self, ErrorKind, Read, Write}; use std::path::{Path, PathBuf}; -use std::str::FromStr; use getopts::{Matches, Options}; @@ -63,8 +61,8 @@ enum Operation { struct CliOptions { skip_children: bool, verbose: bool, - write_mode: Option<WriteMode>, - file_lines: FileLines, // Default is all lines in all files. + write_mode: Option<String>, + file_lines: Option<String>, } impl CliOptions { @@ -73,28 +71,29 @@ impl CliOptions { options.skip_children = matches.opt_present("skip-children"); options.verbose = matches.opt_present("verbose"); - if let Some(ref write_mode) = matches.opt_str("write-mode") { - if let Ok(write_mode) = WriteMode::from_str(write_mode) { - options.write_mode = Some(write_mode); - } else { - return Err(FmtError::from(format!("Invalid write-mode: {}", write_mode))); - } + if let Some(write_mode) = matches.opt_str("write-mode") { + options.write_mode = Some(write_mode); } - if let Some(ref file_lines) = matches.opt_str("file-lines") { - options.file_lines = file_lines.parse()?; + if let Some(file_lines) = matches.opt_str("file-lines") { + options.file_lines = Some(file_lines); } Ok(options) } - fn apply_to(self, config: &mut Config) { - config.skip_children = self.skip_children; - config.verbose = self.verbose; - config.file_lines = self.file_lines; - if let Some(write_mode) = self.write_mode { - config.write_mode = write_mode; + fn apply_to(&self, config: &mut Config) -> FmtResult<()> { + let bool_to_str = |b| if b { "true" } else { "false" }; + config + .override_value("skip_children", bool_to_str(self.skip_children))?; + config.override_value("verbose", bool_to_str(self.verbose))?; + if let Some(ref write_mode) = self.write_mode { + config.override_value("write_mode", &write_mode)?; } + if let Some(ref file_lines) = self.file_lines { + config.override_value("file_lines", &file_lines)?; + } + Ok(()) } } @@ -222,12 +221,12 @@ fn execute(opts: &Options) -> FmtResult<Summary> { &env::current_dir().unwrap())?; // write_mode is always Plain for Stdin. - config.write_mode = WriteMode::Plain; + config.override_value("write_mode", "Plain")?; // parse file_lines if let Some(ref file_lines) = matches.opt_str("file-lines") { - config.file_lines = file_lines.parse()?; - for f in config.file_lines.files() { + config.override_value("file-lines", file_lines)?; + for f in config.file_lines().files() { if f != "stdin" { println!("Warning: Extra file listed in file_lines option '{}'", f); } @@ -239,12 +238,6 @@ fn execute(opts: &Options) -> FmtResult<Summary> { Operation::Format { files, config_path } => { let options = CliOptions::from_matches(&matches)?; - for f in options.file_lines.files() { - if !files.contains(&PathBuf::from(f)) { - println!("Warning: Extra file listed in file_lines option '{}'", f); - } - } - let mut config = Config::default(); let mut path = None; // Load the config path file if provided @@ -253,6 +246,13 @@ fn execute(opts: &Options) -> FmtResult<Summary> { config = cfg_tmp; path = path_tmp; }; + options.apply_to(&mut config)?; + + for f in config.file_lines().files() { + if !files.contains(&PathBuf::from(f)) { + println!("Warning: Extra file listed in file_lines option '{}'", f); + } + } if options.verbose { if let Some(path) = path.as_ref() { @@ -282,7 +282,7 @@ fn execute(opts: &Options) -> FmtResult<Summary> { config = config_tmp; } - options.clone().apply_to(&mut config); + options.apply_to(&mut config)?; error_summary.add(run(Input::File(file), &config)); } } diff --git a/src/chains.rs b/src/chains.rs index 858103489fd..e8a334bb134 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -114,23 +114,23 @@ pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) - }; let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) { let nested_shape = if first_subexpr_is_try { - parent_shape.block_indent(context.config.tab_spaces) + parent_shape.block_indent(context.config.tab_spaces()) } else { chain_indent(context, shape.add_offset(parent_rewrite.len())) }; (nested_shape, - context.config.chain_indent == IndentStyle::Visual || - parent_rewrite.len() <= context.config.tab_spaces) + context.config.chain_indent() == IndentStyle::Visual || + parent_rewrite.len() <= context.config.tab_spaces()) } else if is_block_expr(&parent, &parent_rewrite) { // The parent is a block, so align the rest of the chain with the closing // brace. (parent_shape, false) } else if parent_rewrite_contains_newline { (chain_indent(context, - parent_shape.block_indent(context.config.tab_spaces)), + parent_shape.block_indent(context.config.tab_spaces())), false) } else { - (shape.block_indent(context.config.tab_spaces), false) + (shape.block_indent(context.config.tab_spaces()), false) }; let max_width = try_opt!((shape.width + shape.indent.width() + shape.offset) @@ -143,14 +143,14 @@ pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) - }; let first_child_shape = if extend { let mut shape = try_opt!(parent_shape.offset_left(last_line_width(&parent_rewrite))); - match context.config.chain_indent { + match context.config.chain_indent() { IndentStyle::Visual => shape, IndentStyle::Block => { shape.offset = shape .offset - .checked_sub(context.config.tab_spaces) + .checked_sub(context.config.tab_spaces()) .unwrap_or(0); - shape.indent.block_indent += context.config.tab_spaces; + shape.indent.block_indent += context.config.tab_spaces(); shape } } @@ -176,7 +176,7 @@ pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) - .fold(0, |a, b| a + first_line_width(b)) + parent_rewrite.len(); let one_line_len = rewrites.iter().fold(0, |a, r| a + r.len()) + parent_rewrite.len(); - let veto_single_line = if one_line_len > context.config.chain_one_line_max { + let veto_single_line = if one_line_len > context.config.chain_one_line_max() { if rewrites.len() > 1 { true } else if rewrites.len() == 1 { @@ -185,7 +185,7 @@ pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) - } else { false } - } else if context.config.take_source_hints && subexpr_list.len() > 1 { + } else if context.config.take_source_hints() && subexpr_list.len() > 1 { // Look at the source code. Unless all chain elements start on the same // line, we won't consider putting them on a single line either. let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi)); @@ -214,7 +214,7 @@ pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) - shape) { // If the first line of the last method does not fit into a single line // after the others, allow new lines. - almost_total + first_line_width(&last[0]) < context.config.max_width + almost_total + first_line_width(&last[0]) < context.config.max_width() } else { false } @@ -242,7 +242,7 @@ pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) - parent_rewrite, first_connector, join_rewrites(&rewrites, &subexpr_list, &connector)), - context.config.max_width, + context.config.max_width(), shape) } @@ -320,9 +320,9 @@ fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> (ast::Expr, } fn chain_indent(context: &RewriteContext, shape: Shape) -> Shape { - match context.config.chain_indent { + match context.config.chain_indent() { IndentStyle::Visual => shape.visual_indent(0), - IndentStyle::Block => shape.block_indent(context.config.tab_spaces), + IndentStyle::Block => shape.block_indent(context.config.tab_spaces()), } } @@ -372,7 +372,7 @@ fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Exp fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr { match expr.node { - ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand => { + ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => { if let Some(subexpr) = convert_try_mac(mac, context) { subexpr } else { @@ -428,7 +428,7 @@ fn rewrite_method_call(method_name: ast::Ident, let type_list: Vec<_> = try_opt!(types.iter().map(|ty| ty.rewrite(context, shape)).collect()); - let type_str = if context.config.spaces_within_angle_brackets && type_list.len() > 0 { + let type_str = if context.config.spaces_within_angle_brackets() && type_list.len() > 0 { format!("::< {} >", type_list.join(", ")) } else { format!("::<{}>", type_list.join(", ")) diff --git a/src/comment.rs b/src/comment.rs index 17b1700accd..ad52ec67f33 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -38,23 +38,23 @@ pub fn rewrite_comment(orig: &str, config: &Config) -> Option<String> { // If there are lines without a starting sigil, we won't format them correctly - // so in that case we won't even re-align (if !config.normalize_comments) and + // so in that case we won't even re-align (if !config.normalize_comments()) and // we should stop now. let num_bare_lines = orig.lines() .map(|line| line.trim()) .filter(|l| !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*"))) .count(); - if num_bare_lines > 0 && !config.normalize_comments { + if num_bare_lines > 0 && !config.normalize_comments() { return Some(orig.to_owned()); } - if !config.normalize_comments && !config.wrap_comments { + if !config.normalize_comments() && !config.wrap_comments() { return light_rewrite_comment(orig, shape.indent, config); } let (opener, closer, line_start) = if block_style { ("/* ", " */", " * ") - } else if !config.normalize_comments { + } else if !config.normalize_comments() { if orig.starts_with("/**") && !orig.starts_with("/**/") { ("/** ", " **/", " ** ") } else if orig.starts_with("/*!") { @@ -128,7 +128,7 @@ pub fn rewrite_comment(orig: &str, result.push_str(line_start); } - if config.wrap_comments && line.len() > max_chars { + if config.wrap_comments() && line.len() > max_chars { let rewrite = rewrite_string(line, &fmt).unwrap_or(line.to_owned()); result.push_str(&rewrite); } else { @@ -579,7 +579,7 @@ pub fn recover_comment_removed(new: String, if changed_comment_content(&snippet, &new) { // We missed some comments // Keep previous formatting if it satisfies the constrains - wrap_str(snippet, context.config.max_width, shape) + wrap_str(snippet, context.config.max_width(), shape) } else { Some(new) } @@ -731,8 +731,10 @@ mod test { #[cfg_attr(rustfmt, rustfmt_skip)] fn format_comments() { let mut config: ::config::Config = Default::default(); - config.wrap_comments = true; - config.normalize_comments = true; + config.override_value("wrap_comments", "true") + .expect("Could not set wrap_comments to true"); + config.override_value("normalize_comments", "true") + .expect("Could not set normalize_comments to true"); let comment = rewrite_comment(" //test", true, diff --git a/src/config.rs b/src/config.rs index 632170e6812..63c33cdf6fc 100644 --- a/src/config.rs +++ b/src/config.rs @@ -10,6 +10,9 @@ extern crate toml; +use std::error; +use std::result; + use file_lines::FileLines; use lists::{SeparatorTactic, ListTactic}; @@ -212,7 +215,7 @@ macro_rules! create_config { ($($i:ident: $ty:ty, $def:expr, $( $dstring:expr ),+ );+ $(;)*) => ( #[derive(Deserialize, Clone)] pub struct Config { - $(pub $i: $ty),+ + $($i: $ty),+ } // Just like the Config struct but with each property wrapped @@ -227,6 +230,12 @@ macro_rules! create_config { impl Config { + $( + pub fn $i(&self) -> $ty { + self.$i.clone() + } + )+ + fn fill_from_parsed_config(mut self, parsed: ParsedConfig) -> Config { $( if let Some(val) = parsed.$i { @@ -270,19 +279,16 @@ macro_rules! create_config { } } - pub fn override_value(&mut self, key: &str, val: &str) { + pub fn override_value(&mut self, key: &str, val: &str) + -> result::Result<(), Box<error::Error + Send + Sync>> + { match key { $( - stringify!($i) => { - self.$i = val.parse::<$ty>() - .expect(&format!("Failed to parse override for {} (\"{}\") as a {}", - stringify!($i), - val, - stringify!($ty))); - } + stringify!($i) => self.$i = val.parse::<$ty>()?, )+ _ => panic!("Unknown config key in override: {}", key) } + Ok(()) } pub fn print_docs() { diff --git a/src/expr.rs b/src/expr.rs index 7fb71c2e8b4..9d1f1093fa9 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -65,7 +65,11 @@ fn format_expr(expr: &ast::Expr, ast::LitKind::Str(_, ast::StrStyle::Cooked) => { rewrite_string_lit(context, l.span, shape) } - _ => wrap_str(context.snippet(expr.span), context.config.max_width, shape), + _ => { + wrap_str(context.snippet(expr.span), + context.config.max_width(), + shape) + } } } ast::ExprKind::Call(ref callee, ref args) => { @@ -146,7 +150,7 @@ fn format_expr(expr: &ast::Expr, None => String::new(), }; wrap_str(format!("continue{}", id_str), - context.config.max_width, + context.config.max_width(), shape) } ast::ExprKind::Break(ref opt_ident, ref opt_expr) => { @@ -158,7 +162,9 @@ fn format_expr(expr: &ast::Expr, if let Some(ref expr) = *opt_expr { rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape) } else { - wrap_str(format!("break{}", id_str), context.config.max_width, shape) + wrap_str(format!("break{}", id_str), + context.config.max_width(), + shape) } } ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => { @@ -171,10 +177,15 @@ fn format_expr(expr: &ast::Expr, ast::ExprKind::Mac(ref mac) => { // Failure to rewrite a marco should not imply failure to // rewrite the expression. - rewrite_macro(mac, None, context, shape, MacroPosition::Expression) - .or_else(|| wrap_str(context.snippet(expr.span), context.config.max_width, shape)) + rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| { + wrap_str(context.snippet(expr.span), + context.config.max_width(), + shape) + }) + } + ast::ExprKind::Ret(None) => { + wrap_str("return".to_owned(), context.config.max_width(), shape) } - ast::ExprKind::Ret(None) => wrap_str("return".to_owned(), context.config.max_width, shape), ast::ExprKind::Ret(Some(ref expr)) => { rewrite_unary_prefix(context, "return ", &**expr, shape) } @@ -192,7 +203,7 @@ fn format_expr(expr: &ast::Expr, rewrite_index(&**expr, &**index, context, shape) } ast::ExprKind::Repeat(ref expr, ref repeats) => { - let (lbr, rbr) = if context.config.spaces_within_square_brackets { + let (lbr, rbr) = if context.config.spaces_within_square_brackets() { ("[ ", " ]") } else { ("[", "]") @@ -207,7 +218,7 @@ fn format_expr(expr: &ast::Expr, match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) { (Some(ref lhs), Some(ref rhs)) => { - let sp_delim = if context.config.spaces_around_ranges { + let sp_delim = if context.config.spaces_around_ranges() { format!(" {} ", delim) } else { delim.into() @@ -215,7 +226,7 @@ fn format_expr(expr: &ast::Expr, rewrite_pair(&**lhs, &**rhs, "", &sp_delim, "", context, shape) } (None, Some(ref rhs)) => { - let sp_delim = if context.config.spaces_around_ranges { + let sp_delim = if context.config.spaces_around_ranges() { format!("{} ", delim) } else { delim.into() @@ -223,21 +234,23 @@ fn format_expr(expr: &ast::Expr, rewrite_unary_prefix(context, &sp_delim, &**rhs, shape) } (Some(ref lhs), None) => { - let sp_delim = if context.config.spaces_around_ranges { + let sp_delim = if context.config.spaces_around_ranges() { format!(" {}", delim) } else { delim.into() }; rewrite_unary_suffix(context, &sp_delim, &**lhs, shape) } - (None, None) => wrap_str(delim.into(), context.config.max_width, shape), + (None, None) => wrap_str(delim.into(), context.config.max_width(), shape), } } // We do not format these expressions yet, but they should still // satisfy our width restrictions. ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => { - wrap_str(context.snippet(expr.span), context.config.max_width, shape) + wrap_str(context.snippet(expr.span), + context.config.max_width(), + shape) } }; result.and_then(|res| recover_comment_removed(res, expr.span, context, shape)) @@ -304,14 +317,14 @@ pub fn rewrite_pair<LHS, RHS>(lhs: &LHS, let infix = infix.trim_right(); let lhs_budget = try_opt!(context .config - .max_width + .max_width() .checked_sub(shape.used_width() + prefix.len() + infix.len())); - let rhs_shape = match context.config.control_style { + let rhs_shape = match context.config.control_style() { Style::Default => { try_opt!(shape.sub_width(suffix.len() + prefix.len())).visual_indent(prefix.len()) } - Style::Rfc => try_opt!(shape.block_left(context.config.tab_spaces)), + Style::Rfc => try_opt!(shape.block_left(context.config.tab_spaces())), }; let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape)); @@ -336,14 +349,14 @@ pub fn rewrite_array<'a, I>(expr_iter: I, -> Option<String> where I: Iterator<Item = &'a ast::Expr> { - let bracket_size = if context.config.spaces_within_square_brackets { + let bracket_size = if context.config.spaces_within_square_brackets() { 2 // "[ " } else { 1 // "[" }; - let nested_shape = match context.config.array_layout { - IndentStyle::Block => shape.block().block_indent(context.config.tab_spaces), + let nested_shape = match context.config.array_layout() { + IndentStyle::Block => shape.block().block_indent(context.config.tab_spaces()), IndentStyle::Visual => { try_opt!(shape .visual_indent(bracket_size) @@ -362,7 +375,7 @@ pub fn rewrite_array<'a, I>(expr_iter: I, .collect::<Vec<_>>(); if items.is_empty() { - if context.config.spaces_within_square_brackets { + if context.config.spaces_within_square_brackets() { return Some("[ ]".to_string()); } else { return Some("[]".to_string()); @@ -375,12 +388,13 @@ pub fn rewrite_array<'a, I>(expr_iter: I, .fold(Some(false), |acc, x| acc.and_then(|y| x.map(|x| x || y)))); - let tactic = match context.config.array_layout { + let tactic = match context.config.array_layout() { IndentStyle::Block => { // FIXME wrong shape in one-line case match shape.width.checked_sub(2 * bracket_size) { Some(width) => { - let tactic = ListTactic::LimitedHorizontalVertical(context.config.array_width); + let tactic = + ListTactic::LimitedHorizontalVertical(context.config.array_width()); definitive_tactic(&items, tactic, width) } None => DefinitiveListTactic::Vertical, @@ -389,7 +403,9 @@ pub fn rewrite_array<'a, I>(expr_iter: I, IndentStyle::Visual => { if has_long_item || items.iter().any(ListItem::is_multiline) { definitive_tactic(&items, - ListTactic::LimitedHorizontalVertical(context.config.array_width), + ListTactic::LimitedHorizontalVertical(context + .config + .array_width()), nested_shape.width) } else { DefinitiveListTactic::Mixed @@ -407,9 +423,9 @@ pub fn rewrite_array<'a, I>(expr_iter: I, }; let list_str = try_opt!(write_list(&items, &fmt)); - let result = if context.config.array_layout == IndentStyle::Visual || + let result = if context.config.array_layout() == IndentStyle::Visual || tactic != DefinitiveListTactic::Vertical { - if context.config.spaces_within_square_brackets && list_str.len() > 0 { + if context.config.spaces_within_square_brackets() && list_str.len() > 0 { format!("[ {} ]", list_str) } else { format!("[{}]", list_str) @@ -574,7 +590,7 @@ fn rewrite_closure(capture: ast::CaptureBy, // Start with visual indent, then fall back to block indent if the // closure is large. if let Some(block_str) = block.rewrite(&context, shape) { - let block_threshold = context.config.closure_block_indent_threshold; + let block_threshold = context.config.closure_block_indent_threshold(); if block_threshold < 0 || block_str.matches('\n').count() <= block_threshold as usize { if let Some(block_str) = block_str.rewrite(context, shape) { return Some(format!("{} {}", prefix, block_str)); @@ -878,11 +894,11 @@ impl<'a> Rewrite for ControlFlow<'a> { let pat_expr_string = match self.cond { Some(cond) => { - let mut cond_shape = match context.config.control_style { + let mut cond_shape = match context.config.control_style() { Style::Default => try_opt!(constr_shape.shrink_left(add_offset)), Style::Rfc => constr_shape, }; - if context.config.control_brace_style != ControlBraceStyle::AlwaysNextLine { + if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine { // 2 = " {".len() cond_shape = try_opt!(cond_shape.sub_width(2)); } @@ -897,15 +913,15 @@ impl<'a> Rewrite for ControlFlow<'a> { None => String::new(), }; - let force_newline_brace = context.config.control_style == Style::Rfc && + let force_newline_brace = context.config.control_style() == Style::Rfc && pat_expr_string.contains('\n'); // Try to format if-else on single line. - if self.allow_single_line && context.config.single_line_if_else_max_width > 0 { + if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 { let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width); if trial.is_some() && - trial.as_ref().unwrap().len() <= context.config.single_line_if_else_max_width { + trial.as_ref().unwrap().len() <= context.config.single_line_if_else_max_width() { return trial; } } @@ -957,7 +973,7 @@ impl<'a> Rewrite for ControlFlow<'a> { &shape.indent.block_only().to_string(context.config); let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() { "" - } else if context.config.control_brace_style == ControlBraceStyle::AlwaysNextLine || + } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine || force_newline_brace { alt_block_sep.as_str() } else { @@ -1035,12 +1051,12 @@ impl<'a> Rewrite for ControlFlow<'a> { else_block.span.lo); let after_else_comment = extract_comment(after_else, context, shape); - let between_sep = match context.config.control_brace_style { + let between_sep = match context.config.control_brace_style() { ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => &*alt_block_sep, ControlBraceStyle::AlwaysSameLine => " ", }; - let after_sep = match context.config.control_brace_style { + let after_sep = match context.config.control_brace_style() { ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep, _ => " ", }; @@ -1169,14 +1185,14 @@ fn rewrite_match(context: &RewriteContext, let cond_shape = try_opt!(cond_shape.sub_width(2)); let cond_str = try_opt!(cond.rewrite(context, cond_shape)); let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config); - let block_sep = match context.config.control_brace_style { + let block_sep = match context.config.control_brace_style() { ControlBraceStyle::AlwaysSameLine => " ", _ => alt_block_sep.as_str(), }; let mut result = format!("match {}{}{{", cond_str, block_sep); - let arm_shape = if context.config.indent_match_arms { - shape.block_indent(context.config.tab_spaces) + let arm_shape = if context.config.indent_match_arms() { + shape.block_indent(context.config.tab_spaces()) } else { shape.block_indent(0) }; @@ -1240,7 +1256,7 @@ fn arm_end_pos(arm: &ast::Arm) -> BytePos { } fn arm_comma(config: &Config, body: &ast::Expr) -> &'static str { - if config.match_block_trailing_comma { + if config.match_block_trailing_comma() { "," } else if let ast::ExprKind::Block(ref block) = body.node { if let ast::BlockCheckMode::Default = block.rules { @@ -1322,7 +1338,7 @@ impl Rewrite for ast::Arm { let body = match body.node { ast::ExprKind::Block(ref block) if !is_unsafe_block(block) && is_simple_block(block, context.codemap) && - context.config.wrap_match_arms => { + context.config.wrap_match_arms() => { if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node { expr } else { @@ -1355,9 +1371,9 @@ impl Rewrite for ast::Arm { match rewrite { Some(ref body_str) if (!body_str.contains('\n') && body_str.len() <= arm_shape.width) || - !context.config.wrap_match_arms || + !context.config.wrap_match_arms() || is_block => { - let block_sep = match context.config.control_brace_style { + let block_sep = match context.config.control_brace_style() { ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep.as_str(), _ => " ", }; @@ -1375,16 +1391,16 @@ impl Rewrite for ast::Arm { // FIXME: we're doing a second rewrite of the expr; This may not be // necessary. - let body_shape = try_opt!(shape.sub_width(context.config.tab_spaces)) - .block_indent(context.config.tab_spaces); + let body_shape = try_opt!(shape.sub_width(context.config.tab_spaces())) + .block_indent(context.config.tab_spaces()); let next_line_body = try_opt!(nop_block_collapse(body.rewrite(context, body_shape), body_shape.width)); let indent_str = shape .indent .block_indent(context.config) .to_string(context.config); - let (body_prefix, body_suffix) = if context.config.wrap_match_arms { - if context.config.match_block_trailing_comma { + let (body_prefix, body_suffix) = if context.config.wrap_match_arms() { + if context.config.match_block_trailing_comma() { ("{", "},") } else { ("{", "}") @@ -1394,13 +1410,13 @@ impl Rewrite for ast::Arm { }; - let block_sep = match context.config.control_brace_style { + let block_sep = match context.config.control_brace_style() { ControlBraceStyle::AlwaysNextLine => alt_block_sep + body_prefix + "\n", _ if body_prefix.is_empty() => "\n".to_owned(), _ => " ".to_owned() + body_prefix + "\n", }; - if context.config.wrap_match_arms { + if context.config.wrap_match_arms() { Some(format!("{}{} =>{}{}{}\n{}{}", attr_str.trim_left(), pats_str, @@ -1536,11 +1552,11 @@ fn rewrite_pat_expr(context: &RewriteContext, fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> { let string_lit = context.snippet(span); - if !context.config.format_strings && !context.config.force_format_strings { + if !context.config.format_strings() && !context.config.force_format_strings() { return Some(string_lit); } - if !context.config.force_format_strings && + if !context.config.force_format_strings() && !string_requires_rewrite(context, span, &string_lit, shape) { return Some(string_lit); } @@ -1621,7 +1637,7 @@ fn rewrite_call_inner<R>(context: &RewriteContext, .ok_or(Ordering::Greater)?; // 4 = `( )`, 2 = `()` - let paren_overhead = if context.config.spaces_within_parens { + let paren_overhead = if context.config.spaces_within_parens() { 4 } else { 2 @@ -1632,8 +1648,8 @@ fn rewrite_call_inner<R>(context: &RewriteContext, .checked_sub(used_width + paren_overhead) .ok_or(Ordering::Greater)?; - let nested_shape = match context.config.fn_call_style { - IndentStyle::Block => shape.block().block_left(context.config.tab_spaces), + let nested_shape = match context.config.fn_call_style() { + IndentStyle::Block => shape.block().block_left(context.config.tab_spaces()), // 1 = ( IndentStyle::Visual => { shape @@ -1649,9 +1665,9 @@ fn rewrite_call_inner<R>(context: &RewriteContext, let list_str = rewrite_call_args(context, args, span, nested_shape, one_line_width) .ok_or(Ordering::Less)?; - let result = if context.config.fn_call_style == IndentStyle::Visual || + let result = if context.config.fn_call_style() == IndentStyle::Visual || (!list_str.contains('\n') && list_str.chars().last().unwrap_or(' ') != ',') { - if context.config.spaces_within_parens && list_str.len() > 0 { + if context.config.spaces_within_parens() && list_str.len() > 0 { format!("{}( {} )", callee_str, list_str) } else { format!("{}({})", callee_str, list_str) @@ -1723,7 +1739,7 @@ fn rewrite_call_args(context: &RewriteContext, let tactic = definitive_tactic(&item_vec, - ListTactic::LimitedHorizontalVertical(context.config.fn_call_width), + ListTactic::LimitedHorizontalVertical(context.config.fn_call_width()), one_line_width); // Replace the stub with the full overflowing last argument if the rewrite @@ -1742,11 +1758,11 @@ fn rewrite_call_args(context: &RewriteContext, tactic: tactic, separator: ",", trailing_separator: if context.inside_macro || - context.config.fn_call_style == IndentStyle::Visual || + context.config.fn_call_style() == IndentStyle::Visual || arg_count <= 1 { SeparatorTactic::Never } else { - context.config.trailing_comma + context.config.trailing_comma() }, shape: one_line_shape, ends_with_newline: false, @@ -1757,10 +1773,10 @@ fn rewrite_call_args(context: &RewriteContext, // If arguments do not fit in a single line and do not contain newline, // try to put it on the next line. Try this only when we are in block mode // and not rewriting macro. - Some(ref s) if context.config.fn_call_style == IndentStyle::Block && + Some(ref s) if context.config.fn_call_style() == IndentStyle::Block && !context.inside_macro && (!s.contains('\n') && - (s.len() > one_line_width || s.len() > context.config.fn_call_width)) => { + (s.len() > one_line_width || s.len() > context.config.fn_call_width())) => { fmt.trailing_separator = SeparatorTactic::Vertical; write_list(&item_vec, &fmt) } @@ -1776,7 +1792,7 @@ fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> let subexpr_str = subexpr.rewrite(context, sub_shape); debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str); - subexpr_str.map(|s| if context.config.spaces_within_parens && s.len() > 0 { + subexpr_str.map(|s| if context.config.spaces_within_parens() && s.len() > 0 { format!("( {} )", s) } else { format!("({})", s) @@ -1790,7 +1806,7 @@ fn rewrite_index(expr: &ast::Expr, -> Option<String> { let expr_str = try_opt!(expr.rewrite(context, shape)); - let (lbr, rbr) = if context.config.spaces_within_square_brackets { + let (lbr, rbr) = if context.config.spaces_within_square_brackets() { ("[ ", " ]") } else { ("[", "]") @@ -1811,7 +1827,7 @@ fn rewrite_index(expr: &ast::Expr, // might be reduced from max_width by something on the right. let budget = try_opt!(context .config - .max_width + .max_width() .checked_sub(indent.len() + lbr.len() + rbr.len())); let index_str = try_opt!(index.rewrite(context, Shape::legacy(budget, shape.indent))); Some(format!("{}\n{}{}{}{}", expr_str, indent, lbr, index_str, rbr)) @@ -1887,9 +1903,10 @@ fn rewrite_struct_lit<'a>(context: &RewriteContext, let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some()); let fields_str = try_opt!(write_list(&item_vec, &fmt)); - let fields_str = if context.config.struct_lit_style == IndentStyle::Block && + let fields_str = if context.config.struct_lit_style() == IndentStyle::Block && (fields_str.contains('\n') || - context.config.struct_lit_multiline_style == MultilineStyle::ForceMulti || + context.config.struct_lit_multiline_style() == + MultilineStyle::ForceMulti || fields_str.len() > h_shape.map(|s| s.width).unwrap_or(0)) { format!("\n{}{}\n{}", v_shape.indent.to_string(context.config), @@ -1902,13 +1919,13 @@ fn rewrite_struct_lit<'a>(context: &RewriteContext, Some(format!("{} {{{}}}", path_str, fields_str)) - // FIXME if context.config.struct_lit_style == Visual, but we run out + // FIXME if context.config.struct_lit_style() == Visual, but we run out // of space, we should fall back to BlockIndent. } pub fn type_annotation_separator(config: &Config) -> &str { - colon_spaces(config.space_before_type_annotation, - config.space_after_type_annotation_colon) + colon_spaces(config.space_before_type_annotation(), + config.space_after_type_annotation_colon()) } fn rewrite_field(context: &RewriteContext, field: &ast::Field, shape: Shape) -> Option<String> { @@ -1964,7 +1981,7 @@ pub fn rewrite_tuple<'a, I>(context: &RewriteContext, .next() .unwrap() .rewrite(context, nested_shape) - .map(|s| if context.config.spaces_within_parens { + .map(|s| if context.config.spaces_within_parens() { format!("( {}, )", s) } else { format!("({},)", s) @@ -1983,7 +2000,7 @@ pub fn rewrite_tuple<'a, I>(context: &RewriteContext, span.hi - BytePos(1)); let list_str = try_opt!(format_item_list(items, nested_shape, context.config)); - if context.config.spaces_within_parens && list_str.len() > 0 { + if context.config.spaces_within_parens() && list_str.len() > 0 { Some(format!("( {} )", list_str)) } else { Some(format!("({})", list_str)) diff --git a/src/filemap.rs b/src/filemap.rs index 27f5b990201..d1486e94e39 100644 --- a/src/filemap.rs +++ b/src/filemap.rs @@ -33,11 +33,11 @@ pub fn append_newline(s: &mut StringBuffer) { pub fn write_all_files<T>(file_map: &FileMap, out: &mut T, config: &Config) -> Result<(), io::Error> where T: Write { - output_header(out, config.write_mode).ok(); + output_header(out, config.write_mode()).ok(); for &(ref filename, ref text) in file_map { write_file(text, filename, out, config)?; } - output_footer(out, config.write_mode).ok(); + output_footer(out, config.write_mode()).ok(); Ok(()) } @@ -52,14 +52,14 @@ pub fn write_system_newlines<T>(writer: T, // Buffer output, since we're writing a since char at a time. let mut writer = BufWriter::new(writer); - let style = if config.newline_style == NewlineStyle::Native { + let style = if config.newline_style() == NewlineStyle::Native { if cfg!(windows) { NewlineStyle::Windows } else { NewlineStyle::Unix } } else { - config.newline_style + config.newline_style() }; match style { @@ -107,7 +107,7 @@ pub fn write_file<T>(text: &StringBuffer, Ok(make_diff(&ori, &fmt, 3)) } - match config.write_mode { + match config.write_mode() { WriteMode::Replace => { if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) { if fmt != ori { diff --git a/src/imports.rs b/src/imports.rs index 50c7b4dc938..46ce14f47b7 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -238,7 +238,7 @@ impl<'a> FmtVisitor<'a> { offset.alignment += vis.len() + "use ".len(); // 1 = ";" match vp.rewrite(&self.get_context(), - Shape::legacy(self.config.max_width - offset.width() - 1, offset)) { + Shape::legacy(self.config.max_width() - offset.width() - 1, offset)) { Some(ref s) if s.is_empty() => { // Format up to last newline let prev_span = codemap::mk_sp(self.last_pos, source!(self, span).lo); @@ -339,7 +339,7 @@ pub fn rewrite_use_list(shape: Shape, let has_self = move_self_to_front(&mut items); let first_index = if has_self { 0 } else { 1 }; - if context.config.reorder_imported_names { + if context.config.reorder_imported_names() { items[1..].sort_by(|a, b| a.item.cmp(&b.item)); } diff --git a/src/items.rs b/src/items.rs index 5eb1414c2e0..5fa7a05a142 100644 --- a/src/items.rs +++ b/src/items.rs @@ -94,7 +94,7 @@ struct Item<'a> { impl<'a> Item<'a> { fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> { - let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi { + let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi() { "extern".into() } else { format!("extern {}", fm.abi) @@ -243,7 +243,7 @@ impl<'a> FmtVisitor<'a> { let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi)); let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() || - !context.config.fn_empty_single_line; + !context.config.fn_empty_single_line(); let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context, indent, @@ -260,7 +260,7 @@ impl<'a> FmtVisitor<'a> { has_body, true)); - if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') { + if self.config.fn_brace_style() != BraceStyle::AlwaysNextLine && !result.contains('\n') { newline_brace = false; } else if force_newline_brace { newline_brace = true; @@ -319,12 +319,12 @@ impl<'a> FmtVisitor<'a> { let codemap = self.get_context().codemap; - if self.config.fn_empty_single_line && is_empty_block(block, codemap) && - self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width { + if self.config.fn_empty_single_line() && is_empty_block(block, codemap) && + self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width() { return Some(format!("{}{{}}", fn_str)); } - if self.config.fn_single_line && is_simple_block_stmt(block, codemap) { + if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) { let rewrite = { if let Some(ref stmt) = block.stmts.first() { match stmt_expr(stmt) { @@ -348,7 +348,7 @@ impl<'a> FmtVisitor<'a> { if let Some(res) = rewrite { let width = self.block_indent.width() + fn_str.len() + res.len() + 4; - if !res.contains('\n') && width <= self.config.max_width { + if !res.contains('\n') && width <= self.config.max_width() { return Some(format!("{}{{ {} }}", fn_str, res)); } } @@ -372,7 +372,7 @@ impl<'a> FmtVisitor<'a> { generics, "{", "{", - self.config.item_brace_style, + self.config.item_brace_style(), enum_def.variants.is_empty(), self.block_indent, mk_sp(span.lo, body_start)) @@ -436,7 +436,7 @@ impl<'a> FmtVisitor<'a> { let fmt = ListFormatting { tactic: DefinitiveListTactic::Vertical, separator: ",", - trailing_separator: self.config.trailing_comma, + trailing_separator: self.config.trailing_comma(), shape: shape, ends_with_newline: true, config: self.config, @@ -480,7 +480,7 @@ impl<'a> FmtVisitor<'a> { None, field.span, indent, - Some(self.config.struct_variant_width)) + Some(self.config.struct_variant_width())) } ast::VariantData::Unit(..) => { let tag = if let Some(ref expr) = field.node.disr_expr { @@ -490,7 +490,7 @@ impl<'a> FmtVisitor<'a> { }; wrap_str(tag, - self.config.max_width, + self.config.max_width(), Shape::indented(indent, self.config)) } }; @@ -520,14 +520,14 @@ pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) - let where_budget = try_opt!(context .config - .max_width + .max_width() .checked_sub(last_line_width(&result))); let where_clause_str = try_opt!(rewrite_where_clause(context, &generics.where_clause, - context.config.item_brace_style, + context.config.item_brace_style(), Shape::legacy(where_budget, offset.block_only()), - context.config.where_density, + context.config.where_density(), "{", false, last_line_width(&ref_and_type) == 1, @@ -546,13 +546,13 @@ pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) - if !where_clause_str.is_empty() && !where_clause_str.contains('\n') { result.push('\n'); - let width = offset.block_indent + context.config.tab_spaces - 1; + let width = offset.block_indent + context.config.tab_spaces() - 1; let where_indent = Indent::new(0, width); result.push_str(&where_indent.to_string(context.config)); } result.push_str(&where_clause_str); - match context.config.item_brace_style { + match context.config.item_brace_style() { BraceStyle::AlwaysNextLine => { result.push('\n'); result.push_str(&offset.to_string(context.config)); @@ -615,8 +615,8 @@ fn is_impl_single_line(context: &RewriteContext, let snippet = context.snippet(item.span); let open_pos = try_opt!(snippet.find_uncommented("{")) + 1; - Some(context.config.impl_empty_single_line && items.is_empty() && - result.len() + where_clause_str.len() <= context.config.max_width && + Some(context.config.impl_empty_single_line() && items.is_empty() && + result.len() + where_clause_str.len() <= context.config.max_width() && !contains_comment(&snippet[open_pos..])) } @@ -651,7 +651,7 @@ fn format_impl_ref_and_type(context: &RewriteContext, result.push_str(" "); } let used_space = last_line_width(&result); - let budget = try_opt!(context.config.max_width.checked_sub(used_space)); + let budget = try_opt!(context.config.max_width().checked_sub(used_space)); let indent = offset + used_space; result.push_str(&*try_opt!(trait_ref.rewrite(context, Shape::legacy(budget, indent)))); @@ -659,7 +659,7 @@ fn format_impl_ref_and_type(context: &RewriteContext, result.push('\n'); // Add indentation of one additional tab. - let width = offset.block_indent + context.config.tab_spaces; + let width = offset.block_indent + context.config.tab_spaces(); let for_indent = Indent::new(0, width); result.push_str(&for_indent.to_string(context.config)); @@ -673,7 +673,7 @@ fn format_impl_ref_and_type(context: &RewriteContext, if generics.where_clause.predicates.is_empty() { // If there is no where clause adapt budget for type formatting to take space and curly // brace into account. - match context.config.item_brace_style { + match context.config.item_brace_style() { BraceStyle::AlwaysNextLine => {} BraceStyle::PreferSameLine => used_space += 2, BraceStyle::SameLineWhere => used_space += 2, @@ -681,7 +681,7 @@ fn format_impl_ref_and_type(context: &RewriteContext, } // 1 = space before the type. - let budget = try_opt!(context.config.max_width.checked_sub(used_space + 1)); + let budget = try_opt!(context.config.max_width().checked_sub(used_space + 1)); let indent = offset + result.len() + 1; let self_ty_str = self_ty.rewrite(context, Shape::legacy(budget, indent)); if let Some(self_ty_str) = self_ty_str { @@ -759,11 +759,11 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) let trait_bound_str = try_opt!(rewrite_trait_bounds(context, type_param_bounds, - Shape::legacy(context.config.max_width, offset))); + Shape::legacy(context.config.max_width(), offset))); // If the trait, generics, and trait bound cannot fit on the same line, // put the trait bounds on an indented new line if offset.width() + last_line_width(&result) + trait_bound_str.len() > - context.config.comment_width { + context.config.comment_width() { result.push('\n'); let trait_indent = offset.block_only().block_indent(context.config); result.push_str(&trait_indent.to_string(context.config)); @@ -773,10 +773,11 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) let has_body = !trait_items.is_empty(); let where_density = - if (context.config.where_density == Density::Compressed && - (!result.contains('\n') || context.config.fn_args_layout == IndentStyle::Block)) || - (context.config.fn_args_layout == IndentStyle::Block && result.is_empty()) || - (context.config.where_density == Density::CompressedIfEmpty && !has_body && + if (context.config.where_density() == Density::Compressed && + (!result.contains('\n') || + context.config.fn_args_layout() == IndentStyle::Block)) || + (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty()) || + (context.config.where_density() == Density::CompressedIfEmpty && !has_body && !result.contains('\n')) { Density::Compressed } else { @@ -785,11 +786,11 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) let where_budget = try_opt!(context .config - .max_width + .max_width() .checked_sub(last_line_width(&result))); let where_clause_str = try_opt!(rewrite_where_clause(context, &generics.where_clause, - context.config.item_brace_style, + context.config.item_brace_style(), Shape::legacy(where_budget, offset.block_only()), where_density, @@ -802,15 +803,15 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) // put the where clause on a new line if !where_clause_str.contains('\n') && last_line_width(&result) + where_clause_str.len() + offset.width() > - context.config.comment_width { + context.config.comment_width() { result.push('\n'); - let width = offset.block_indent + context.config.tab_spaces - 1; + let width = offset.block_indent + context.config.tab_spaces() - 1; let where_indent = Indent::new(0, width); result.push_str(&where_indent.to_string(context.config)); } result.push_str(&where_clause_str); - match context.config.item_brace_style { + match context.config.item_brace_style() { BraceStyle::AlwaysNextLine => { result.push('\n'); result.push_str(&offset.to_string(context.config)); @@ -888,13 +889,14 @@ fn format_struct_struct(context: &RewriteContext, g, "{", "{", - context.config.item_brace_style, + context.config.item_brace_style(), fields.is_empty(), offset, mk_sp(span.lo, body_lo))) } None => { - if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() { + if context.config.item_brace_style() == BraceStyle::AlwaysNextLine && + !fields.is_empty() { format!("\n{}{{", offset.block_only().to_string(context.config)) } else { " {".to_owned() @@ -923,7 +925,7 @@ fn format_struct_struct(context: &RewriteContext, // 1 = "," let item_budget = try_opt!(context .config - .max_width + .max_width() .checked_sub(item_indent.width() + 1)); let items = @@ -944,7 +946,7 @@ fn format_struct_struct(context: &RewriteContext, span.hi) .collect::<Vec<_>>(); // 1 = , - let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1; + let budget = context.config.max_width() - offset.width() + context.config.tab_spaces() - 1; let tactic = match one_line_width { Some(w) => definitive_tactic(&items, ListTactic::LimitedHorizontalVertical(w), budget), @@ -954,7 +956,7 @@ fn format_struct_struct(context: &RewriteContext, let fmt = ListFormatting { tactic: tactic, separator: ",", - trailing_separator: context.config.trailing_comma, + trailing_separator: context.config.trailing_comma(), shape: Shape::legacy(budget, item_indent), ends_with_newline: true, config: context.config, @@ -1003,11 +1005,11 @@ fn format_tuple_struct(context: &RewriteContext, let where_budget = try_opt!(context .config - .max_width + .max_width() .checked_sub(last_line_width(&result))); try_opt!(rewrite_where_clause(context, &generics.where_clause, - context.config.item_brace_style, + context.config.item_brace_style(), Shape::legacy(where_budget, offset.block_only()), Density::Compressed, ";", @@ -1032,7 +1034,7 @@ fn format_tuple_struct(context: &RewriteContext, } result.push(')'); } else { - let (tactic, item_indent) = match context.config.fn_args_layout { + let (tactic, item_indent) = match context.config.fn_args_layout() { IndentStyle::Visual => { // 1 = `(` (ListTactic::HorizontalVertical, offset.block_only() + result.len() + 1) @@ -1044,7 +1046,7 @@ fn format_tuple_struct(context: &RewriteContext, // 3 = `();` let item_budget = try_opt!(context .config - .max_width + .max_width() .checked_sub(item_indent.width() + 3)); let items = @@ -1065,7 +1067,7 @@ fn format_tuple_struct(context: &RewriteContext, span.hi); let body_budget = try_opt!(context .config - .max_width + .max_width() .checked_sub(offset.block_only().width() + result.len() + 3)); let body = try_opt!(list_helper(items, @@ -1074,15 +1076,15 @@ fn format_tuple_struct(context: &RewriteContext, context.config, tactic)); - if context.config.fn_args_layout == IndentStyle::Visual || !body.contains('\n') { + if context.config.fn_args_layout() == IndentStyle::Visual || !body.contains('\n') { result.push('('); - if context.config.spaces_within_parens && body.len() > 0 { + if context.config.spaces_within_parens() && body.len() > 0 { result.push(' '); } result.push_str(&body); - if context.config.spaces_within_parens && body.len() > 0 { + if context.config.spaces_within_parens() && body.len() > 0 { result.push(' '); } result.push(')'); @@ -1099,11 +1101,11 @@ fn format_tuple_struct(context: &RewriteContext, if !where_clause_str.is_empty() && !where_clause_str.contains('\n') && (result.contains('\n') || offset.block_indent + result.len() + where_clause_str.len() + 1 > - context.config.max_width) { + context.config.max_width()) { // We need to put the where clause on a new line, but we didn't // know that earlier, so the where clause will not be indented properly. result.push('\n'); - result.push_str(&(offset.block_only() + (context.config.tab_spaces - 1)) + result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1)) .to_string(context.config)); } result.push_str(&where_clause_str); @@ -1135,13 +1137,13 @@ pub fn rewrite_type_alias(context: &RewriteContext, let where_budget = try_opt!(context .config - .max_width + .max_width() .checked_sub(last_line_width(&result))); let where_clause_str = try_opt!(rewrite_where_clause(context, &generics.where_clause, - context.config.item_brace_style, + context.config.item_brace_style(), Shape::legacy(where_budget, indent), - context.config.where_density, + context.config.where_density(), "=", true, true, @@ -1154,7 +1156,7 @@ pub fn rewrite_type_alias(context: &RewriteContext, // In that case the budget is set to 0 which will make ty.rewrite retry on a new line let budget = context .config - .max_width + .max_width() .checked_sub(indent.width() + line_width + ";".len()) .unwrap_or(0); let type_indent = indent + line_width; @@ -1170,7 +1172,7 @@ pub fn rewrite_type_alias(context: &RewriteContext, result.push_str(&type_indent.to_string(context.config)); let budget = try_opt!(context .config - .max_width + .max_width() .checked_sub(type_indent.width() + ";".len())); ty.rewrite(context, Shape::legacy(budget, type_indent)) })); @@ -1180,12 +1182,12 @@ pub fn rewrite_type_alias(context: &RewriteContext, } fn type_annotation_spacing(config: &Config) -> (&str, &str) { - (if config.space_before_type_annotation { + (if config.space_before_type_annotation() { " " } else { "" }, - if config.space_after_type_annotation_colon { + if config.space_after_type_annotation_colon() { " " } else { "" @@ -1196,7 +1198,7 @@ impl Rewrite for ast::StructField { fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> { if contains_skip(&self.attrs) { let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi)); - return wrap_str(span, context.config.max_width, shape); + return wrap_str(span, context.config.max_width(), shape); } let name = self.ident; @@ -1232,7 +1234,7 @@ impl Rewrite for ast::StructField { match new_ty { Some(ref new_ty) if !new_ty.contains('\n') && new_ty.len() + type_offset.width() <= - context.config.max_width => { + context.config.max_width() => { Some(format!("{}\n{}{}", result, type_offset.to_string(&context.config), @@ -1282,7 +1284,8 @@ pub fn rewrite_static(prefix: &str, type_annotation_spacing.1); // 2 = " =".len() let ty_str = try_opt!(ty.rewrite(context, - Shape::legacy(context.config.max_width - offset.block_indent - + Shape::legacy(context.config.max_width() - + offset.block_indent - prefix.len() - 2, offset.block_only()))); @@ -1290,7 +1293,7 @@ pub fn rewrite_static(prefix: &str, if let Some(expr) = expr_opt { let lhs = format!("{}{} =", prefix, ty_str); // 1 = ; - let remaining_width = context.config.max_width - offset.block_indent - 1; + let remaining_width = context.config.max_width() - offset.block_indent - 1; rewrite_assign_rhs(context, lhs, expr, @@ -1310,31 +1313,32 @@ pub fn rewrite_associated_type(ident: ast::Ident, -> Option<String> { let prefix = format!("type {}", ident); - let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt { - let joiner = match context.config.type_punctuation_density { - TypeDensity::Compressed => "+", - TypeDensity::Wide => " + ", - }; - let bounds: &[_] = ty_param_bounds; - let bound_str = try_opt!(bounds - .iter() - .map(|ty_bound| { - ty_bound.rewrite(context, Shape::legacy(context.config.max_width, indent)) - }) - .intersperse(Some(joiner.to_string())) - .collect::<Option<String>>()); - if bounds.len() > 0 { - format!(": {}", bound_str) + let type_bounds_str = + if let Some(ty_param_bounds) = ty_param_bounds_opt { + let joiner = match context.config.type_punctuation_density() { + TypeDensity::Compressed => "+", + TypeDensity::Wide => " + ", + }; + let bounds: &[_] = ty_param_bounds; + let bound_str = try_opt!(bounds + .iter() + .map(|ty_bound| { + ty_bound.rewrite(context, Shape::legacy(context.config.max_width(), indent)) + }) + .intersperse(Some(joiner.to_string())) + .collect::<Option<String>>()); + if bounds.len() > 0 { + format!(": {}", bound_str) + } else { + String::new() + } } else { String::new() - } - } else { - String::new() - }; + }; if let Some(ty) = ty_opt { let ty_str = try_opt!(ty.rewrite(context, - Shape::legacy(context.config.max_width - + Shape::legacy(context.config.max_width() - indent.block_indent - prefix.len() - 2, @@ -1382,11 +1386,11 @@ impl Rewrite for ast::Arg { Shape::legacy(shape.width, shape.indent))); if self.ty.node != ast::TyKind::Infer { - if context.config.space_before_type_annotation { + if context.config.space_before_type_annotation() { result.push_str(" "); } result.push_str(":"); - if context.config.space_after_type_annotation_colon { + if context.config.space_after_type_annotation_colon() { result.push_str(" "); } let max_width = try_opt!(shape.width.checked_sub(result.len())); @@ -1539,7 +1543,7 @@ fn rewrite_fn_base(context: &RewriteContext, result.push_str(::utils::format_unsafety(unsafety)); if abi != abi::Abi::Rust { - result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi)); + result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi())); } // fn foo @@ -1567,9 +1571,9 @@ fn rewrite_fn_base(context: &RewriteContext, let (mut one_line_budget, mut multi_line_budget, mut arg_indent) = try_opt!(compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace)); - if context.config.fn_args_layout == IndentStyle::Block { + if context.config.fn_args_layout() == IndentStyle::Block { arg_indent = indent.block_indent(context.config); - multi_line_budget = context.config.max_width - arg_indent.width(); + multi_line_budget = context.config.max_width() - arg_indent.width(); } debug!("rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}", @@ -1581,12 +1585,12 @@ fn rewrite_fn_base(context: &RewriteContext, if one_line_budget == 0 { if snuggle_angle_bracket { result.push_str("("); - } else if context.config.fn_args_paren_newline { + } else if context.config.fn_args_paren_newline() { result.push('\n'); result.push_str(&arg_indent.to_string(context.config)); arg_indent = arg_indent + 1; // extra space for `(` result.push('('); - if context.config.spaces_within_parens && fd.inputs.len() > 0 { + if context.config.spaces_within_parens() && fd.inputs.len() > 0 { result.push(' ') } } else { @@ -1595,7 +1599,7 @@ fn rewrite_fn_base(context: &RewriteContext, } } else { result.push('('); - if context.config.spaces_within_parens && fd.inputs.len() > 0 { + if context.config.spaces_within_parens() && fd.inputs.len() > 0 { result.push(' ') } } @@ -1624,7 +1628,7 @@ fn rewrite_fn_base(context: &RewriteContext, let multi_line_arg_str = arg_str.contains('\n'); - let put_args_in_block = match context.config.fn_args_layout { + let put_args_in_block = match context.config.fn_args_layout() { IndentStyle::Block => multi_line_arg_str || generics_str.contains('\n'), _ => false, } && !fd.inputs.is_empty(); @@ -1639,7 +1643,7 @@ fn rewrite_fn_base(context: &RewriteContext, result.push(')'); } else { result.push_str(&arg_str); - if context.config.spaces_within_parens && fd.inputs.len() > 0 { + if context.config.spaces_within_parens() && fd.inputs.len() > 0 { result.push(' ') } result.push(')'); @@ -1647,7 +1651,7 @@ fn rewrite_fn_base(context: &RewriteContext, // Return type. if !ret_str.is_empty() { - let ret_should_indent = match context.config.fn_args_layout { + let ret_should_indent = match context.config.fn_args_layout() { // If our args are block layout then we surely must have space. IndentStyle::Block if put_args_in_block => false, _ => { @@ -1663,13 +1667,13 @@ fn rewrite_fn_base(context: &RewriteContext, sig_length += 2; } - let overlong_sig = sig_length > context.config.max_width; + let overlong_sig = sig_length > context.config.max_width(); result.contains('\n') || multi_line_ret_str || overlong_sig } }; let ret_indent = if ret_should_indent { - let indent = match context.config.fn_return_indent { + let indent = match context.config.fn_return_indent() { ReturnIndent::WithWhereClause => indent + 4, // Aligning with non-existent args looks silly. _ if arg_str.is_empty() => { @@ -1718,7 +1722,7 @@ fn rewrite_fn_base(context: &RewriteContext, } } - let should_compress_where = match context.config.where_density { + let should_compress_where = match context.config.where_density() { Density::Compressed => !result.contains('\n') || put_args_in_block, Density::CompressedIfEmpty => !has_body && !result.contains('\n'), _ => false, @@ -1727,12 +1731,12 @@ fn rewrite_fn_base(context: &RewriteContext, if where_clause.predicates.len() == 1 && should_compress_where { let budget = try_opt!(context .config - .max_width + .max_width() .checked_sub(last_line_width(&result))); if let Some(where_clause_str) = rewrite_where_clause(context, where_clause, - context.config.fn_brace_style, + context.config.fn_brace_style(), Shape::legacy(budget, indent), Density::Compressed, "{", @@ -1740,7 +1744,7 @@ fn rewrite_fn_base(context: &RewriteContext, put_args_in_block && ret_str.is_empty(), Some(span.hi)) { if !where_clause_str.contains('\n') { - if last_line_width(&result) + where_clause_str.len() > context.config.max_width { + if last_line_width(&result) + where_clause_str.len() > context.config.max_width() { result.push('\n'); } @@ -1753,7 +1757,7 @@ fn rewrite_fn_base(context: &RewriteContext, let where_clause_str = try_opt!(rewrite_where_clause(context, where_clause, - context.config.fn_brace_style, + context.config.fn_brace_style(), Shape::indented(indent, context.config), Density::Tall, "{", @@ -1859,7 +1863,7 @@ fn rewrite_args(context: &RewriteContext, item.item = Some(arg); } - let (indent, trailing_comma, end_with_newline) = match context.config.fn_args_layout { + let (indent, trailing_comma, end_with_newline) = match context.config.fn_args_layout() { IndentStyle::Block if !generics_str_contains_newline && arg_items.len() <= 1 => { (indent.block_indent(context.config), SeparatorTactic::Never, true) } @@ -1870,7 +1874,7 @@ fn rewrite_args(context: &RewriteContext, }; let tactic = definitive_tactic(&arg_items, - context.config.fn_args_density.to_list_tactic(), + context.config.fn_args_density().to_list_tactic(), one_line_budget); let budget = match tactic { DefinitiveListTactic::Horizontal => one_line_budget, @@ -1919,7 +1923,7 @@ fn compute_budgets_for_args(context: &RewriteContext, } let one_line_budget = context .config - .max_width + .max_width() .checked_sub(used_space) .unwrap_or(0); @@ -1927,7 +1931,7 @@ fn compute_budgets_for_args(context: &RewriteContext, // 4 = "() {".len() let multi_line_budget = try_opt!(context .config - .max_width + .max_width() .checked_sub(indent.width() + result.len() + 4)); @@ -1938,7 +1942,7 @@ fn compute_budgets_for_args(context: &RewriteContext, // Didn't work. we must force vertical layout and put args on a newline. let new_indent = indent.block_indent(context.config); let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`. - let max_space = context.config.max_width; + let max_space = context.config.max_width(); if used_space <= max_space { Some((0, max_space - used_space, new_indent)) } else { @@ -1948,7 +1952,7 @@ fn compute_budgets_for_args(context: &RewriteContext, } fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool { - match config.fn_brace_style { + match config.fn_brace_style() { BraceStyle::AlwaysNextLine => true, BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true, _ => false, @@ -1968,7 +1972,7 @@ fn rewrite_generics(context: &RewriteContext, return Some(String::new()); } - let offset = match context.config.generics_indent { + let offset = match context.config.generics_indent() { IndentStyle::Block => shape.indent.block_only().block_indent(context.config), // 1 = < IndentStyle::Visual => shape.indent + 1, @@ -2009,13 +2013,13 @@ fn rewrite_generics(context: &RewriteContext, let list_str = try_opt!(format_item_list(items, Shape::legacy(h_budget, offset), context.config)); - let result = if context.config.generics_indent != IndentStyle::Visual && + let result = if context.config.generics_indent() != IndentStyle::Visual && list_str.contains('\n') { format!("<\n{}{}\n{}>", offset.to_string(context.config), list_str, shape.indent.block_only().to_string(context.config)) - } else if context.config.spaces_within_angle_brackets { + } else if context.config.spaces_within_angle_brackets() { format!("< {} >", list_str) } else { format!("<{}>", list_str) @@ -2032,7 +2036,7 @@ fn rewrite_trait_bounds(context: &RewriteContext, if bounds.is_empty() { return Some(String::new()); } - let joiner = match context.config.type_punctuation_density { + let joiner = match context.config.type_punctuation_density() { TypeDensity::Compressed => "+", TypeDensity::Wide => " + ", }; @@ -2077,7 +2081,7 @@ fn rewrite_where_clause_rfc_style(context: &RewriteContext, "\n".to_owned() + &block_shape.indent.to_string(context.config) }; - let clause_shape = block_shape.block_indent(context.config.tab_spaces); + let clause_shape = block_shape.block_indent(context.config.tab_spaces()); // each clause on one line, trailing comma (except if suppress_comma) let span_start = span_for_where_pred(&where_clause.predicates[0]).lo; // If we don't have the start of the next span, then use the end of the @@ -2129,7 +2133,7 @@ fn rewrite_where_clause(context: &RewriteContext, return Some(String::new()); } - if context.config.where_style == Style::Rfc { + if context.config.where_style() == Style::Rfc { return rewrite_where_clause_rfc_style(context, where_clause, shape, @@ -2139,9 +2143,9 @@ fn rewrite_where_clause(context: &RewriteContext, span_end); } - let extra_indent = Indent::new(context.config.tab_spaces, 0); + let extra_indent = Indent::new(context.config.tab_spaces(), 0); - let offset = match context.config.where_pred_indent { + let offset = match context.config.where_pred_indent() { IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config), // 6 = "where ".len() IndentStyle::Visual => shape.indent + extra_indent + 6, @@ -2149,7 +2153,7 @@ fn rewrite_where_clause(context: &RewriteContext, // FIXME: if where_pred_indent != Visual, then the budgets below might // be out by a char or two. - let budget = context.config.max_width - offset.width(); + let budget = context.config.max_width() - offset.width(); let span_start = span_for_where_pred(&where_clause.predicates[0]).lo; // If we don't have the start of the next span, then use the end of the // predicates, but that means we miss comments. @@ -2167,9 +2171,9 @@ fn rewrite_where_clause(context: &RewriteContext, let item_vec = items.collect::<Vec<_>>(); // FIXME: we don't need to collect here if the where_layout isn't // HorizontalVertical. - let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget); + let tactic = definitive_tactic(&item_vec, context.config.where_layout(), budget); - let mut comma_tactic = context.config.trailing_comma; + let mut comma_tactic = context.config.trailing_comma(); // Kind of a hack because we don't usually have trailing commas in where clauses. if comma_tactic == SeparatorTactic::Vertical || suppress_comma { comma_tactic = SeparatorTactic::Never; @@ -2227,7 +2231,7 @@ fn format_generics(context: &RewriteContext, if !generics.where_clause.predicates.is_empty() || result.contains('\n') { let budget = try_opt!(context .config - .max_width + .max_width() .checked_sub(last_line_width(&result))); let where_clause_str = try_opt!(rewrite_where_clause(context, diff --git a/src/lib.rs b/src/lib.rs index 99054b23712..8c112b5f8af 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -145,12 +145,12 @@ impl Indent { } pub fn block_indent(mut self, config: &Config) -> Indent { - self.block_indent += config.tab_spaces; + self.block_indent += config.tab_spaces(); self } pub fn block_unindent(mut self, config: &Config) -> Indent { - self.block_indent -= config.tab_spaces; + self.block_indent -= config.tab_spaces(); self } @@ -159,8 +159,8 @@ impl Indent { } pub fn to_string(&self, config: &Config) -> String { - let (num_tabs, num_spaces) = if config.hard_tabs { - (self.block_indent / config.tab_spaces, self.alignment) + let (num_tabs, num_spaces) = if config.hard_tabs() { + (self.block_indent / config.tab_spaces(), self.alignment) } else { (0, self.width()) }; @@ -248,7 +248,7 @@ impl Shape { pub fn indented(indent: Indent, config: &Config) -> Shape { Shape { - width: config.max_width.checked_sub(indent.width()).unwrap_or(0), + width: config.max_width().checked_sub(indent.width()).unwrap_or(0), indent: indent, offset: indent.alignment, } @@ -257,7 +257,7 @@ impl Shape { pub fn with_max_width(&self, config: &Config) -> Shape { Shape { width: config - .max_width + .max_width() .checked_sub(self.indent.width()) .unwrap_or(0), ..*self @@ -442,13 +442,13 @@ fn format_ast<F>(krate: &ast::Crate, // We always skip children for the "Plain" write mode, since there is // nothing to distinguish the nested module contents. - let skip_children = config.skip_children || config.write_mode == config::WriteMode::Plain; + let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain; for (path, module) in modules::list_files(krate, parse_session.codemap()) { if skip_children && path.as_path() != main_file { continue; } let path = path.to_str().unwrap(); - if config.verbose { + if config.verbose() { println!("Formatting {}", path); } let mut visitor = FmtVisitor::from_codemap(parse_session, config); @@ -473,14 +473,14 @@ fn format_lines(text: &mut StringBuffer, name: &str, config: &Config, report: &m let mut cur_line = 1; let mut newline_count = 0; let mut errors = vec![]; - let mut issue_seeker = BadIssueSeeker::new(config.report_todo, config.report_fixme); + let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme()); for (c, b) in text.chars() { if c == '\r' { continue; } - let format_line = config.file_lines.contains_line(name, cur_line as usize); + let format_line = config.file_lines().contains_line(name, cur_line as usize); if format_line { // Add warnings for bad todos/ fixmes @@ -501,10 +501,10 @@ fn format_lines(text: &mut StringBuffer, name: &str, config: &Config, report: &m } // Check for any line width errors we couldn't correct. - if config.error_on_line_overflow && line_len > config.max_width { + if config.error_on_line_overflow() && line_len > config.max_width() { errors.push(FormattingError { line: cur_line, - kind: ErrorKind::LineOverflow(line_len, config.max_width), + kind: ErrorKind::LineOverflow(line_len, config.max_width()), }); } } @@ -577,7 +577,7 @@ pub fn format_input<T: Write>(input: Input, mut out: Option<&mut T>) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> { let mut summary = Summary::new(); - if config.disable_all_formatting { + if config.disable_all_formatting() { return Ok((summary, FileMap::new(), FormatReport::new())); } let codemap = Rc::new(CodeMap::new()); @@ -651,10 +651,10 @@ pub enum Input { pub fn run(input: Input, config: &Config) -> Summary { let mut out = &mut stdout(); - output_header(out, config.write_mode).ok(); + output_header(out, config.write_mode()).ok(); match format_input(input, config, Some(out)) { Ok((summary, _, report)) => { - output_footer(out, config.write_mode).ok(); + output_footer(out, config.write_mode()).ok(); if report.has_warnings() { msg!("{}", report); @@ -708,7 +708,9 @@ mod test { #[test] fn indent_to_string_hard_tabs() { let mut config = Config::default(); - config.hard_tabs = true; + config + .override_value("hard_tabs", "true") + .expect("Could not set hard_tabs to true"); let indent = Indent::new(8, 4); // 2 tabs + 4 spaces @@ -719,10 +721,10 @@ mod test { fn shape_visual_indent() { let config = Config::default(); let indent = Indent::new(4, 8); - let shape = Shape::legacy(config.max_width, indent); + let shape = Shape::legacy(config.max_width(), indent); let shape = shape.visual_indent(20); - assert_eq!(config.max_width, shape.width); + assert_eq!(config.max_width(), shape.width); assert_eq!(4, shape.indent.block_indent); assert_eq!(28, shape.indent.alignment); assert_eq!(28, shape.offset); @@ -732,10 +734,10 @@ mod test { fn shape_block_indent_without_alignment() { let config = Config::default(); let indent = Indent::new(4, 0); - let shape = Shape::legacy(config.max_width, indent); + let shape = Shape::legacy(config.max_width(), indent); let shape = shape.block_indent(20); - assert_eq!(config.max_width, shape.width); + assert_eq!(config.max_width(), shape.width); assert_eq!(24, shape.indent.block_indent); assert_eq!(0, shape.indent.alignment); assert_eq!(0, shape.offset); @@ -745,10 +747,10 @@ mod test { fn shape_block_indent_with_alignment() { let config = Config::default(); let indent = Indent::new(4, 8); - let shape = Shape::legacy(config.max_width, indent); + let shape = Shape::legacy(config.max_width(), indent); let shape = shape.block_indent(20); - assert_eq!(config.max_width, shape.width); + assert_eq!(config.max_width(), shape.width); assert_eq!(4, shape.indent.block_indent); assert_eq!(28, shape.indent.alignment); assert_eq!(28, shape.offset); diff --git a/src/lists.rs b/src/lists.rs index 7933ebab807..5e03afff6fd 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -73,7 +73,7 @@ pub fn format_fn_args<I>(items: I, shape: Shape, config: &Config) -> Option<Stri list_helper(items, shape, config, - ListTactic::LimitedHorizontalVertical(config.fn_call_width)) + ListTactic::LimitedHorizontalVertical(config.fn_call_width())) } pub fn format_item_list<I>(items: I, shape: Shape, config: &Config) -> Option<String> @@ -527,14 +527,14 @@ pub fn struct_lit_shape(shape: Shape, prefix_width: usize, suffix_width: usize) -> Option<(Option<Shape>, Shape)> { - let v_shape = match context.config.struct_lit_style { + let v_shape = match context.config.struct_lit_style() { IndentStyle::Visual => { try_opt!(try_opt!(shape.shrink_left(prefix_width)).sub_width(suffix_width)) } IndentStyle::Block => { - let shape = shape.block_indent(context.config.tab_spaces); + let shape = shape.block_indent(context.config.tab_spaces()); Shape { - width: try_opt!(context.config.max_width.checked_sub(shape.indent.width())), + width: try_opt!(context.config.max_width().checked_sub(shape.indent.width())), ..shape } } @@ -549,13 +549,14 @@ pub fn struct_lit_tactic(h_shape: Option<Shape>, items: &[ListItem]) -> DefinitiveListTactic { if let Some(h_shape) = h_shape { - let mut prelim_tactic = match (context.config.struct_lit_style, items.len()) { + let mut prelim_tactic = match (context.config.struct_lit_style(), items.len()) { (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical, - _ => context.config.struct_lit_multiline_style.to_list_tactic(), + _ => context.config.struct_lit_multiline_style().to_list_tactic(), }; if prelim_tactic == ListTactic::HorizontalVertical && items.len() > 1 { - prelim_tactic = ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width); + prelim_tactic = + ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width()); } definitive_tactic(items, prelim_tactic, h_shape.width) @@ -583,7 +584,7 @@ pub fn struct_lit_formatting<'a>(shape: Shape, context: &'a RewriteContext, force_no_trailing_comma: bool) -> ListFormatting<'a> { - let ends_with_newline = context.config.struct_lit_style != IndentStyle::Visual && + let ends_with_newline = context.config.struct_lit_style() != IndentStyle::Visual && tactic == DefinitiveListTactic::Vertical; ListFormatting { tactic: tactic, @@ -591,7 +592,7 @@ pub fn struct_lit_formatting<'a>(shape: Shape, trailing_separator: if force_no_trailing_comma { SeparatorTactic::Never } else { - context.config.trailing_comma + context.config.trailing_comma() }, shape: shape, ends_with_newline: ends_with_newline, diff --git a/src/macros.rs b/src/macros.rs index 8f998e42035..98472d67fa7 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -67,7 +67,7 @@ pub fn rewrite_macro(mac: &ast::Mac, -> Option<String> { let mut context = &mut context.clone(); context.inside_macro = true; - if context.config.use_try_shorthand { + if context.config.use_try_shorthand() { if let Some(expr) = convert_try_mac(mac, context) { return expr.rewrite(context, shape); } diff --git a/src/missed_spans.rs b/src/missed_spans.rs index 843556b9b38..40b6bdd8ce9 100644 --- a/src/missed_spans.rs +++ b/src/missed_spans.rs @@ -116,7 +116,7 @@ impl<'a> FmtVisitor<'a> { .collect() } - let replaced = match self.config.write_mode { + let replaced = match self.config.write_mode() { WriteMode::Coverage => replace_chars(old_snippet), _ => old_snippet.to_owned(), }; @@ -138,7 +138,7 @@ impl<'a> FmtVisitor<'a> { if rewrite_next_comment && !self.config - .file_lines + .file_lines() .intersects_range(file_name, cur_line, cur_line + subslice_num_lines) { rewrite_next_comment = false; } @@ -154,8 +154,8 @@ impl<'a> FmtVisitor<'a> { self.buffer.push_str(" "); } - let comment_width = ::std::cmp::min(self.config.comment_width, - self.config.max_width - + let comment_width = ::std::cmp::min(self.config.comment_width(), + self.config.max_width() - self.block_indent.width()); self.buffer @@ -197,7 +197,7 @@ impl<'a> FmtVisitor<'a> { i += offset; if c == '\n' { - if !self.config.file_lines.contains_line(file_name, cur_line) { + if !self.config.file_lines().contains_line(file_name, cur_line) { last_wspace = None; } diff --git a/src/patterns.rs b/src/patterns.rs index 75175cc7667..7dd146efdf9 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -51,7 +51,7 @@ impl Rewrite for Pat { }; let result = format!("{}{}{}{}", prefix, mut_infix, id_str, sub_pat); - wrap_str(result, context.config.max_width, shape) + wrap_str(result, context.config.max_width(), shape) } PatKind::Wild => { if 1 <= shape.width { @@ -108,19 +108,21 @@ impl Rewrite for Pat { let pats = try_opt!(pats); // Unwrap all the sub-strings and join them with commas. - let result = if context.config.spaces_within_square_brackets { + let result = if context.config.spaces_within_square_brackets() { format!("[ {} ]", pats.join(", ")) } else { format!("[{}]", pats.join(", ")) }; - wrap_str(result, context.config.max_width, shape) + wrap_str(result, context.config.max_width(), shape) } PatKind::Struct(ref path, ref fields, elipses) => { rewrite_struct_pat(path, fields, elipses, self.span, context, shape) } // FIXME(#819) format pattern macros. PatKind::Mac(..) => { - wrap_str(context.snippet(self.span), context.config.max_width, shape) + wrap_str(context.snippet(self.span), + context.config.max_width(), + shape) } } } @@ -187,9 +189,10 @@ fn rewrite_struct_pat(path: &ast::Path, } - let fields_str = if context.config.struct_lit_style == IndentStyle::Block && + let fields_str = if context.config.struct_lit_style() == IndentStyle::Block && (fields_str.contains('\n') || - context.config.struct_lit_multiline_style == MultilineStyle::ForceMulti || + context.config.struct_lit_multiline_style() == + MultilineStyle::ForceMulti || fields_str.len() > h_shape.map(|s| s.width).unwrap_or(0)) { format!("\n{}{}\n{}", v_shape.indent.to_string(context.config), @@ -210,7 +213,7 @@ impl Rewrite for FieldPat { pat } else { wrap_str(format!("{}: {}", self.ident.to_string(), try_opt!(pat)), - context.config.max_width, + context.config.max_width(), shape) } } @@ -296,7 +299,7 @@ fn rewrite_tuple_pat(pats: &[ptr::P<ast::Pat>], // Condense wildcard string suffix into a single .. let wildcard_suffix_len = count_wildcard_suffix_len(&items); - let list = if context.config.condense_wildcard_suffices && wildcard_suffix_len >= 2 { + let list = if context.config.condense_wildcard_suffices() && wildcard_suffix_len >= 2 { let new_item_count = 1 + pats.len() - wildcard_suffix_len; items[new_item_count - 1].item = Some("..".to_owned()); @@ -308,7 +311,7 @@ fn rewrite_tuple_pat(pats: &[ptr::P<ast::Pat>], match path_str { Some(path_str) => { - Some(if context.config.spaces_within_parens { + Some(if context.config.spaces_within_parens() { format!("{}( {} )", path_str, list) } else { format!("{}({})", path_str, list) @@ -316,7 +319,7 @@ fn rewrite_tuple_pat(pats: &[ptr::P<ast::Pat>], } None => { let comma = if add_comma { "," } else { "" }; - Some(if context.config.spaces_within_parens { + Some(if context.config.spaces_within_parens() { format!("( {}{} )", list, comma) } else { format!("({}{})", list, comma) diff --git a/src/string.rs b/src/string.rs index 37a569ce67d..365d205aef1 100644 --- a/src/string.rs +++ b/src/string.rs @@ -119,7 +119,7 @@ pub fn rewrite_string<'a>(orig: &str, fmt: &StringFormat<'a>) -> Option<String> } result.push_str(fmt.closer); - wrap_str(result, fmt.config.max_width, fmt.shape) + wrap_str(result, fmt.config.max_width(), fmt.shape) } #[cfg(test)] diff --git a/src/types.rs b/src/types.rs index 754db673013..a0e7246e29d 100644 --- a/src/types.rs +++ b/src/types.rs @@ -53,7 +53,7 @@ pub fn rewrite_path(context: &RewriteContext, if let Some(qself) = qself { result.push('<'); - if context.config.spaces_within_angle_brackets { + if context.config.spaces_within_angle_brackets() { result.push_str(" ") } @@ -79,7 +79,7 @@ pub fn rewrite_path(context: &RewriteContext, shape)); } - if context.config.spaces_within_angle_brackets { + if context.config.spaces_within_angle_brackets() { result.push_str(" ") } @@ -158,7 +158,7 @@ impl<'a> Rewrite for SegmentParam<'a> { SegmentParam::LifeTime(lt) => lt.rewrite(context, shape), SegmentParam::Type(ty) => ty.rewrite(context, shape), SegmentParam::Binding(binding) => { - let mut result = match context.config.type_punctuation_density { + let mut result = match context.config.type_punctuation_density() { TypeDensity::Wide => format!("{} = ", binding.ident), TypeDensity::Compressed => format!("{}=", binding.ident), }; @@ -237,7 +237,7 @@ fn rewrite_segment(path_context: PathContext, // Update position of last bracket. *span_lo = next_span_lo; - if context.config.spaces_within_angle_brackets && list_str.len() > 0 { + if context.config.spaces_within_angle_brackets() && list_str.len() > 0 { format!("{}< {} >", separator, list_str) } else { format!("{}<{}>", separator, list_str) @@ -338,7 +338,7 @@ fn format_function_type<'a, I>(inputs: I, String::new() }; - Some(if context.config.spaces_within_parens { + Some(if context.config.spaces_within_parens() { format!("( {} ){}{}", list_str, infix, output) } else { format!("({}){}{}", list_str, infix, output) @@ -346,8 +346,8 @@ fn format_function_type<'a, I>(inputs: I, } fn type_bound_colon(context: &RewriteContext) -> &'static str { - colon_spaces(context.config.space_before_bound, - context.config.space_after_bound_colon) + colon_spaces(context.config.space_before_bound(), + context.config.space_after_bound_colon()) } impl Rewrite for ast::WherePredicate { @@ -370,7 +370,7 @@ impl Rewrite for ast::WherePredicate { .intersperse(Some(", ".to_string())) .collect()); - let joiner = match context.config.type_punctuation_density { + let joiner = match context.config.type_punctuation_density() { TypeDensity::Compressed => "+", TypeDensity::Wide => " + ", }; @@ -386,7 +386,7 @@ impl Rewrite for ast::WherePredicate { .intersperse(Some(joiner.to_string())) .collect()); - if context.config.spaces_within_angle_brackets && lifetime_str.len() > 0 { + if context.config.spaces_within_angle_brackets() && lifetime_str.len() > 0 { format!("for< {} > {}{}{}", lifetime_str, type_str, @@ -396,7 +396,7 @@ impl Rewrite for ast::WherePredicate { format!("for<{}> {}{}{}", lifetime_str, type_str, colon, bounds_str) } } else { - let joiner = match context.config.type_punctuation_density { + let joiner = match context.config.type_punctuation_density() { TypeDensity::Compressed => "+", TypeDensity::Wide => " + ", }; @@ -437,7 +437,7 @@ impl Rewrite for ast::WherePredicate { } }; - wrap_str(result, context.config.max_width, shape) + wrap_str(result, context.config.max_width(), shape) } } @@ -464,12 +464,12 @@ fn rewrite_bounded_lifetime<'b, I>(lt: &ast::Lifetime, .map(|b| b.rewrite(context, shape)) .collect()); let colon = type_bound_colon(context); - let joiner = match context.config.type_punctuation_density { + let joiner = match context.config.type_punctuation_density() { TypeDensity::Compressed => "+", TypeDensity::Wide => " + ", }; let result = format!("{}{}{}", result, colon, appendix.join(joiner)); - wrap_str(result, context.config.max_width, shape) + wrap_str(result, context.config.max_width(), shape) } } @@ -493,19 +493,19 @@ impl Rewrite for ast::TyParamBound { impl Rewrite for ast::Lifetime { fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> { wrap_str(pprust::lifetime_to_string(self), - context.config.max_width, + context.config.max_width(), shape) } } impl Rewrite for ast::TyParamBounds { fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> { - let joiner = match context.config.type_punctuation_density { + let joiner = match context.config.type_punctuation_density() { TypeDensity::Compressed => "+", TypeDensity::Wide => " + ", }; let strs: Vec<_> = try_opt!(self.iter().map(|b| b.rewrite(context, shape)).collect()); - wrap_str(strs.join(joiner), context.config.max_width, shape) + wrap_str(strs.join(joiner), context.config.max_width(), shape) } } @@ -514,14 +514,14 @@ impl Rewrite for ast::TyParam { let mut result = String::with_capacity(128); result.push_str(&self.ident.to_string()); if !self.bounds.is_empty() { - if context.config.space_before_bound { + if context.config.space_before_bound() { result.push_str(" "); } result.push_str(":"); - if context.config.space_after_bound_colon { + if context.config.space_after_bound_colon() { result.push_str(" "); } - let joiner = match context.config.type_punctuation_density { + let joiner = match context.config.type_punctuation_density() { TypeDensity::Compressed => "+", TypeDensity::Wide => " + ", }; @@ -536,7 +536,7 @@ impl Rewrite for ast::TyParam { } if let Some(ref def) = self.default { - let eq_str = match context.config.type_punctuation_density { + let eq_str = match context.config.type_punctuation_density() { TypeDensity::Compressed => "=", TypeDensity::Wide => " = ", }; @@ -547,7 +547,7 @@ impl Rewrite for ast::TyParam { result.push_str(&rewrite); } - wrap_str(result, context.config.max_width, shape) + wrap_str(result, context.config.max_width(), shape) } } @@ -568,7 +568,7 @@ impl Rewrite for ast::PolyTraitRef { Shape::legacy(max_path_width, shape.indent + extra_offset))); - Some(if context.config.spaces_within_angle_brackets && lifetime_str.len() > 0 { + Some(if context.config.spaces_within_angle_brackets() && lifetime_str.len() > 0 { format!("for< {} > {}", lifetime_str, path_str) } else { format!("for<{}> {}", lifetime_str, path_str) @@ -637,20 +637,20 @@ impl Rewrite for ast::Ty { ast::TyKind::Paren(ref ty) => { let budget = try_opt!(shape.width.checked_sub(2)); ty.rewrite(context, Shape::legacy(budget, shape.indent + 1)) - .map(|ty_str| if context.config.spaces_within_parens { + .map(|ty_str| if context.config.spaces_within_parens() { format!("( {} )", ty_str) } else { format!("({})", ty_str) }) } ast::TyKind::Slice(ref ty) => { - let budget = if context.config.spaces_within_square_brackets { + let budget = if context.config.spaces_within_square_brackets() { try_opt!(shape.width.checked_sub(4)) } else { try_opt!(shape.width.checked_sub(2)) }; ty.rewrite(context, Shape::legacy(budget, shape.indent + 1)) - .map(|ty_str| if context.config.spaces_within_square_brackets { + .map(|ty_str| if context.config.spaces_within_square_brackets() { format!("[ {} ]", ty_str) } else { format!("[{}]", ty_str) @@ -663,7 +663,7 @@ impl Rewrite for ast::Ty { rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape) } ast::TyKind::Array(ref ty, ref repeats) => { - let use_spaces = context.config.spaces_within_square_brackets; + let use_spaces = context.config.spaces_within_square_brackets(); let lbr = if use_spaces { "[ " } else { "[" }; let rbr = if use_spaces { " ]" } else { "]" }; rewrite_pair(&**ty, &**repeats, lbr, "; ", rbr, context, shape) @@ -715,7 +715,7 @@ fn rewrite_bare_fn(bare_fn: &ast::BareFnTy, result.push_str(::utils::format_unsafety(bare_fn.unsafety)); if bare_fn.abi != abi::Abi::Rust { - result.push_str(&::utils::format_abi(bare_fn.abi, context.config.force_explicit_abi)); + result.push_str(&::utils::format_abi(bare_fn.abi, context.config.force_explicit_abi())); } result.push_str("fn"); diff --git a/src/utils.rs b/src/utils.rs index d7778448b86..059040c70a2 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -312,7 +312,7 @@ pub fn wrap_str<S: AsRef<str>>(s: S, max_width: usize, shape: Shape) -> Option<S impl Rewrite for String { fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> { - wrap_str(self, context.config.max_width, shape).map(ToOwned::to_owned) + wrap_str(self, context.config.max_width(), shape).map(ToOwned::to_owned) } } diff --git a/src/visitor.rs b/src/visitor.rs index 556b9912697..c8d8cf52e7a 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -50,7 +50,7 @@ impl<'a> FmtVisitor<'a> { // FIXME(#434): Move this check to somewhere more central, eg Rewrite. if !self.config - .file_lines + .file_lines() .intersects(&self.codemap.lookup_line_range(stmt.span)) { return; } @@ -113,10 +113,10 @@ impl<'a> FmtVisitor<'a> { // level. fn close_block(&mut self) { let total_len = self.buffer.len; - let chars_too_many = if self.config.hard_tabs { + let chars_too_many = if self.config.hard_tabs() { 1 } else { - self.config.tab_spaces + self.config.tab_spaces() }; self.buffer.truncate(total_len - chars_too_many); self.buffer.push_str("}"); @@ -509,7 +509,7 @@ impl<'a> FmtVisitor<'a> { // If the next item is a `use` declaration, then extract it and any subsequent `use`s // to be potentially reordered within `format_imports`. Otherwise, just format the // next item for output. - if self.config.reorder_imports && is_use_item(&*items_left[0]) { + if self.config.reorder_imports() && is_use_item(&*items_left[0]) { let use_item_length = items_left .iter() .take_while(|ppi| is_use_item(&***ppi)) @@ -599,13 +599,13 @@ impl<'a> Rewrite for [ast::Attribute] { let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1; let comment = comment.trim(); if !comment.is_empty() { - let comment = try_opt!(rewrite_comment(comment, - false, - Shape::legacy(context.config - .comment_width - - shape.indent.width(), - shape.indent), - context.config)); + let comment = + try_opt!(rewrite_comment(comment, + false, + Shape::legacy(context.config.comment_width() - + shape.indent.width(), + shape.indent), + context.config)); result.push_str(&indent); result.push_str(&comment); result.push('\n'); @@ -618,7 +618,7 @@ impl<'a> Rewrite for [ast::Attribute] { if a_str.starts_with("//") { a_str = try_opt!(rewrite_comment(&a_str, false, - Shape::legacy(context.config.comment_width - + Shape::legacy(context.config.comment_width() - shape.indent.width(), shape.indent), context.config)); diff --git a/tests/system.rs b/tests/system.rs index 48531d321c8..91386a7f768 100644 --- a/tests/system.rs +++ b/tests/system.rs @@ -20,7 +20,7 @@ use std::path::{Path, PathBuf}; use rustfmt::*; use rustfmt::filemap::{write_system_newlines, FileMap}; -use rustfmt::config::{Config, ReportTactic}; +use rustfmt::config::Config; use rustfmt::rustfmt_diff::*; const DIFF_CONTEXT_SIZE: usize = 3; @@ -224,12 +224,16 @@ fn read_config(filename: &str) -> Config { for (key, val) in &sig_comments { if key != "target" && key != "config" { - config.override_value(key, val); + config + .override_value(key, val) + .expect(&format!("Failed to override config {} (\"{}\")", key, val)); } } // Don't generate warnings for to-do items. - config.report_todo = ReportTactic::Never; + config + .override_value("report_todo", "Never") + .expect("Could not set report-todo to Never"); config }