mirror of
https://github.com/rust-lang/rust.git
synced 2025-05-14 02:49:40 +00:00
Merge pull request #1558 from mjkillough/config
Add a flag to emit which options are used
This commit is contained in:
commit
068b8b3b5c
@ -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.
|
||||
|
@ -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.
|
||||
|
||||
|
@ -44,6 +44,7 @@ enum Operation {
|
||||
Format {
|
||||
files: Vec<PathBuf>,
|
||||
config_path: Option<PathBuf>,
|
||||
minimal_config_path: Option<String>,
|
||||
},
|
||||
/// Print the help message.
|
||||
Help,
|
||||
@ -51,6 +52,8 @@ enum Operation {
|
||||
Version,
|
||||
/// Print detailed configuration help.
|
||||
ConfigHelp,
|
||||
/// Output default config to a file
|
||||
ConfigOutputDefault { path: String },
|
||||
/// No file specified, read from stdin
|
||||
Stdin {
|
||||
input: String,
|
||||
@ -89,11 +92,11 @@ impl CliOptions {
|
||||
}
|
||||
|
||||
fn apply_to(self, config: &mut Config) {
|
||||
config.skip_children = self.skip_children;
|
||||
config.verbose = self.verbose;
|
||||
config.file_lines = self.file_lines;
|
||||
config.set().skip_children(self.skip_children);
|
||||
config.set().verbose(self.verbose);
|
||||
config.set().file_lines(self.file_lines);
|
||||
if let Some(write_mode) = self.write_mode {
|
||||
config.write_mode = write_mode;
|
||||
config.set().write_mode(write_mode);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -186,6 +189,14 @@ fn make_opts() -> Options {
|
||||
opts.optflag("",
|
||||
"config-help",
|
||||
"show details of rustfmt configuration options");
|
||||
opts.optopt("",
|
||||
"dump-default-config",
|
||||
"Dumps the default configuration to a file and exits.",
|
||||
"PATH");
|
||||
opts.optopt("",
|
||||
"dump-minimal-config",
|
||||
"Dumps configuration options that were checked during formatting to a file.",
|
||||
"PATH");
|
||||
opts.optopt("",
|
||||
"config-path",
|
||||
"Recursively searches the given path for the rustfmt.toml config file. If not \
|
||||
@ -216,18 +227,24 @@ fn execute(opts: &Options) -> FmtResult<Summary> {
|
||||
Config::print_docs();
|
||||
Ok(Summary::new())
|
||||
}
|
||||
Operation::ConfigOutputDefault { path } => {
|
||||
let mut file = File::create(path)?;
|
||||
let toml = Config::default().all_options().to_toml()?;
|
||||
file.write_all(toml.as_bytes())?;
|
||||
Ok(Summary::new())
|
||||
}
|
||||
Operation::Stdin { input, config_path } => {
|
||||
// try to read config from local directory
|
||||
let (mut config, _) = match_cli_path_or_file(config_path,
|
||||
&env::current_dir().unwrap())?;
|
||||
|
||||
// write_mode is always Plain for Stdin.
|
||||
config.write_mode = WriteMode::Plain;
|
||||
config.set().write_mode(WriteMode::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.set().file_lines(file_lines.parse()?);
|
||||
for f in config.file_lines().files() {
|
||||
if f != "stdin" {
|
||||
println!("Warning: Extra file listed in file_lines option '{}'", f);
|
||||
}
|
||||
@ -236,7 +253,11 @@ fn execute(opts: &Options) -> FmtResult<Summary> {
|
||||
|
||||
Ok(run(Input::Text(input), &config))
|
||||
}
|
||||
Operation::Format { files, config_path } => {
|
||||
Operation::Format {
|
||||
files,
|
||||
config_path,
|
||||
minimal_config_path,
|
||||
} => {
|
||||
let options = CliOptions::from_matches(&matches)?;
|
||||
|
||||
for f in options.file_lines.files() {
|
||||
@ -286,6 +307,15 @@ fn execute(opts: &Options) -> FmtResult<Summary> {
|
||||
error_summary.add(run(Input::File(file), &config));
|
||||
}
|
||||
}
|
||||
|
||||
// If we were given a path via dump-minimal-config, output any options
|
||||
// that were used during formatting as TOML.
|
||||
if let Some(path) = minimal_config_path {
|
||||
let mut file = File::create(path)?;
|
||||
let toml = config.used_options().to_toml()?;
|
||||
file.write_all(toml.as_bytes())?;
|
||||
}
|
||||
|
||||
Ok(error_summary)
|
||||
}
|
||||
}
|
||||
@ -353,6 +383,10 @@ fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
|
||||
return Ok(Operation::ConfigHelp);
|
||||
}
|
||||
|
||||
if let Some(path) = matches.opt_str("dump-default-config") {
|
||||
return Ok(Operation::ConfigOutputDefault { path });
|
||||
}
|
||||
|
||||
if matches.opt_present("version") {
|
||||
return Ok(Operation::Version);
|
||||
}
|
||||
@ -383,6 +417,9 @@ fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
|
||||
path @ _ => path,
|
||||
};
|
||||
|
||||
// If no path is given, we won't output a minimal config.
|
||||
let minimal_config_path = matches.opt_str("dump-minimal-config");
|
||||
|
||||
// if no file argument is supplied, read from stdin
|
||||
if matches.free.is_empty() {
|
||||
let mut buffer = String::new();
|
||||
@ -408,5 +445,6 @@ fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
|
||||
Ok(Operation::Format {
|
||||
files: files,
|
||||
config_path: config_path,
|
||||
minimal_config_path: minimal_config_path,
|
||||
})
|
||||
}
|
||||
|
@ -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
|
||||
}
|
||||
}
|
||||
@ -177,7 +177,7 @@ pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -
|
||||
let one_line_len = rewrites.iter().fold(0, |a, r| a + first_line_width(r)) +
|
||||
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 {
|
||||
@ -186,7 +186,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));
|
||||
@ -215,7 +215,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
|
||||
}
|
||||
@ -243,7 +243,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)
|
||||
}
|
||||
|
||||
@ -319,9 +319,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()),
|
||||
}
|
||||
}
|
||||
|
||||
@ -371,7 +371,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 {
|
||||
@ -427,7 +427,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(", "))
|
||||
|
@ -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,8 @@ 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.set().wrap_comments(true);
|
||||
config.set().normalize_comments(true);
|
||||
|
||||
let comment = rewrite_comment(" //test",
|
||||
true,
|
||||
|
113
src/config.rs
113
src/config.rs
@ -10,6 +10,8 @@
|
||||
|
||||
extern crate toml;
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
use file_lines::FileLines;
|
||||
use lists::{SeparatorTactic, ListTactic};
|
||||
|
||||
@ -20,7 +22,7 @@ macro_rules! configuration_option_enum{
|
||||
$( $x ),+
|
||||
}
|
||||
|
||||
impl_enum_decodable!($e, $( $x ),+);
|
||||
impl_enum_serialize_and_deserialize!($e, $( $x ),+);
|
||||
}
|
||||
}
|
||||
|
||||
@ -210,27 +212,66 @@ impl ConfigHelpItem {
|
||||
|
||||
macro_rules! create_config {
|
||||
($($i:ident: $ty:ty, $def:expr, $( $dstring:expr ),+ );+ $(;)*) => (
|
||||
#[derive(Deserialize, Clone)]
|
||||
#[derive(Clone)]
|
||||
pub struct Config {
|
||||
$(pub $i: $ty),+
|
||||
// For each config item, we store a bool indicating whether it has
|
||||
// been accessed and the value.
|
||||
$($i: (Cell<bool>, $ty)),+
|
||||
}
|
||||
|
||||
// Just like the Config struct but with each property wrapped
|
||||
// as Option<T>. This is used to parse a rustfmt.toml that doesn't
|
||||
// specity all properties of `Config`.
|
||||
// We first parse into `ParsedConfig`, then create a default `Config`
|
||||
// and overwrite the properties with corresponding values from `ParsedConfig`
|
||||
#[derive(Deserialize, Clone)]
|
||||
pub struct ParsedConfig {
|
||||
// We first parse into `PartialConfig`, then create a default `Config`
|
||||
// and overwrite the properties with corresponding values from `PartialConfig`.
|
||||
#[derive(Deserialize, Serialize, Clone)]
|
||||
pub struct PartialConfig {
|
||||
$(pub $i: Option<$ty>),+
|
||||
}
|
||||
|
||||
impl PartialConfig {
|
||||
pub fn to_toml(&self) -> Result<String, String> {
|
||||
// file_lines can't be specified in TOML
|
||||
let mut cloned = self.clone();
|
||||
cloned.file_lines = None;
|
||||
|
||||
toml::to_string(&cloned)
|
||||
.map_err(|e| format!("Could not output config: {}", e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
// Macro hygiene won't allow us to make `set_$i()` methods on Config
|
||||
// for each item, so this struct is used to give the API to set values:
|
||||
// `config.get().option(false)`. It's pretty ugly. Consider replacing
|
||||
// with `config.set_option(false)` if we ever get a stable/usable
|
||||
// `concat_idents!()`.
|
||||
pub struct ConfigSetter<'a>(&'a mut Config);
|
||||
|
||||
impl<'a> ConfigSetter<'a> {
|
||||
$(
|
||||
pub fn $i(&mut self, value: $ty) {
|
||||
(self.0).$i.1 = value;
|
||||
}
|
||||
)+
|
||||
}
|
||||
|
||||
impl Config {
|
||||
|
||||
fn fill_from_parsed_config(mut self, parsed: ParsedConfig) -> Config {
|
||||
$(
|
||||
pub fn $i(&self) -> $ty {
|
||||
self.$i.0.set(true);
|
||||
self.$i.1.clone()
|
||||
}
|
||||
)+
|
||||
|
||||
pub fn set<'a>(&'a mut self) -> ConfigSetter<'a> {
|
||||
ConfigSetter(self)
|
||||
}
|
||||
|
||||
fn fill_from_parsed_config(mut self, parsed: PartialConfig) -> Config {
|
||||
$(
|
||||
if let Some(val) = parsed.$i {
|
||||
self.$i = val;
|
||||
self.$i.1 = val;
|
||||
}
|
||||
)+
|
||||
self
|
||||
@ -270,11 +311,32 @@ macro_rules! create_config {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn override_value(&mut self, key: &str, val: &str) {
|
||||
pub fn used_options(&self) -> PartialConfig {
|
||||
PartialConfig {
|
||||
$(
|
||||
$i: if self.$i.0.get() {
|
||||
Some(self.$i.1.clone())
|
||||
} else {
|
||||
None
|
||||
},
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
pub fn all_options(&self) -> PartialConfig {
|
||||
PartialConfig {
|
||||
$(
|
||||
$i: Some(self.$i.1.clone()),
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
pub fn override_value(&mut self, key: &str, val: &str)
|
||||
{
|
||||
match key {
|
||||
$(
|
||||
stringify!($i) => {
|
||||
self.$i = val.parse::<$ty>()
|
||||
self.$i.1 = val.parse::<$ty>()
|
||||
.expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
|
||||
stringify!($i),
|
||||
val,
|
||||
@ -319,7 +381,7 @@ macro_rules! create_config {
|
||||
fn default() -> Config {
|
||||
Config {
|
||||
$(
|
||||
$i: $def,
|
||||
$i: (Cell::new(false), $def),
|
||||
)+
|
||||
}
|
||||
}
|
||||
@ -424,3 +486,30 @@ create_config! {
|
||||
condense_wildcard_suffixes: bool, false, "Replace strings of _ wildcards by a single .. in \
|
||||
tuple patterns"
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::Config;
|
||||
|
||||
#[test]
|
||||
fn test_config_set() {
|
||||
let mut config = Config::default();
|
||||
config.set().verbose(false);
|
||||
assert_eq!(config.verbose(), false);
|
||||
config.set().verbose(true);
|
||||
assert_eq!(config.verbose(), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_config_used_to_toml() {
|
||||
let config = Config::default();
|
||||
|
||||
let verbose = config.verbose();
|
||||
let skip_children = config.skip_children();
|
||||
|
||||
let used_options = config.used_options();
|
||||
let toml = used_options.to_toml().unwrap();
|
||||
assert_eq!(toml,
|
||||
format!("verbose = {}\nskip_children = {}\n", verbose, skip_children));
|
||||
}
|
||||
}
|
||||
|
153
src/expr.rs
153
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 {
|
||||
@ -1034,12 +1050,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,
|
||||
_ => " ",
|
||||
};
|
||||
@ -1168,14 +1184,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)
|
||||
};
|
||||
@ -1239,7 +1255,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 {
|
||||
@ -1321,7 +1337,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 {
|
||||
@ -1354,9 +1370,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(),
|
||||
_ => " ",
|
||||
};
|
||||
@ -1374,16 +1390,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 {
|
||||
("{", "}")
|
||||
@ -1393,13 +1409,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,
|
||||
@ -1535,11 +1551,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);
|
||||
}
|
||||
@ -1620,7 +1636,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
|
||||
@ -1631,8 +1647,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
|
||||
@ -1648,9 +1664,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)
|
||||
@ -1722,7 +1738,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
|
||||
@ -1741,11 +1757,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,
|
||||
@ -1756,10 +1772,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)
|
||||
}
|
||||
@ -1775,7 +1791,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)
|
||||
@ -1789,7 +1805,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 {
|
||||
("[", "]")
|
||||
@ -1810,7 +1826,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))
|
||||
@ -1886,9 +1902,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),
|
||||
@ -1901,13 +1918,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> {
|
||||
@ -1963,7 +1980,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)
|
||||
@ -1982,7 +1999,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))
|
||||
|
@ -216,6 +216,16 @@ impl<'de> ::serde::de::Deserialize<'de> for FileLines {
|
||||
}
|
||||
}
|
||||
|
||||
// We also want to avoid attempting to serialize a FileLines to toml. The
|
||||
// `Config` struct should ensure this impl is never reached.
|
||||
impl ::serde::ser::Serialize for FileLines {
|
||||
fn serialize<S>(&self, _: S) -> Result<S::Ok, S::Error>
|
||||
where S: ::serde::ser::Serializer
|
||||
{
|
||||
unreachable!("FileLines cannot be serialized. This is a rustfmt bug.");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::Range;
|
||||
|
@ -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 {
|
||||
|
@ -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));
|
||||
}
|
||||
|
||||
|
234
src/items.rs
234
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,
|
||||
@ -477,7 +477,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 {
|
||||
@ -487,7 +487,7 @@ impl<'a> FmtVisitor<'a> {
|
||||
};
|
||||
|
||||
wrap_str(tag,
|
||||
self.config.max_width,
|
||||
self.config.max_width(),
|
||||
Shape::indented(indent, self.config))
|
||||
}
|
||||
};
|
||||
@ -517,14 +517,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,
|
||||
@ -543,13 +543,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));
|
||||
@ -612,8 +612,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..]))
|
||||
}
|
||||
|
||||
@ -648,7 +648,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))));
|
||||
|
||||
@ -656,7 +656,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));
|
||||
|
||||
@ -670,7 +670,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,
|
||||
@ -678,7 +678,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 {
|
||||
@ -756,11 +756,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));
|
||||
@ -770,10 +770,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 {
|
||||
@ -782,11 +783,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,
|
||||
@ -799,15 +800,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));
|
||||
@ -885,13 +886,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()
|
||||
@ -920,7 +922,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 =
|
||||
@ -941,7 +943,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),
|
||||
@ -951,7 +953,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,
|
||||
@ -1000,11 +1002,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,
|
||||
";",
|
||||
@ -1029,7 +1031,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)
|
||||
@ -1041,7 +1043,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 =
|
||||
@ -1062,7 +1064,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,
|
||||
@ -1071,15 +1073,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(')');
|
||||
@ -1096,11 +1098,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);
|
||||
@ -1132,13 +1134,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,
|
||||
@ -1151,7 +1153,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;
|
||||
@ -1167,7 +1169,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))
|
||||
}));
|
||||
@ -1177,12 +1179,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 {
|
||||
""
|
||||
@ -1193,7 +1195,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;
|
||||
@ -1229,7 +1231,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),
|
||||
@ -1279,7 +1281,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())));
|
||||
@ -1287,7 +1290,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,
|
||||
@ -1307,31 +1310,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,
|
||||
@ -1378,11 +1382,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()));
|
||||
@ -1534,7 +1538,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
|
||||
@ -1562,9 +1566,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: {:?}",
|
||||
@ -1576,12 +1580,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 {
|
||||
@ -1590,7 +1594,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(' ')
|
||||
}
|
||||
}
|
||||
@ -1620,7 +1624,7 @@ fn rewrite_fn_base(context: &RewriteContext,
|
||||
let multi_line_arg_str = arg_str.contains('\n') ||
|
||||
arg_str.chars().last().map_or(false, |c| c == ',');
|
||||
|
||||
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();
|
||||
@ -1635,7 +1639,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(')');
|
||||
@ -1643,7 +1647,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,
|
||||
_ => {
|
||||
@ -1659,13 +1663,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() => {
|
||||
@ -1713,7 +1717,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,
|
||||
@ -1722,12 +1726,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,
|
||||
"{",
|
||||
@ -1735,7 +1739,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');
|
||||
}
|
||||
|
||||
@ -1748,7 +1752,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,
|
||||
"{",
|
||||
@ -1858,7 +1862,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 fits_in_one_line => {
|
||||
(indent.block_indent(context.config), SeparatorTactic::Never, true)
|
||||
}
|
||||
@ -1869,7 +1873,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,
|
||||
@ -1918,7 +1922,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);
|
||||
|
||||
@ -1926,7 +1930,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));
|
||||
|
||||
@ -1937,7 +1941,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 {
|
||||
@ -1947,7 +1951,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,
|
||||
@ -1967,7 +1971,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,
|
||||
@ -2006,13 +2010,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)
|
||||
@ -2029,7 +2033,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 => " + ",
|
||||
};
|
||||
@ -2074,7 +2078,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
|
||||
@ -2126,7 +2130,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,
|
||||
@ -2136,9 +2140,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,
|
||||
@ -2146,7 +2150,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.
|
||||
@ -2164,9 +2168,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;
|
||||
@ -2224,7 +2228,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,
|
||||
|
44
src/lib.rs
44
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,7 @@ mod test {
|
||||
#[test]
|
||||
fn indent_to_string_hard_tabs() {
|
||||
let mut config = Config::default();
|
||||
config.hard_tabs = true;
|
||||
config.set().hard_tabs(true);
|
||||
let indent = Indent::new(8, 4);
|
||||
|
||||
// 2 tabs + 4 spaces
|
||||
@ -719,10 +719,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 +732,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 +745,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);
|
||||
|
23
src/lists.rs
23
src/lists.rs
@ -35,7 +35,7 @@ pub enum ListTactic {
|
||||
Mixed,
|
||||
}
|
||||
|
||||
impl_enum_decodable!(ListTactic, Vertical, Horizontal, HorizontalVertical, Mixed);
|
||||
impl_enum_serialize_and_deserialize!(ListTactic, Vertical, Horizontal, HorizontalVertical, Mixed);
|
||||
|
||||
#[derive(Eq, PartialEq, Debug, Copy, Clone)]
|
||||
pub enum SeparatorTactic {
|
||||
@ -44,7 +44,7 @@ pub enum SeparatorTactic {
|
||||
Vertical,
|
||||
}
|
||||
|
||||
impl_enum_decodable!(SeparatorTactic, Always, Never, Vertical);
|
||||
impl_enum_serialize_and_deserialize!(SeparatorTactic, Always, Never, Vertical);
|
||||
|
||||
impl SeparatorTactic {
|
||||
pub fn from_bool(b: bool) -> SeparatorTactic {
|
||||
@ -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>
|
||||
@ -525,14 +525,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
|
||||
}
|
||||
}
|
||||
@ -547,13 +547,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)
|
||||
@ -581,7 +582,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,
|
||||
@ -589,7 +590,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,
|
||||
|
@ -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);
|
||||
}
|
||||
|
@ -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.push_str(&rewrite_comment(subslice,
|
||||
@ -196,7 +196,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;
|
||||
}
|
||||
|
||||
|
@ -50,7 +50,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 {
|
||||
@ -107,19 +107,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -186,9 +188,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),
|
||||
@ -209,7 +212,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)
|
||||
}
|
||||
}
|
||||
@ -295,7 +298,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_suffixes && wildcard_suffix_len >= 2 {
|
||||
let list = if context.config.condense_wildcard_suffixes() && wildcard_suffix_len >= 2 {
|
||||
let new_item_count = 1 + pats.len() - wildcard_suffix_len;
|
||||
items[new_item_count - 1].item = Some("..".to_owned());
|
||||
|
||||
@ -307,7 +310,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)
|
||||
@ -315,7 +318,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)
|
||||
|
@ -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)]
|
||||
|
54
src/types.rs
54
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),
|
||||
};
|
||||
@ -236,7 +236,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)
|
||||
@ -337,7 +337,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)
|
||||
@ -345,8 +345,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 {
|
||||
@ -369,7 +369,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 => " + ",
|
||||
};
|
||||
@ -385,7 +385,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,
|
||||
@ -395,7 +395,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 => " + ",
|
||||
};
|
||||
@ -436,7 +436,7 @@ impl Rewrite for ast::WherePredicate {
|
||||
}
|
||||
};
|
||||
|
||||
wrap_str(result, context.config.max_width, shape)
|
||||
wrap_str(result, context.config.max_width(), shape)
|
||||
}
|
||||
}
|
||||
|
||||
@ -463,12 +463,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)
|
||||
}
|
||||
}
|
||||
|
||||
@ -492,19 +492,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)
|
||||
}
|
||||
}
|
||||
|
||||
@ -513,14 +513,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 => " + ",
|
||||
};
|
||||
@ -535,7 +535,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 => " = ",
|
||||
};
|
||||
@ -546,7 +546,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)
|
||||
}
|
||||
}
|
||||
|
||||
@ -567,7 +567,7 @@ impl Rewrite for ast::PolyTraitRef {
|
||||
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)
|
||||
@ -634,20 +634,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)
|
||||
@ -660,7 +660,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)
|
||||
@ -712,7 +712,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");
|
||||
|
25
src/utils.rs
25
src/utils.rs
@ -189,10 +189,29 @@ pub fn trim_newlines(input: &str) -> &str {
|
||||
}
|
||||
}
|
||||
|
||||
// Macro for deriving implementations of Decodable for enums
|
||||
// Macro for deriving implementations of Serialize/Deserialize for enums
|
||||
#[macro_export]
|
||||
macro_rules! impl_enum_decodable {
|
||||
macro_rules! impl_enum_serialize_and_deserialize {
|
||||
( $e:ident, $( $x:ident ),* ) => {
|
||||
impl ::serde::ser::Serialize for $e {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: ::serde::ser::Serializer
|
||||
{
|
||||
use serde::ser::Error;
|
||||
|
||||
// We don't know whether the user of the macro has given us all options.
|
||||
#[allow(unreachable_patterns)]
|
||||
match *self {
|
||||
$(
|
||||
$e::$x => serializer.serialize_str(stringify!($x)),
|
||||
)*
|
||||
_ => {
|
||||
Err(S::Error::custom(format!("Cannot serialize {:?}", self)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> ::serde::de::Deserialize<'de> for $e {
|
||||
fn deserialize<D>(d: D) -> Result<Self, D::Error>
|
||||
where D: ::serde::Deserializer<'de> {
|
||||
@ -312,7 +331,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)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -65,7 +65,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;
|
||||
}
|
||||
@ -128,10 +128,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("}");
|
||||
@ -524,8 +524,8 @@ 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]) {
|
||||
let reorder_imports_in_group = self.config.reorder_imports_in_group;
|
||||
if self.config.reorder_imports() && is_use_item(&*items_left[0]) {
|
||||
let reorder_imports_in_group = self.config.reorder_imports_in_group();
|
||||
let mut last = self.codemap.lookup_line_range(item_bound(&items_left[0]));
|
||||
let use_item_length = items_left
|
||||
.iter()
|
||||
@ -625,13 +625,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');
|
||||
@ -644,7 +644,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));
|
||||
|
@ -229,7 +229,7 @@ fn read_config(filename: &str) -> Config {
|
||||
}
|
||||
|
||||
// Don't generate warnings for to-do items.
|
||||
config.report_todo = ReportTactic::Never;
|
||||
config.set().report_todo(ReportTactic::Never);
|
||||
|
||||
config
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user