Merge pull request #1782 from topecongiro/rfc/combining-match-arm

Rfc: combining match arm
This commit is contained in:
Nick Cameron 2017-07-12 16:23:18 +12:00 committed by GitHub
commit 2725636f58
26 changed files with 653 additions and 815 deletions

View File

@ -1986,7 +1986,7 @@ Break comments to fit on the line
## `wrap_match_arms`
Wrap multiline match arms in blocks
Wrap the body of arms in blocks when it does not fit on the same line with the pattern of arms
- **Default value**: `true`
- **Possible values**: `true`, `false`
@ -1995,13 +1995,9 @@ Wrap multiline match arms in blocks
```rust
match lorem {
true => {
let ipsum = dolor;
println!("{}", ipsum);
}
false => {
println!("{}", sit)
}
true =>
foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(x),
false => println!("{}", sit),
}
```
@ -2010,8 +2006,7 @@ match lorem {
```rust
match lorem {
true => {
let ipsum = dolor;
println!("{}", ipsum);
foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(x)
}
false => println!("{}", sit),
}

View File

@ -90,13 +90,11 @@ fn execute() -> i32 {
print_usage(&opts, &e.to_string());
failure
}
Ok(status) => {
if status.success() {
success
} else {
status.code().unwrap_or(failure)
}
}
Ok(status) => if status.success() {
success
} else {
status.code().unwrap_or(failure)
},
}
}
@ -324,12 +322,10 @@ fn format_files(
.args(fmt_args)
.spawn()
.map_err(|e| match e.kind() {
std::io::ErrorKind::NotFound => {
std::io::Error::new(
std::io::ErrorKind::Other,
"Could not run rustfmt, please make sure it is in your PATH.",
)
}
std::io::ErrorKind::NotFound => std::io::Error::new(
std::io::ErrorKind::Other,
"Could not run rustfmt, please make sure it is in your PATH.",
),
_ => e,
})?;
command.wait()

View File

@ -444,12 +444,10 @@ fn rewrite_method_call_with_overflow(
None => return false,
};
let types = match segment.parameters {
Some(ref params) => {
match **params {
ast::PathParameters::AngleBracketed(ref data) => &data.types[..],
_ => &[],
}
}
Some(ref params) => match **params {
ast::PathParameters::AngleBracketed(ref data) => &data.types[..],
_ => &[],
},
_ => &[],
};
let mut last_rewrite = rewrite_method_call(
@ -516,12 +514,10 @@ fn rewrite_chain_subexpr(
match expr.node {
ast::ExprKind::MethodCall(ref segment, ref expressions) => {
let types = match segment.parameters {
Some(ref params) => {
match **params {
ast::PathParameters::AngleBracketed(ref data) => &data.types[..],
_ => &[],
}
}
Some(ref params) => match **params {
ast::PathParameters::AngleBracketed(ref data) => &data.types[..],
_ => &[],
},
_ => &[],
};
rewrite_method_call(segment.identifier, types, expressions, span, context, shape)

View File

@ -342,14 +342,12 @@ impl FindUncommented for str {
None => {
return Some(i - pat.len());
}
Some(c) => {
match kind {
FullCodeCharKind::Normal if b == c => {}
_ => {
needle_iter = pat.chars();
}
Some(c) => match kind {
FullCodeCharKind::Normal if b == c => {}
_ => {
needle_iter = pat.chars();
}
}
},
}
}
@ -494,42 +492,34 @@ where
let item = try_opt!(self.base.next());
let chr = item.get_char();
self.status = match self.status {
CharClassesStatus::LitString => {
match chr {
'"' => CharClassesStatus::Normal,
'\\' => CharClassesStatus::LitStringEscape,
_ => CharClassesStatus::LitString,
}
}
CharClassesStatus::LitString => match chr {
'"' => CharClassesStatus::Normal,
'\\' => CharClassesStatus::LitStringEscape,
_ => CharClassesStatus::LitString,
},
CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
CharClassesStatus::LitChar => {
match chr {
'\\' => CharClassesStatus::LitCharEscape,
'\'' => CharClassesStatus::Normal,
_ => CharClassesStatus::LitChar,
}
}
CharClassesStatus::LitChar => match chr {
'\\' => CharClassesStatus::LitCharEscape,
'\'' => CharClassesStatus::Normal,
_ => CharClassesStatus::LitChar,
},
CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
CharClassesStatus::Normal => {
match chr {
'"' => CharClassesStatus::LitString,
'\'' => CharClassesStatus::LitChar,
'/' => {
match self.base.peek() {
Some(next) if next.get_char() == '*' => {
self.status = CharClassesStatus::BlockCommentOpening(1);
return Some((FullCodeCharKind::StartComment, item));
}
Some(next) if next.get_char() == '/' => {
self.status = CharClassesStatus::LineComment;
return Some((FullCodeCharKind::StartComment, item));
}
_ => CharClassesStatus::Normal,
}
CharClassesStatus::Normal => match chr {
'"' => CharClassesStatus::LitString,
'\'' => CharClassesStatus::LitChar,
'/' => match self.base.peek() {
Some(next) if next.get_char() == '*' => {
self.status = CharClassesStatus::BlockCommentOpening(1);
return Some((FullCodeCharKind::StartComment, item));
}
Some(next) if next.get_char() == '/' => {
self.status = CharClassesStatus::LineComment;
return Some((FullCodeCharKind::StartComment, item));
}
_ => CharClassesStatus::Normal,
}
}
},
_ => CharClassesStatus::Normal,
},
CharClassesStatus::BlockComment(deepness) => {
assert!(deepness != 0);
self.status = match self.base.peek() {
@ -558,18 +548,16 @@ where
return Some((FullCodeCharKind::InComment, item));
}
}
CharClassesStatus::LineComment => {
match chr {
'\n' => {
self.status = CharClassesStatus::Normal;
return Some((FullCodeCharKind::EndComment, item));
}
_ => {
self.status = CharClassesStatus::LineComment;
return Some((FullCodeCharKind::InComment, item));
}
CharClassesStatus::LineComment => match chr {
'\n' => {
self.status = CharClassesStatus::Normal;
return Some((FullCodeCharKind::EndComment, item));
}
}
_ => {
self.status = CharClassesStatus::LineComment;
return Some((FullCodeCharKind::InComment, item));
}
},
};
Some((FullCodeCharKind::Normal, item))
}

View File

@ -482,11 +482,9 @@ pub fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
// Return the error if it's something other than `NotFound`; otherwise we didn't
// find the project file yet, and continue searching.
Err(e) => {
if e.kind() != ErrorKind::NotFound {
return Err(e);
}
}
Err(e) => if e.kind() != ErrorKind::NotFound {
return Err(e);
},
_ => {}
}
}
@ -572,7 +570,8 @@ create_config! {
wrap_comments: bool, false, "Break comments to fit on the line";
comment_width: usize, 80, "Maximum length of comments. No effect unless wrap_comments = true";
normalize_comments: bool, false, "Convert /* */ comments to // comments where possible";
wrap_match_arms: bool, true, "Wrap multiline match arms in blocks";
wrap_match_arms: bool, true, "Wrap the body of arms in blocks when it does not fit on \
the same line with the pattern of arms";
match_block_trailing_comma: bool, false,
"Put a trailing comma after a block based match arm (non-block arms are not affected)";
indent_match_arms: bool, true, "Indent match arms instead of keeping them at the same \

View File

@ -88,29 +88,23 @@ pub fn format_expr(
}
}
let expr_rw = match expr.node {
ast::ExprKind::Array(ref expr_vec) => {
rewrite_array(
expr_vec.iter().map(|e| &**e),
mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi),
context,
shape,
false,
)
}
ast::ExprKind::Lit(ref l) => {
match l.node {
ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
rewrite_string_lit(context, l.span, shape)
}
_ => {
wrap_str(
context.snippet(expr.span),
context.config.max_width(),
shape,
)
}
ast::ExprKind::Array(ref expr_vec) => rewrite_array(
expr_vec.iter().map(|e| &**e),
mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi),
context,
shape,
false,
),
ast::ExprKind::Lit(ref l) => match l.node {
ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
rewrite_string_lit(context, l.span, shape)
}
}
_ => wrap_str(
context.snippet(expr.span),
context.config.max_width(),
shape,
),
},
ast::ExprKind::Call(ref callee, ref args) => {
let inner_span = mk_sp(callee.span.hi, expr.span.hi);
rewrite_call_with_binary_search(
@ -135,33 +129,27 @@ pub fn format_expr(
)
}
ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
ast::ExprKind::Struct(ref path, ref fields, ref base) => {
rewrite_struct_lit(
context,
path,
fields,
base.as_ref().map(|e| &**e),
expr.span,
shape,
)
}
ast::ExprKind::Tup(ref items) => {
rewrite_tuple(
context,
&items.iter().map(|x| &**x).collect::<Vec<_>>()[..],
expr.span,
shape,
)
}
ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
context,
path,
fields,
base.as_ref().map(|e| &**e),
expr.span,
shape,
),
ast::ExprKind::Tup(ref items) => rewrite_tuple(
context,
&items.iter().map(|x| &**x).collect::<Vec<_>>()[..],
expr.span,
shape,
),
ast::ExprKind::If(..) |
ast::ExprKind::IfLet(..) |
ast::ExprKind::ForLoop(..) |
ast::ExprKind::Loop(..) |
ast::ExprKind::While(..) |
ast::ExprKind::WhileLet(..) => {
to_control_flow(expr, expr_type)
.and_then(|control_flow| control_flow.rewrite(context, shape))
}
ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
.and_then(|control_flow| control_flow.rewrite(context, shape)),
ast::ExprKind::Block(ref block) => {
match expr_type {
ExprType::Statement => {
@ -271,14 +259,12 @@ pub fn format_expr(
fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
match lhs.node {
ast::ExprKind::Lit(ref lit) => {
match lit.node {
ast::LitKind::FloatUnsuffixed(..) => {
context.snippet(lit.span).ends_with('.')
}
_ => false,
ast::ExprKind::Lit(ref lit) => match lit.node {
ast::LitKind::FloatUnsuffixed(..) => {
context.snippet(lit.span).ends_with('.')
}
}
_ => false,
},
_ => false,
}
}
@ -315,13 +301,11 @@ pub fn format_expr(
}
// 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,
)
}
ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => wrap_str(
context.snippet(expr.span),
context.config.max_width(),
shape,
),
ast::ExprKind::Catch(ref block) => {
if let rewrite @ Some(_) =
rewrite_single_line_block(context, "do catch ", block, shape)
@ -338,14 +322,12 @@ pub fn format_expr(
}
};
match (attr_rw, expr_rw) {
(Some(attr_str), Some(expr_str)) => {
recover_comment_removed(
combine_attr_and_expr(context, shape, &attr_str, &expr_str),
expr.span,
context,
shape,
)
}
(Some(attr_str), Some(expr_str)) => recover_comment_removed(
combine_attr_and_expr(context, shape, &attr_str, &expr_str),
expr.span,
context,
shape,
),
_ => None,
}
}
@ -460,22 +442,18 @@ where
};
let mut nested_shape = match context.config.array_layout() {
IndentStyle::Block => {
try_opt!(
shape
.block()
.block_indent(context.config.tab_spaces())
.with_max_width(context.config)
.sub_width(1)
)
}
IndentStyle::Visual => {
try_opt!(
shape
.visual_indent(bracket_size)
.sub_width(bracket_size * 2)
)
}
IndentStyle::Block => try_opt!(
shape
.block()
.block_indent(context.config.tab_spaces())
.with_max_width(context.config)
.sub_width(1)
),
IndentStyle::Visual => try_opt!(
shape
.visual_indent(bracket_size)
.sub_width(bracket_size * 2)
),
};
let items = itemize_list(
@ -513,17 +491,15 @@ where
None => DefinitiveListTactic::Vertical,
}
}
IndentStyle::Visual => {
if has_long_item || items.iter().any(ListItem::is_multiline) {
definitive_tactic(
&items,
ListTactic::LimitedHorizontalVertical(context.config.array_width()),
nested_shape.width,
)
} else {
DefinitiveListTactic::Mixed
}
}
IndentStyle::Visual => if has_long_item || items.iter().any(ListItem::is_multiline) {
definitive_tactic(
&items,
ListTactic::LimitedHorizontalVertical(context.config.array_width()),
nested_shape.width,
)
} else {
DefinitiveListTactic::Mixed
},
};
if context.config.array_horizontal_layout_threshold() > 0 &&
items.len() > context.config.array_horizontal_layout_threshold()
@ -965,15 +941,13 @@ fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Opt
ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
stmt_expr(&block.stmts[0]).and_then(|e| rewrite_cond(context, e, shape))
}
_ => {
to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
let alt_block_sep =
String::from("\n") + &shape.indent.block_only().to_string(context.config);
control_flow
.rewrite_cond(context, shape, &alt_block_sep)
.and_then(|rw| Some(rw.0))
})
}
_ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
let alt_block_sep =
String::from("\n") + &shape.indent.block_only().to_string(context.config);
control_flow
.rewrite_cond(context, shape, &alt_block_sep)
.and_then(|rw| Some(rw.0))
}),
}
}
@ -996,17 +970,15 @@ struct ControlFlow<'a> {
fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'a>> {
match expr.node {
ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
Some(ControlFlow::new_if(
cond,
None,
if_block,
else_block.as_ref().map(|e| &**e),
expr_type == ExprType::SubExpression,
false,
expr.span,
))
}
ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
cond,
None,
if_block,
else_block.as_ref().map(|e| &**e),
expr_type == ExprType::SubExpression,
false,
expr.span,
)),
ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
Some(ControlFlow::new_if(
cond,
@ -1021,21 +993,15 @@ fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<Contr
ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
}
ast::ExprKind::Loop(ref block, label) => Some(
ControlFlow::new_loop(block, label, expr.span),
),
ast::ExprKind::While(ref cond, ref block, label) => Some(
ControlFlow::new_while(None, cond, block, label, expr.span),
),
ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => {
Some(ControlFlow::new_while(
Some(pat),
cond,
block,
label,
expr.span,
))
ast::ExprKind::Loop(ref block, label) => {
Some(ControlFlow::new_loop(block, label, expr.span))
}
ast::ExprKind::While(ref cond, ref block, label) => {
Some(ControlFlow::new_while(None, cond, block, label, expr.span))
}
ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
ControlFlow::new_while(Some(pat), cond, block, label, expr.span),
),
_ => None,
}
}
@ -1553,88 +1519,14 @@ fn rewrite_match(
ControlBraceStyle::AlwaysNextLine => 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())
} else {
shape.block_indent(0)
};
let arm_indent_str = arm_shape.indent.to_string(context.config);
let open_brace_pos = context
.codemap
.span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])), "{");
let arm_num = arms.len();
for (i, arm) in arms.iter().enumerate() {
// Make sure we get the stuff between arms.
let missed_str = if i == 0 {
context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
} else {
context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
};
let comment = try_opt!(rewrite_match_arm_comment(
context,
&missed_str,
arm_shape,
&arm_indent_str,
));
result.push_str(&comment);
result.push('\n');
result.push_str(&arm_indent_str);
let arm_str = arm.rewrite(&context, arm_shape.with_max_width(context.config));
if let Some(ref arm_str) = arm_str {
// Trim the trailing comma if necessary.
if i == arm_num - 1 && context.config.trailing_comma() == SeparatorTactic::Never &&
arm_str.ends_with(',')
{
result.push_str(&arm_str[0..arm_str.len() - 1])
} else {
result.push_str(arm_str)
}
} else {
// We couldn't format the arm, just reproduce the source.
let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
result.push_str(&snippet);
if context.config.trailing_comma() != SeparatorTactic::Never {
result.push_str(arm_comma(context.config, &arm.body))
}
}
}
// BytePos(1) = closing match brace.
let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
let last_comment = context.snippet(last_span);
let comment = try_opt!(rewrite_match_arm_comment(
context,
&last_comment,
arm_shape,
&arm_indent_str,
));
result.push_str(&comment);
result.push('\n');
result.push_str(&shape.indent.to_string(context.config));
result.push('}');
Some(result)
}
fn arm_start_pos(arm: &ast::Arm) -> BytePos {
let &ast::Arm {
ref attrs,
ref pats,
..
} = arm;
if !attrs.is_empty() {
return attrs[0].span.lo;
}
pats[0].span.lo
}
fn arm_end_pos(arm: &ast::Arm) -> BytePos {
arm.body.span.hi
Some(format!(
"match {}{}{{{}\n{}}}",
cond_str,
block_sep,
try_opt!(rewrite_match_arms(context, arms, shape, span, cond.span.hi)),
shape.indent.to_string(context.config),
))
}
fn arm_comma(config: &Config, body: &ast::Expr) -> &'static str {
@ -1651,186 +1543,252 @@ fn arm_comma(config: &Config, body: &ast::Expr) -> &'static str {
}
}
// Match arms.
impl Rewrite for ast::Arm {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
debug!("Arm::rewrite {:?} {:?}", self, shape);
let &ast::Arm {
ref attrs,
ref pats,
ref guard,
ref body,
} = self;
fn rewrite_match_pattern(
context: &RewriteContext,
pats: &Vec<ptr::P<ast::Pat>>,
guard: &Option<ptr::P<ast::Expr>>,
shape: Shape,
) -> Option<String> {
// Patterns
// 5 = ` => {`
let pat_shape = try_opt!(shape.sub_width(5));
let attr_str = if !attrs.is_empty() {
if contains_skip(attrs) {
return None;
}
format!(
"{}\n{}",
try_opt!(attrs.rewrite(context, shape)),
shape.indent.to_string(context.config)
)
let pat_strs = try_opt!(
pats.iter()
.map(|p| p.rewrite(context, pat_shape))
.collect::<Option<Vec<_>>>()
);
let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
let tactic = definitive_tactic(&items, ListTactic::HorizontalVertical, pat_shape.width);
let fmt = ListFormatting {
tactic: tactic,
separator: " |",
trailing_separator: SeparatorTactic::Never,
shape: pat_shape,
ends_with_newline: false,
config: context.config,
};
let pats_str = try_opt!(write_list(&items, &fmt));
// Guard
let guard_str = try_opt!(rewrite_guard(
context,
guard,
shape,
trimmed_last_line_width(&pats_str),
));
Some(format!("{}{}", pats_str, guard_str))
}
fn rewrite_match_arms(
context: &RewriteContext,
arms: &[ast::Arm],
shape: Shape,
span: Span,
cond_end_pos: BytePos,
) -> Option<String> {
let mut result = String::new();
let arm_shape = if context.config.indent_match_arms() {
shape.block_indent(context.config.tab_spaces())
} else {
shape.block_indent(0)
}.with_max_width(context.config);
let arm_indent_str = arm_shape.indent.to_string(context.config);
let open_brace_pos = context
.codemap
.span_after(mk_sp(cond_end_pos, arms[0].span().lo), "{");
let arm_num = arms.len();
for (i, arm) in arms.iter().enumerate() {
// Make sure we get the stuff between arms.
let missed_str = if i == 0 {
context.snippet(mk_sp(open_brace_pos, arm.span().lo))
} else {
String::new()
context.snippet(mk_sp(arms[i - 1].span().hi, arm.span().lo))
};
// Patterns
// 5 = ` => {`
let pat_shape = try_opt!(shape.sub_width(5));
let pat_strs = try_opt!(
pats.iter()
.map(|p| p.rewrite(context, pat_shape))
.collect::<Option<Vec<_>>>()
);
let all_simple = pat_strs.iter().all(|p| !p.contains('\n'));
let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
let mut tactic = definitive_tactic(&items, ListTactic::HorizontalVertical, pat_shape.width);
if tactic == DefinitiveListTactic::Horizontal && all_simple {
tactic = DefinitiveListTactic::Mixed;
}
let fmt = ListFormatting {
tactic: tactic,
separator: " |",
trailing_separator: SeparatorTactic::Never,
shape: pat_shape,
ends_with_newline: false,
config: context.config,
};
let pats_str = try_opt!(write_list(&items, &fmt));
let guard_str = try_opt!(rewrite_guard(
let comment = try_opt!(rewrite_match_arm_comment(
context,
guard,
shape,
trimmed_last_line_width(&pats_str),
&missed_str,
arm_shape,
&arm_indent_str,
));
result.push_str(&comment);
result.push('\n');
result.push_str(&arm_indent_str);
let pats_len = pats_str.len();
let pats_str = format!("{}{}", pats_str, guard_str);
let (mut extend, 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() => {
if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
(false, &**expr)
} else {
(false, &**body)
}
}
ast::ExprKind::Call(_, ref args) => (args.len() == 1, &**body),
ast::ExprKind::Closure(..) | ast::ExprKind::Struct(..) | ast::ExprKind::Tup(..) => (
true,
&**body,
),
_ => (false, &**body),
};
extend &= context.use_block_indent();
let comma = arm_comma(&context.config, body);
let alt_block_sep =
String::from("\n") + &shape.indent.block_only().to_string(context.config);
let pat_width = extra_offset(&pats_str, shape);
// Let's try and get the arm body on the same line as the condition.
// 4 = ` => `.len()
if shape.width > pat_width + comma.len() + 4 {
let arm_shape = shape
.offset_left(pat_width + 4)
.unwrap()
.sub_width(comma.len())
.unwrap();
let rewrite = nop_block_collapse(
format_expr(body, ExprType::Statement, context, arm_shape),
arm_shape.width,
);
let is_block = if let ast::ExprKind::Block(..) = body.node {
true
let arm_str = rewrite_match_arm(context, arm, arm_shape);
if let Some(ref arm_str) = arm_str {
// Trim the trailing comma if necessary.
if i == arm_num - 1 && context.config.trailing_comma() == SeparatorTactic::Never &&
arm_str.ends_with(',')
{
result.push_str(&arm_str[0..arm_str.len() - 1])
} else {
false
};
match rewrite {
Some(ref body_str)
if (!body_str.contains('\n') && body_str.len() <= arm_shape.width) ||
!context.config.wrap_match_arms() ||
(extend && first_line_width(body_str) <= arm_shape.width) ||
is_block =>
{
let block_sep = match context.config.control_brace_style() {
ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep.as_str(),
_ if guard.is_some() && pats_str.contains('\n') && is_block &&
body_str != "{}" &&
pats_len > context.config.tab_spaces() => alt_block_sep.as_str(),
_ => " ",
};
return Some(format!(
"{}{} =>{}{}{}",
attr_str.trim_left(),
pats_str,
block_sep,
body_str,
comma
));
}
_ => {}
result.push_str(arm_str)
}
} else {
// We couldn't format the arm, just reproduce the source.
let snippet = context.snippet(arm.span());
result.push_str(&snippet);
if context.config.trailing_comma() != SeparatorTactic::Never {
result.push_str(arm_comma(context.config, &arm.body))
}
}
}
// BytePos(1) = closing match brace.
let last_span = mk_sp(arms[arms.len() - 1].span().hi, span.hi - BytePos(1));
let last_comment = context.snippet(last_span);
let comment = try_opt!(rewrite_match_arm_comment(
context,
&last_comment,
arm_shape,
&arm_indent_str,
));
result.push_str(&comment);
// FIXME: we're doing a second rewrite of the expr; This may not be
// necessary.
let body_shape = try_opt!(shape.block_left(context.config.tab_spaces()));
let next_line_body = try_opt!(nop_block_collapse(
format_expr(body, ExprType::Statement, context, body_shape),
body_shape.width,
));
Some(result)
}
fn rewrite_match_arm(context: &RewriteContext, arm: &ast::Arm, shape: Shape) -> Option<String> {
let attr_str = if !arm.attrs.is_empty() {
if contains_skip(&arm.attrs) {
return None;
}
format!(
"{}\n{}",
try_opt!(arm.attrs.rewrite(context, shape)),
shape.indent.to_string(context.config)
)
} else {
String::new()
};
let pats_str = try_opt!(rewrite_match_pattern(context, &arm.pats, &arm.guard, shape));
let pats_str = attr_str + &pats_str;
rewrite_match_body(context, &arm.body, &pats_str, shape, arm.guard.is_some())
}
fn rewrite_match_body(
context: &RewriteContext,
body: &ptr::P<ast::Expr>,
pats_str: &str,
shape: Shape,
has_guard: bool,
) -> Option<String> {
let (extend, body) = match body.node {
ast::ExprKind::Block(ref block)
if !is_unsafe_block(block) && is_simple_block(block, context.codemap) => {
if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
(expr.can_be_overflowed(context, 1), &**expr)
} else {
(false, &**body)
}
}
_ => (body.can_be_overflowed(context, 1), &**body),
};
let comma = arm_comma(&context.config, body);
let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
let alt_block_sep = alt_block_sep.as_str();
let is_block = if let ast::ExprKind::Block(..) = body.node {
true
} else {
false
};
let combine_orig_body = |body_str: &str| {
let block_sep = match context.config.control_brace_style() {
ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
_ if has_guard && pats_str.contains('\n') && is_block && body_str != "{}" => {
alt_block_sep
}
_ => " ",
};
Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
};
let combine_next_line_body = |body_str: &str| {
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 comma = if context.config.match_block_trailing_comma() {
","
} else {
("{", "}")
}
""
};
(
"{",
format!("\n{}}}{}", shape.indent.to_string(context.config), comma),
)
} else {
("", ",")
("", String::from(","))
};
let block_sep = match context.config.control_brace_style() {
ControlBraceStyle::AlwaysNextLine => alt_block_sep + body_prefix + "\n",
ControlBraceStyle::AlwaysNextLine => format!("{}{}\n", alt_block_sep, body_prefix),
_ if body_prefix.is_empty() => "\n".to_owned(),
_ => " ".to_owned() + body_prefix + "\n",
};
} + &indent_str;
if context.config.wrap_match_arms() {
Some(format!(
"{}{} =>{}{}{}\n{}{}",
attr_str.trim_left(),
pats_str,
block_sep,
indent_str,
next_line_body,
shape.indent.to_string(context.config),
body_suffix
))
} else {
Some(format!(
"{}{} =>{}{}{}{}",
attr_str.trim_left(),
pats_str,
block_sep,
indent_str,
next_line_body,
body_suffix
))
Some(format!(
"{} =>{}{}{}",
pats_str,
block_sep,
body_str,
body_suffix
))
};
// Let's try and get the arm body on the same line as the condition.
// 4 = ` => `.len()
let orig_arm_shape = shape
.offset_left(extra_offset(&pats_str, shape) + 4)
.and_then(|shape| shape.sub_width(comma.len()));
let orig_body = if let Some(arm_shape) = orig_arm_shape {
let rewrite = nop_block_collapse(
format_expr(body, ExprType::Statement, context, arm_shape),
arm_shape.width,
);
match rewrite {
Some(ref body_str)
if ((!body_str.contains('\n')) && first_line_width(body_str) <= arm_shape.width) ||
is_block =>
{
return combine_orig_body(body_str);
}
_ => rewrite,
}
} else {
None
};
let orig_budget = orig_arm_shape.map_or(0, |shape| shape.width);
// Try putting body on the next line and see if it looks better.
let next_line_body_shape =
Shape::indented(shape.indent.block_indent(context.config), context.config);
let next_line_body = nop_block_collapse(
format_expr(body, ExprType::Statement, context, next_line_body_shape),
next_line_body_shape.width,
);
match (orig_body, next_line_body) {
(Some(ref orig_str), Some(ref next_line_str))
if prefer_next_line(orig_str, next_line_str) => combine_next_line_body(next_line_str),
(Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
combine_orig_body(orig_str)
}
(Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
combine_next_line_body(next_line_str)
}
(None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
(None, None) => None,
(Some(ref orig_str), _) => combine_orig_body(orig_str),
}
}
@ -1846,14 +1804,11 @@ fn rewrite_guard(
if let Some(ref guard) = *guard {
// First try to fit the guard string on the same line as the pattern.
// 4 = ` if `, 5 = ` => {`
if let Some(cond_shape) = shape
let cond_shape = shape
.offset_left(pattern_width + 4)
.and_then(|s| s.sub_width(5))
{
if let Some(cond_str) = guard
.rewrite(context, cond_shape)
.and_then(|s| s.rewrite(context, cond_shape))
{
.and_then(|s| s.sub_width(5));
if let Some(cond_shape) = cond_shape {
if let Some(cond_str) = guard.rewrite(context, cond_shape) {
if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
return Some(format!(" if {}", cond_str));
}
@ -1862,11 +1817,10 @@ fn rewrite_guard(
// Not enough space to put the guard after the pattern, try a newline.
// 3 = `if `, 5 = ` => {`
if let Some(cond_shape) =
Shape::indented(shape.indent.block_indent(context.config), context.config)
.offset_left(3)
.and_then(|s| s.sub_width(5))
{
let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
.offset_left(3)
.and_then(|s| s.sub_width(5));
if let Some(cond_shape) = cond_shape {
if let Some(cond_str) = guard.rewrite(context, cond_shape) {
return Some(format!(
"\n{}if {}",
@ -2514,26 +2468,22 @@ fn rewrite_index(
let index_shape = try_opt!(index_shape.sub_width(rbr.len() + rhs_overhead));
let new_index_rw = index.rewrite(context, index_shape);
match (orig_index_rw, new_index_rw) {
(_, Some(ref new_index_str)) if !new_index_str.contains('\n') => {
Some(format!(
"{}\n{}{}{}{}",
expr_str,
indent.to_string(&context.config),
lbr,
new_index_str,
rbr
))
}
(None, Some(ref new_index_str)) => {
Some(format!(
"{}\n{}{}{}{}",
expr_str,
indent.to_string(&context.config),
lbr,
new_index_str,
rbr
))
}
(_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
"{}\n{}{}{}{}",
expr_str,
indent.to_string(&context.config),
lbr,
new_index_str,
rbr
)),
(None, Some(ref new_index_str)) => Some(format!(
"{}\n{}{}{}{}",
expr_str,
indent.to_string(&context.config),
lbr,
new_index_str,
rbr
)),
(Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
_ => None,
}

View File

@ -60,12 +60,10 @@ fn compare_path_list_items(a: &ast::PathListItem, b: &ast::PathListItem) -> Orde
};
if name_ordering == Ordering::Equal {
match a.node.rename {
Some(a_rename) => {
match b.node.rename {
Some(b_rename) => a_rename.name.as_str().cmp(&b_rename.name.as_str()),
None => Ordering::Greater,
}
}
Some(a_rename) => match b.node.rename {
Some(b_rename) => a_rename.name.as_str().cmp(&b_rename.name.as_str()),
None => Ordering::Greater,
},
None => Ordering::Less,
}
} else {
@ -159,9 +157,9 @@ impl Rewrite for ast::ViewPath {
// Returns an empty string when the ViewPath is empty (like foo::bar::{})
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
match self.node {
ast::ViewPath_::ViewPathList(_, ref path_list) if path_list.is_empty() => Some(
String::new(),
),
ast::ViewPath_::ViewPathList(_, ref path_list) if path_list.is_empty() => {
Some(String::new())
}
ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
rewrite_use_list(shape, path, path_list, self.span, context)
}

View File

@ -189,25 +189,19 @@ impl BadIssueSeeker {
}
match part {
NumberPart::OpenParen => {
if c != '(' {
return IssueClassification::Bad(issue);
} else {
part = NumberPart::Pound;
}
}
NumberPart::Pound => {
if c == '#' {
part = NumberPart::Number;
}
}
NumberPart::Number => {
if c >= '0' && c <= '9' {
part = NumberPart::CloseParen;
} else {
return IssueClassification::Bad(issue);
}
}
NumberPart::OpenParen => if c != '(' {
return IssueClassification::Bad(issue);
} else {
part = NumberPart::Pound;
},
NumberPart::Pound => if c == '#' {
part = NumberPart::Number;
},
NumberPart::Number => if c >= '0' && c <= '9' {
part = NumberPart::CloseParen;
} else {
return IssueClassification::Bad(issue);
},
NumberPart::CloseParen => {}
}

View File

@ -362,12 +362,10 @@ impl<'a> FmtVisitor<'a> {
).map(|s| s + suffix)
.or_else(|| Some(self.snippet(e.span)))
}
None => {
stmt.rewrite(
&self.get_context(),
Shape::indented(self.block_indent, self.config),
)
}
None => stmt.rewrite(
&self.get_context(),
Shape::indented(self.block_indent, self.config),
),
}
} else {
None
@ -418,13 +416,11 @@ impl<'a> FmtVisitor<'a> {
let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
match variant_list {
Some(ref body_str) => self.buffer.push_str(body_str),
None => {
if contains_comment(&enum_snippet[brace_pos..]) {
self.format_missing_no_indent(span.hi - BytePos(1))
} else {
self.format_missing(span.hi - BytePos(1))
}
}
None => if contains_comment(&enum_snippet[brace_pos..]) {
self.format_missing_no_indent(span.hi - BytePos(1))
} else {
self.format_missing(span.hi - BytePos(1))
},
}
self.block_indent = self.block_indent.block_unindent(self.config);
@ -620,14 +616,12 @@ pub fn format_impl(
result.push_str(&offset.to_string(context.config));
}
BraceStyle::PreferSameLine => result.push(' '),
BraceStyle::SameLineWhere => {
if !where_clause_str.is_empty() {
result.push('\n');
result.push_str(&offset.to_string(context.config));
} else {
result.push(' ');
}
}
BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
result.push('\n');
result.push_str(&offset.to_string(context.config));
} else {
result.push(' ');
},
}
result.push('{');
@ -876,31 +870,27 @@ pub fn format_struct(
) -> Option<String> {
match *struct_def {
ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
ast::VariantData::Tuple(ref fields, _) => {
format_tuple_struct(
context,
item_name,
ident,
vis,
fields,
generics,
span,
offset,
)
}
ast::VariantData::Struct(ref fields, _) => {
format_struct_struct(
context,
item_name,
ident,
vis,
fields,
generics,
span,
offset,
one_line_width,
)
}
ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
context,
item_name,
ident,
vis,
fields,
generics,
span,
offset,
),
ast::VariantData::Struct(ref fields, _) => format_struct_struct(
context,
item_name,
ident,
vis,
fields,
generics,
span,
offset,
one_line_width,
),
}
}
@ -1003,16 +993,14 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent)
result.push_str(&offset.to_string(context.config));
}
BraceStyle::PreferSameLine => result.push(' '),
BraceStyle::SameLineWhere => {
if !where_clause_str.is_empty() &&
(!trait_items.is_empty() || result.contains('\n'))
{
result.push('\n');
result.push_str(&offset.to_string(context.config));
} else {
result.push(' ');
}
}
BraceStyle::SameLineWhere => if !where_clause_str.is_empty() &&
(!trait_items.is_empty() || result.contains('\n'))
{
result.push('\n');
result.push_str(&offset.to_string(context.config));
} else {
result.push(' ');
},
}
result.push('{');
@ -1072,19 +1060,17 @@ pub fn format_struct_struct(
let body_lo = context.codemap.span_after(span, "{");
let generics_str = match generics {
Some(g) => {
try_opt!(format_generics(
context,
g,
"{",
"{",
context.config.item_brace_style(),
fields.is_empty(),
offset,
mk_sp(span.lo, body_lo),
last_line_width(&result),
))
}
Some(g) => try_opt!(format_generics(
context,
g,
"{",
"{",
context.config.item_brace_style(),
fields.is_empty(),
offset,
mk_sp(span.lo, body_lo),
last_line_width(&result),
)),
None => {
// 3 = ` {}`, 2 = ` {`.
let overhead = if fields.is_empty() { 3 } else { 2 };
@ -1416,16 +1402,14 @@ pub fn rewrite_struct_field_prefix(
let type_annotation_spacing = type_annotation_spacing(context.config);
Some(match field.ident {
Some(name) => {
format!(
"{}{}{}{}{}:",
attr_str,
missing_comment,
vis,
name,
type_annotation_spacing.0
)
}
Some(name) => format!(
"{}{}{}{}{}:",
attr_str,
missing_comment,
vis,
name,
type_annotation_spacing.0
),
None => format!("{}{}{}", attr_str, missing_comment, vis),
})
}
@ -1492,19 +1476,15 @@ pub fn rewrite_struct_field(
match ty_rewritten {
// If we start from the next line and type fits in a single line, then do so.
Some(ref ty) => {
match rewrite_type_in_next_line() {
Some(ref new_ty) if !new_ty.contains('\n') => {
Some(format!(
"{}\n{}{}",
prefix,
type_offset.to_string(&context.config),
&new_ty
))
}
_ => Some(prefix + &ty),
}
}
Some(ref ty) => match rewrite_type_in_next_line() {
Some(ref new_ty) if !new_ty.contains('\n') => Some(format!(
"{}\n{}{}",
prefix,
type_offset.to_string(&context.config),
&new_ty
)),
_ => Some(prefix + &ty),
},
_ => {
let ty = try_opt!(rewrite_type_in_next_line());
Some(format!(
@ -2221,20 +2201,16 @@ fn rewrite_args(
.map_or(false, |s| s.trim().starts_with("//"));
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,
)
}
IndentStyle::Block => {
(
indent.block_indent(context.config),
context.config.trailing_comma(),
true,
)
}
IndentStyle::Block if fits_in_one_line => (
indent.block_indent(context.config),
SeparatorTactic::Never,
true,
),
IndentStyle::Block => (
indent.block_indent(context.config),
context.config.trailing_comma(),
true,
),
IndentStyle::Visual if last_line_ends_with_comment => {
(arg_indent, context.config.trailing_comma(), true)
}

View File

@ -104,6 +104,17 @@ impl Spanned for ast::Ty {
}
}
impl Spanned for ast::Arm {
fn span(&self) -> Span {
let hi = self.body.span.hi;
if self.attrs.is_empty() {
mk_sp(self.pats[0].span.lo, hi)
} else {
mk_sp(self.attrs[0].span.lo, hi)
}
}
}
impl Spanned for ast::Arg {
fn span(&self) -> Span {
if items::is_named_arg(self) {
@ -431,14 +442,12 @@ pub enum ErrorKind {
impl fmt::Display for ErrorKind {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ErrorKind::LineOverflow(found, maximum) => {
write!(
fmt,
"line exceeded maximum length (maximum: {}, found: {})",
maximum,
found
)
}
ErrorKind::LineOverflow(found, maximum) => write!(
fmt,
"line exceeded maximum length (maximum: {}, found: {})",
maximum,
found
),
ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
}

View File

@ -440,29 +440,23 @@ where
// Comment belongs to next item.
(Some(i), None) if i > separator_index => separator_index + 1,
// Block-style post-comment before the separator.
(Some(i), None) => {
cmp::max(
find_comment_end(&post_snippet[i..]).unwrap() + i,
separator_index + 1,
)
}
(Some(i), None) => cmp::max(
find_comment_end(&post_snippet[i..]).unwrap() + i,
separator_index + 1,
),
// Block-style post-comment. Either before or after the separator.
(Some(i), Some(j)) if i < j => {
cmp::max(
find_comment_end(&post_snippet[i..]).unwrap() + i,
separator_index + 1,
)
}
(Some(i), Some(j)) if i < j => cmp::max(
find_comment_end(&post_snippet[i..]).unwrap() + i,
separator_index + 1,
),
// Potential *single* line comment.
(_, Some(j)) if j > separator_index => j + 1,
_ => post_snippet.len(),
}
}
None => {
post_snippet
.find_uncommented(self.terminator)
.unwrap_or(post_snippet.len())
}
None => post_snippet
.find_uncommented(self.terminator)
.unwrap_or(post_snippet.len()),
};
if !post_snippet.is_empty() && comment_end > 0 {
@ -595,11 +589,9 @@ pub fn struct_lit_shape(
suffix_width: usize,
) -> Option<(Option<Shape>, Shape)> {
let v_shape = match context.config.struct_lit_style() {
IndentStyle::Visual => {
try_opt!(
try_opt!(shape.visual_indent(0).shrink_left(prefix_width)).sub_width(suffix_width)
)
}
IndentStyle::Visual => try_opt!(
try_opt!(shape.visual_indent(0).shrink_left(prefix_width)).sub_width(suffix_width)
),
IndentStyle::Block => {
let shape = shape.block_indent(context.config.tab_spaces());
Shape {

View File

@ -80,13 +80,11 @@ pub fn rewrite_macro(
let macro_name = match extra_ident {
None => format!("{}!", mac.node.path),
Some(ident) => {
if ident == symbol::keywords::Invalid.ident() {
format!("{}!", mac.node.path)
} else {
format!("{}! {}", mac.node.path, ident)
}
}
Some(ident) => if ident == symbol::keywords::Invalid.ident() {
format!("{}!", mac.node.path)
} else {
format!("{}! {}", mac.node.path, ident)
},
};
let style = if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {

View File

@ -54,23 +54,15 @@ impl Rewrite for Pat {
let result = format!("{}{}{}{}", prefix, mut_infix, id_str, sub_pat);
wrap_str(result, context.config.max_width(), shape)
}
PatKind::Wild => {
if 1 <= shape.width {
Some("_".to_owned())
} else {
None
}
}
PatKind::Range(ref lhs, ref rhs, ref end_kind) => {
match *end_kind {
RangeEnd::Included => {
rewrite_pair(&**lhs, &**rhs, "", "...", "", context, shape)
}
RangeEnd::Excluded => {
rewrite_pair(&**lhs, &**rhs, "", "..", "", context, shape)
}
}
}
PatKind::Wild => if 1 <= shape.width {
Some("_".to_owned())
} else {
None
},
PatKind::Range(ref lhs, ref rhs, ref end_kind) => match *end_kind {
RangeEnd::Included => rewrite_pair(&**lhs, &**rhs, "", "...", "", context, shape),
RangeEnd::Excluded => rewrite_pair(&**lhs, &**rhs, "", "..", "", context, shape),
},
PatKind::Ref(ref pat, mutability) => {
let prefix = format!("&{}", format_mutability(mutability));
rewrite_unary_prefix(context, &prefix, &**pat, shape)
@ -121,13 +113,11 @@ impl Rewrite for Pat {
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,
)
}
PatKind::Mac(..) => wrap_str(
context.snippet(self.span),
context.config.max_width(),
shape,
),
}
}
}
@ -250,18 +240,16 @@ impl<'a> Spanned for TuplePatField<'a> {
pub fn can_be_overflowed_pat(context: &RewriteContext, pat: &TuplePatField, len: usize) -> bool {
match pat {
&TuplePatField::Pat(ref pat) => {
match pat.node {
ast::PatKind::Path(..) | ast::PatKind::Tuple(..) | ast::PatKind::Struct(..) => {
context.use_block_indent() && len == 1
}
ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => {
can_be_overflowed_pat(context, &TuplePatField::Pat(p), len)
}
ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len),
_ => false,
&TuplePatField::Pat(ref pat) => match pat.node {
ast::PatKind::Path(..) | ast::PatKind::Tuple(..) | ast::PatKind::Struct(..) => {
context.use_block_indent() && len == 1
}
}
ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => {
can_be_overflowed_pat(context, &TuplePatField::Pat(p), len)
}
ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len),
_ => false,
},
&TuplePatField::Dotdot(..) => false,
}
}

View File

@ -474,14 +474,12 @@ impl Rewrite for ast::WherePredicate {
ref lifetime,
ref bounds,
..
}) => {
try_opt!(rewrite_bounded_lifetime(
lifetime,
bounds.iter(),
context,
shape,
))
}
}) => try_opt!(rewrite_bounded_lifetime(
lifetime,
bounds.iter(),
context,
shape,
)),
ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
ref lhs_ty,
ref rhs_ty,
@ -727,14 +725,12 @@ impl Rewrite for ast::Ty {
format!("[{}]", ty_str)
})
}
ast::TyKind::Tup(ref items) => {
rewrite_tuple(
context,
&items.iter().map(|x| &**x).collect::<Vec<_>>()[..],
self.span,
shape,
)
}
ast::TyKind::Tup(ref items) => rewrite_tuple(
context,
&items.iter().map(|x| &**x).collect::<Vec<_>>()[..],
self.span,
shape,
),
ast::TyKind::Path(ref q_self, ref path) => {
rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
}
@ -744,21 +740,17 @@ impl Rewrite for ast::Ty {
let rbr = if use_spaces { " ]" } else { "]" };
rewrite_pair(&**ty, &**repeats, lbr, "; ", rbr, context, shape)
}
ast::TyKind::Infer => {
if shape.width >= 1 {
Some("_".to_owned())
} else {
None
}
}
ast::TyKind::Infer => if shape.width >= 1 {
Some("_".to_owned())
} else {
None
},
ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
ast::TyKind::Never => Some(String::from("!")),
ast::TyKind::Mac(..) => None,
ast::TyKind::ImplicitSelf => Some(String::from("")),
ast::TyKind::ImplTrait(ref it) => {
it.rewrite(context, shape)
.map(|it_str| format!("impl {}", it_str))
}
ast::TyKind::ImplTrait(ref it) => it.rewrite(context, shape)
.map(|it_str| format!("impl {}", it_str)),
ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
}
}

View File

@ -25,11 +25,9 @@ use SKIP_ANNOTATION;
pub fn extra_offset(text: &str, shape: Shape) -> usize {
match text.rfind('\n') {
// 1 for newline character
Some(idx) => {
text.len()
.checked_sub(idx + 1 + shape.used_width())
.unwrap_or(0)
}
Some(idx) => text.len()
.checked_sub(idx + 1 + shape.used_width())
.unwrap_or(0),
None => text.len(),
}
}
@ -168,15 +166,13 @@ pub fn semicolon_for_expr(expr: &ast::Expr) -> bool {
#[inline]
pub fn semicolon_for_stmt(stmt: &ast::Stmt) -> bool {
match stmt.node {
ast::StmtKind::Semi(ref expr) => {
match expr.node {
ast::ExprKind::While(..) |
ast::ExprKind::WhileLet(..) |
ast::ExprKind::Loop(..) |
ast::ExprKind::ForLoop(..) => false,
_ => true,
}
}
ast::StmtKind::Semi(ref expr) => match expr.node {
ast::ExprKind::While(..) |
ast::ExprKind::WhileLet(..) |
ast::ExprKind::Loop(..) |
ast::ExprKind::ForLoop(..) => false,
_ => true,
},
ast::StmtKind::Expr(..) => false,
_ => true,
}

View File

@ -289,12 +289,10 @@ impl<'a> FmtVisitor<'a> {
assert!(!self.visit_attrs(&attrs));
}
}
_ => {
if self.visit_attrs(&item.attrs) {
self.push_rewrite(item.span, None);
return;
}
}
_ => if self.visit_attrs(&item.attrs) {
self.push_rewrite(item.span, None);
return;
},
}
match item.node {

View File

@ -3,10 +3,7 @@
fn main() {
match lorem {
true => {
let ipsum = dolor;
println!("{:?}", ipsum);
}
true => foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(x),
false => {
println!("{}", sit)
}

View File

@ -3,10 +3,7 @@
fn main() {
match lorem {
true => {
let ipsum = dolor;
println!("{}", ipsum);
}
true => foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(x),
false => {
println!("{}", sit)
}

View File

@ -3,12 +3,8 @@
fn main() {
match lorem {
true => {
let ipsum = dolor;
println!("{:?}", ipsum);
}
false => {
println!("{}", sit)
}
true =>
foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(x),
false => println!("{}", sit),
}
}

View File

@ -4,8 +4,7 @@
fn main() {
match lorem {
true => {
let ipsum = dolor;
println!("{}", ipsum);
foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(x)
}
false => println!("{}", sit),
}

View File

@ -173,17 +173,15 @@ fn macros() {
baz!(one_item_macro_which_is_also_loooooooooooooooooooooooooooooooooooooooooooooooong);
let _ = match option {
None => {
baz!(
function,
like,
macro_as,
expression,
which,
is,
loooooooooooooooong
)
}
None => baz!(
function,
like,
macro_as,
expression,
which,
is,
loooooooooooooooong
),
Some(p) => baz!(one_item_macro_as_expression_which_is_also_loooooooooooooooong),
};
}
@ -318,12 +316,10 @@ fn combine_block() {
y => func(
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
),
_ => {
func(
x,
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy,
zzz,
)
}
_ => func(
x,
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy,
zzz,
),
}
}

View File

@ -15,14 +15,12 @@ fn main() {
2 => "two",
3 => "three",
4 => "four",
5 => {
match y {
'a' => 'A',
'b' => 'B',
'c' => 'C',
_ => "Nope",
}
}
5 => match y {
'a' => 'A',
'b' => 'B',
'c' => 'C',
_ => "Nope",
},
_ => "something else",
}

View File

@ -5,12 +5,10 @@ impl Struct {
fn fun() {
let result = match <R::RequestResult as serde::Deserialize>::deserialize(&json) {
Ok(v) => v,
Err(e) => {
match <R::ErrorResult as serde::Deserialize>::deserialize(&json) {
Ok(v) => return Err(Error::with_json(v)),
Err(e2) => return Err(Error::with_json(e)),
}
}
Err(e) => match <R::ErrorResult as serde::Deserialize>::deserialize(&json) {
Ok(v) => return Err(Error::with_json(v)),
Err(e2) => return Err(Error::with_json(e)),
},
};
}
}

View File

@ -4,9 +4,7 @@
fn foo() {
match x {
a => {
foo()
}
a => foo(),
b => (
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,

View File

@ -215,14 +215,12 @@ fn issue355() {
wc => println!["a", b], // comment
xc => vec![1, 2], // comment
yc => vec![3; 4], // comment
yd => {
looooooooooooooooooooooooooooooooooooooooooooooooooooooooong_func(
aaaaaaaaaa,
bbbbbbbbbb,
cccccccccc,
dddddddddd,
)
}
yd => looooooooooooooooooooooooooooooooooooooooooooooooooooooooong_func(
aaaaaaaaaa,
bbbbbbbbbb,
cccccccccc,
dddddddddd,
),
}
}
@ -342,14 +340,12 @@ fn issue1371() {
}
sfEvtLostFocus => LostFocus,
sfEvtGainedFocus => GainedFocus,
sfEvtTextEntered => {
TextEntered {
unicode: unsafe {
::std::char::from_u32((*event.text.as_ref()).unicode)
.expect("Invalid unicode encountered on TextEntered event")
},
}
}
sfEvtTextEntered => TextEntered {
unicode: unsafe {
::std::char::from_u32((*event.text.as_ref()).unicode)
.expect("Invalid unicode encountered on TextEntered event")
},
},
sfEvtKeyPressed => {
let e = unsafe { event.key.as_ref() };

View File

@ -19,13 +19,11 @@ fn main() {
},
|item| {
match *item {
StructLitField::Regular(ref field) => {
rewrite_field(
inner_context,
&field,
&Constraints::new(v_budget.checked_sub(1).unwrap_or(0), indent),
)
}
StructLitField::Regular(ref field) => rewrite_field(
inner_context,
&field,
&Constraints::new(v_budget.checked_sub(1).unwrap_or(0), indent),
),
StructLitField::Base(ref expr) => {
// 2 = ..
expr.rewrite(