This commit is contained in:
Nick Cameron 2017-02-22 16:20:50 +13:00
parent ba1202f6b3
commit 9eb78a3333
16 changed files with 431 additions and 406 deletions

View File

@ -16,11 +16,11 @@ fn main() {
writeln!(f,
"const COMMIT_HASH: Option<&'static str> = {:?};",
git_head_sha1())
.unwrap();
.unwrap();
writeln!(f,
"const WORKTREE_CLEAN: Option<bool> = {:?};",
git_tree_is_clean())
.unwrap();
.unwrap();
// cargo:rerun-if-changed requires one entry per individual file.
for entry in WalkDir::new("src") {

View File

@ -119,20 +119,25 @@ pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -
// brace.
(parent_shape, false)
} else if parent_rewrite.contains('\n') {
(chain_indent(context, parent_shape.block_indent(context.config.tab_spaces)), false)
(chain_indent(context,
parent_shape.block_indent(context.config.tab_spaces)),
false)
} else {
(chain_indent_newline(context, shape.add_offset(parent_rewrite.len())), false)
};
let max_width = try_opt!((shape.width + shape.indent.width() + shape.offset).checked_sub(nested_shape.indent.width() + nested_shape.offset));
let max_width = try_opt!((shape.width + shape.indent.width() + shape.offset)
.checked_sub(nested_shape.indent.width() +
nested_shape.offset));
// The alignement in the shape is only used if we start the item on a new
// line, so we don't need to preserve the offset.
let child_shape = Shape { width: max_width, ..nested_shape };
debug!("child_shape {:?}", child_shape);
let mut rewrites = try_opt!(subexpr_list.iter()
.rev()
.map(|e| rewrite_chain_subexpr(e, total_span, context, child_shape))
.collect::<Option<Vec<_>>>());
let mut rewrites =
try_opt!(subexpr_list.iter()
.rev()
.map(|e| rewrite_chain_subexpr(e, total_span, context, child_shape))
.collect::<Option<Vec<_>>>());
// Total of all items excluding the last.
let almost_total = rewrites[..rewrites.len() - 1]
@ -199,10 +204,10 @@ pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -
// True if the chain is only `?`s.
fn chain_only_try(exprs: &[ast::Expr]) -> bool {
exprs.iter().all(|e| if let ast::ExprKind::Try(_) = e.node {
true
} else {
false
})
true
} else {
false
})
}
pub fn rewrite_try(expr: &ast::Expr,
@ -400,8 +405,8 @@ fn rewrite_method_call(method_name: ast::Ident,
(args[0].span.hi, String::new())
} else {
let type_list: Vec<_> = try_opt!(types.iter()
.map(|ty| ty.rewrite(context, shape))
.collect());
.map(|ty| ty.rewrite(context, shape))
.collect());
let type_str = if context.config.spaces_within_angle_brackets && type_list.len() > 0 {
format!("::< {} >", type_list.join(", "))

View File

@ -110,10 +110,10 @@ pub fn rewrite_comment(orig: &str,
})
.map(left_trim_comment_line)
.map(|line| if orig.starts_with("/*") && line_breaks == 0 {
line.trim_left()
} else {
line
});
line.trim_left()
} else {
line
});
let mut result = opener.to_owned();
for line in lines {
@ -771,9 +771,9 @@ mod test {
fn uncommented(text: &str) -> String {
CharClasses::new(text.chars())
.filter_map(|(s, c)| match s {
FullCodeCharKind::Normal => Some(c),
_ => None,
})
FullCodeCharKind::Normal => Some(c),
_ => None,
})
.collect()
}

View File

@ -115,7 +115,7 @@ fn format_expr(expr: &ast::Expr,
expr_type == ExprType::SubExpression,
false,
expr.span)
.rewrite(context, shape)
.rewrite(context, shape)
}
ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
ControlFlow::new_if(cond,
@ -125,7 +125,7 @@ fn format_expr(expr: &ast::Expr,
expr_type == ExprType::SubExpression,
false,
expr.span)
.rewrite(context, shape)
.rewrite(context, shape)
}
ast::ExprKind::Match(ref cond, ref arms) => {
rewrite_match(context, cond, arms, shape, expr.span)
@ -170,8 +170,9 @@ 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(Some(ref expr)) => {
@ -300,9 +301,11 @@ pub fn rewrite_pair<LHS, RHS>(lhs: &LHS,
// Re-evaluate the rhs because we have more space now:
let infix = infix.trim_right();
let lhs_budget = try_opt!(context.config
.max_width
.checked_sub(shape.used_width() + prefix.len() + infix.len()));
let rhs_shape = try_opt!(shape.sub_width(suffix.len() + prefix.len())).visual_indent(prefix.len());
.max_width
.checked_sub(shape.used_width() + prefix.len() +
infix.len()));
let rhs_shape = try_opt!(shape.sub_width(suffix.len() + prefix.len()))
.visual_indent(prefix.len());
let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape));
let lhs_result = try_opt!(lhs.rewrite(context, Shape { width: lhs_budget, ..shape }));
@ -328,20 +331,20 @@ pub fn rewrite_array<'a, I>(expr_iter: I,
1 // "["
};
let nested_shape = try_opt!(shape.visual_indent(bracket_size).sub_width(bracket_size * 2));
let items =
itemize_list(context.codemap,
expr_iter,
"]",
|item| item.span.lo,
|item| item.span.hi,
|item| item.rewrite(context, nested_shape),
span.lo,
span.hi)
let items = itemize_list(context.codemap,
expr_iter,
"]",
|item| item.span.lo,
|item| item.span.hi,
|item| item.rewrite(context, nested_shape),
span.lo,
span.hi)
.collect::<Vec<_>>();
let has_long_item = try_opt!(items.iter()
.map(|li| li.item.as_ref().map(|s| s.len() > 10))
.fold(Some(false), |acc, x| acc.and_then(|y| x.map(|x| x || y))));
.map(|li| li.item.as_ref().map(|s| s.len() > 10))
.fold(Some(false),
|acc, x| acc.and_then(|y| x.map(|x| x || y))));
let tactic = if has_long_item || items.iter().any(ListItem::is_multiline) {
definitive_tactic(&items, ListTactic::HorizontalVertical, nested_shape.width)
@ -360,10 +363,10 @@ pub fn rewrite_array<'a, I>(expr_iter: I,
let list_str = try_opt!(write_list(&items, &fmt));
Some(if context.config.spaces_within_square_brackets && list_str.len() > 0 {
format!("[ {} ]", list_str)
} else {
format!("[{}]", list_str)
})
format!("[ {} ]", list_str)
} else {
format!("[{}]", list_str)
})
}
// This functions is pretty messy because of the rules around closures and blocks:
@ -396,15 +399,14 @@ fn rewrite_closure(capture: ast::CaptureBy,
let arg_shape = try_opt!(nested_shape.shrink_left(1)).visual_indent(0);
let ret_str = try_opt!(fn_decl.output.rewrite(context, arg_shape));
let arg_items =
itemize_list(context.codemap,
fn_decl.inputs.iter(),
"|",
|arg| span_lo_for_arg(arg),
|arg| span_hi_for_arg(arg),
|arg| arg.rewrite(context, arg_shape),
context.codemap.span_after(span, "|"),
body.span.lo);
let arg_items = itemize_list(context.codemap,
fn_decl.inputs.iter(),
"|",
|arg| span_lo_for_arg(arg),
|arg| span_hi_for_arg(arg),
|arg| arg.rewrite(context, arg_shape),
context.codemap.span_after(span, "|"),
body.span.lo);
let item_vec = arg_items.collect::<Vec<_>>();
// 1 = space between arguments and return type.
let horizontal_budget = nested_shape.width.checked_sub(ret_str.len() + 1).unwrap_or(0);
@ -453,10 +455,7 @@ fn rewrite_closure(capture: ast::CaptureBy,
if ret_str.is_empty() && !needs_block {
// lock.stmts.len() == 1
if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
if let Some(rw) = rewrite_closure_expr(expr,
&prefix,
context,
body_shape) {
if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
return Some(rw);
}
}
@ -466,8 +465,7 @@ fn rewrite_closure(capture: ast::CaptureBy,
// We need braces, but we might still prefer a one-liner.
let stmt = &block.stmts[0];
// 4 = braces and spaces.
let mut rewrite = stmt.rewrite(context,
try_opt!(body_shape.sub_width(4)));
let mut rewrite = stmt.rewrite(context, try_opt!(body_shape.sub_width(4)));
// Checks if rewrite succeeded and fits on a single line.
rewrite = and_one_line(rewrite);
@ -482,10 +480,7 @@ fn rewrite_closure(capture: ast::CaptureBy,
return rewrite_closure_block(&block, prefix, context, body_shape);
}
if let Some(rw) = rewrite_closure_expr(body,
&prefix,
context,
body_shape) {
if let Some(rw) = rewrite_closure_expr(body, &prefix, context, body_shape) {
return Some(rw);
}
@ -546,10 +541,10 @@ fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String
block_str.map(|block_str| if block_str.starts_with('{') && budget >= 2 &&
(block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() ==
block_str.len() - 2) {
"{}".to_owned()
} else {
block_str.to_owned()
})
"{}".to_owned()
} else {
block_str.to_owned()
})
}
impl Rewrite for ast::Block {
@ -599,9 +594,10 @@ impl Rewrite for ast::Block {
};
if is_simple_block(self, context.codemap) && prefix.len() < shape.width {
let expr_str = self.stmts[0].rewrite(context,
Shape::legacy(shape.width - prefix.len(),
shape.indent));
let expr_str =
self.stmts[0].rewrite(context,
Shape::legacy(shape.width - prefix.len(),
shape.indent));
let expr_str = try_opt!(expr_str);
let result = format!("{}{{ {} }}", prefix, expr_str);
if result.len() <= shape.width && !result.contains('\n') {
@ -643,7 +639,7 @@ impl Rewrite for ast::Stmt {
},
context,
try_opt!(shape.sub_width(suffix.len())))
.map(|s| s + suffix)
.map(|s| s + suffix)
}
ast::StmtKind::Mac(..) |
ast::StmtKind::Item(..) => None,
@ -782,8 +778,8 @@ impl<'a> ControlFlow<'a> {
let new_width = try_opt!(new_width.checked_sub(if_str.len()));
let else_expr = &else_node.stmts[0];
let else_str =
try_opt!(else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
let else_str = try_opt!(else_expr.rewrite(context,
Shape::legacy(new_width, Indent::empty())));
if if_str.contains('\n') || else_str.contains('\n') {
return None;
@ -877,17 +873,18 @@ impl<'a> Rewrite for ControlFlow<'a> {
let between_kwd_cond =
mk_sp(context.codemap.span_after(self.span, self.keyword.trim()),
self.pat.map_or(cond_span.lo, |p| if self.matcher.is_empty() {
p.span.lo
} else {
context.codemap.span_before(self.span, self.matcher.trim())
}));
p.span.lo
} else {
context.codemap.span_before(self.span, self.matcher.trim())
}));
let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
let after_cond_comment =
extract_comment(mk_sp(cond_span.hi, self.block.span.lo), context, shape);
let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
let alt_block_sep = String::from("\n") +
&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 ==
@ -897,15 +894,15 @@ impl<'a> Rewrite for ControlFlow<'a> {
" "
};
let mut result = format!("{}{}{}{}{}{}",
label_string,
self.keyword,
between_kwd_cond_comment.as_ref()
.map_or(if pat_expr_string.is_empty() { "" } else { " " },
|s| &**s),
pat_expr_string,
after_cond_comment.as_ref().map_or(block_sep, |s| &**s),
block_str);
let mut result =
format!("{}{}{}{}{}{}",
label_string,
self.keyword,
between_kwd_cond_comment.as_ref()
.map_or(if pat_expr_string.is_empty() { "" } else { " " }, |s| &**s),
pat_expr_string,
after_cond_comment.as_ref().map_or(block_sep, |s| &**s),
block_str);
if let Some(else_block) = self.else_block {
// Since this is an else block, we should not indent for the assignment preceding
@ -925,7 +922,7 @@ impl<'a> Rewrite for ControlFlow<'a> {
false,
true,
mk_sp(else_block.span.lo, self.span.hi))
.rewrite(context, shape.visual_indent(0))
.rewrite(context, shape.visual_indent(0))
}
ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
ControlFlow::new_if(cond,
@ -935,7 +932,7 @@ impl<'a> Rewrite for ControlFlow<'a> {
false,
true,
mk_sp(else_block.span.lo, self.span.hi))
.rewrite(context, shape.visual_indent(0))
.rewrite(context, shape.visual_indent(0))
}
_ => {
last_in_chain = true;
@ -953,10 +950,10 @@ impl<'a> Rewrite for ControlFlow<'a> {
let between_kwd_else_block_comment =
extract_comment(between_kwd_else_block, context, shape);
let after_else = mk_sp(context.codemap
.span_after(mk_sp(self.block.span.hi, else_block.span.lo),
"else"),
else_block.span.lo);
let after_else =
mk_sp(context.codemap
.span_after(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
else_block.span.lo);
let after_else_comment = extract_comment(after_else, context, shape);
let between_sep = match context.config.control_brace_style {
@ -973,7 +970,7 @@ impl<'a> Rewrite for ControlFlow<'a> {
between_kwd_else_block_comment.as_ref()
.map_or(between_sep, |s| &**s),
after_else_comment.as_ref().map_or(after_sep, |s| &**s))
.ok());
.ok());
result.push_str(&try_opt!(rewrite));
}
@ -1108,16 +1105,17 @@ fn rewrite_match(context: &RewriteContext,
} 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));
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,
Shape { width: context.config.max_width - arm_shape.indent.width(), .. arm_shape });
Shape {
width: context.config.max_width - arm_shape.indent.width(),
..arm_shape
});
if let Some(ref arm_str) = arm_str {
result.push_str(arm_str);
} else {
@ -1130,10 +1128,8 @@ fn rewrite_match(context: &RewriteContext,
// 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));
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));
@ -1203,8 +1199,8 @@ impl Rewrite for ast::Arm {
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<_>>>());
.map(|p| p.rewrite(context, pat_shape))
.collect::<Option<Vec<_>>>());
let all_simple = pat_strs.iter().all(|p| pat_is_simple(p));
let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
@ -1251,17 +1247,18 @@ impl Rewrite for ast::Arm {
};
let comma = arm_comma(&context.config, self, body);
let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
let alt_block_sep = String::from("\n") +
&shape.indent.block_only().to_string(context.config);
// Let's try and get the arm body on the same line as the condition.
// 4 = ` => `.len()
if shape.width > line_start + comma.len() + 4 {
let arm_shape = shape.shrink_left(line_start + 4).unwrap().sub_width(comma.len()).unwrap().block();
let arm_shape =
shape.shrink_left(line_start + 4).unwrap().sub_width(comma.len()).unwrap().block();
// TODO
// let offset = Indent::new(shape.indent.block_indent,
// line_start + 4 - shape.indent.block_indent);
let rewrite = nop_block_collapse(body.rewrite(context, arm_shape),
arm_shape.width);
let rewrite = nop_block_collapse(body.rewrite(context, arm_shape), arm_shape.width);
let is_block = if let ast::ExprKind::Block(..) = body.node {
true
} else {
@ -1292,7 +1289,8 @@ impl Rewrite for ast::Arm {
// TODO
// let body_budget = try_opt!(shape.width.checked_sub(context.config.tab_spaces));
// let indent = shape.indent.block_only().block_indent(context.config);
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);
@ -1341,9 +1339,10 @@ fn rewrite_guard(context: &RewriteContext,
// 4 = ` if `, 5 = ` => {`
let overhead = pattern_width + 4 + 5;
if overhead < shape.width {
let cond_str = guard.rewrite(context,
Shape::legacy(shape.width - overhead,
shape.indent + pattern_width + 4));
let cond_str =
guard.rewrite(context,
Shape::legacy(shape.width - overhead,
shape.indent + pattern_width + 4));
if let Some(cond_str) = cond_str {
return Some(format!(" if {}", cond_str));
}
@ -1389,7 +1388,8 @@ fn rewrite_pat_expr(context: &RewriteContext,
} else {
format!("{} ", matcher)
};
let pat_shape = try_opt!(try_opt!(shape.shrink_left(matcher.len())).sub_width(connector.len()));
let pat_shape = try_opt!(try_opt!(shape.shrink_left(matcher.len()))
.sub_width(connector.len()));
let pat_string = try_opt!(pat.rewrite(context, pat_shape));
format!("{}{}{}", matcher, pat_string, connector)
}
@ -1403,12 +1403,14 @@ fn rewrite_pat_expr(context: &RewriteContext,
if shape.width > extra_offset + 1 {
let spacer = if pat.is_some() { " " } else { "" };
let expr_shape = try_opt!(shape.sub_width(extra_offset + spacer.len())).add_offset(extra_offset + spacer.len());
let expr_shape = try_opt!(shape.sub_width(extra_offset + spacer.len()))
.add_offset(extra_offset + spacer.len());
let expr_rewrite = expr.rewrite(context, expr_shape);
if let Some(expr_string) = expr_rewrite {
let pat_simple = pat.and_then(|p| {
p.rewrite(context, Shape::legacy(context.config.max_width, Indent::empty()))
p.rewrite(context,
Shape::legacy(context.config.max_width, Indent::empty()))
})
.map(|s| pat_is_simple(&s));
@ -1540,15 +1542,16 @@ fn rewrite_call_inner<R>(context: &RewriteContext,
let nested_shape = shape.visual_indent(used_width + 1);
let arg_count = args.len();
let items =
itemize_list(context.codemap,
args.iter(),
")",
|item| item.span.lo,
|item| item.span.hi,
|item| item.rewrite(context, Shape { width: remaining_width, ..nested_shape }),
span.lo,
span.hi);
let items = itemize_list(context.codemap,
args.iter(),
")",
|item| item.span.lo,
|item| item.span.hi,
|item| {
item.rewrite(context, Shape { width: remaining_width, ..nested_shape })
},
span.lo,
span.hi);
let mut item_vec: Vec<_> = items.collect();
// Try letting the last argument overflow to the next line with block
@ -1584,7 +1587,7 @@ fn rewrite_call_inner<R>(context: &RewriteContext,
let tactic = definitive_tactic(&item_vec,
ListTactic::LimitedHorizontalVertical(context.config
.fn_call_width),
.fn_call_width),
remaining_width);
// Replace the stub with the full overflowing last argument if the rewrite
@ -1614,10 +1617,10 @@ fn rewrite_call_inner<R>(context: &RewriteContext,
};
Ok(if context.config.spaces_within_parens && list_str.len() > 0 {
format!("{}( {} )", callee_str, list_str)
} else {
format!("{}({})", callee_str, list_str)
})
format!("{}( {} )", callee_str, list_str)
} else {
format!("{}({})", callee_str, list_str)
})
}
fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
@ -1629,10 +1632,10 @@ fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) ->
debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
subexpr_str.map(|s| if context.config.spaces_within_parens && s.len() > 0 {
format!("( {} )", s)
} else {
format!("({})", s)
})
format!("( {} )", s)
} else {
format!("({})", s)
})
}
fn rewrite_index(expr: &ast::Expr,
@ -1658,8 +1661,8 @@ fn rewrite_index(expr: &ast::Expr,
let indent = indent.to_string(&context.config);
// FIXME this is not right, since we don't take into account that shape.width
// might be reduced from max_width by something on the right.
let budget =
try_opt!(context.config.max_width.checked_sub(indent.len() + lbr.len() + rbr.len()));
let budget = try_opt!(context.config.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))
}
@ -1680,19 +1683,20 @@ fn rewrite_struct_lit<'a>(context: &RewriteContext,
// 2 = " {".len()
let path_shape = try_opt!(shape.sub_width(2));
let path_str = try_opt!(rewrite_path(context,
PathContext::Expr,
None,
path,
path_shape));
let path_str = try_opt!(rewrite_path(context, PathContext::Expr, None, path, path_shape));
// Foo { a: Foo } - indent is +3, width is -5.
let h_shape = shape.sub_width(path_str.len() + 5);
let v_shape = match context.config.struct_lit_style {
StructLitStyle::Visual => try_opt!(try_opt!(shape.shrink_left(path_str.len() + 3)).sub_width(2)),
StructLitStyle::Visual => {
try_opt!(try_opt!(shape.shrink_left(path_str.len() + 3)).sub_width(2))
}
StructLitStyle::Block => {
let shape = shape.block_indent(context.config.tab_spaces);
Shape { width: try_opt!(context.config.max_width.checked_sub(shape.indent.width())), ..shape }
Shape {
width: try_opt!(context.config.max_width.checked_sub(shape.indent.width())),
..shape
}
}
};
@ -1706,13 +1710,12 @@ fn rewrite_struct_lit<'a>(context: &RewriteContext,
|item| match *item {
StructLitField::Regular(field) => field.span.lo,
StructLitField::Base(expr) => {
let last_field_hi = fields.last()
.map_or(span.lo, |field| field.span.hi);
let snippet =
context.snippet(mk_sp(last_field_hi, expr.span.lo));
let pos = snippet.find_uncommented("..").unwrap();
last_field_hi + BytePos(pos as u32)
}
let last_field_hi = fields.last()
.map_or(span.lo, |field| field.span.hi);
let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
let pos = snippet.find_uncommented("..").unwrap();
last_field_hi + BytePos(pos as u32)
}
},
|item| match *item {
StructLitField::Regular(field) => field.span.hi,
@ -1722,14 +1725,11 @@ fn rewrite_struct_lit<'a>(context: &RewriteContext,
match *item {
StructLitField::Regular(field) => {
// The 1 taken from the v_budget is for the comma.
rewrite_field(context,
field,
try_opt!(v_shape.sub_width(1)))
rewrite_field(context, field, try_opt!(v_shape.sub_width(1)))
}
StructLitField::Base(expr) => {
// 2 = ..
expr.rewrite(context,
try_opt!(v_shape.shrink_left(2)))
expr.rewrite(context, try_opt!(v_shape.shrink_left(2)))
.map(|s| format!("..{}", s))
}
}
@ -1827,8 +1827,8 @@ fn rewrite_field(context: &RewriteContext, field: &ast::Field, shape: Shape) ->
let expr = field.expr
.rewrite(context,
Shape::legacy(try_opt!(context.config
.max_width
.checked_sub(expr_offset.width())),
.max_width
.checked_sub(expr_offset.width())),
expr_offset));
expr.map(|s| format!("{}:\n{}{}", name, expr_offset.to_string(&context.config), s))
}
@ -1851,13 +1851,13 @@ pub fn rewrite_tuple<'a, I>(context: &RewriteContext,
// 3 = "(" + ",)"
let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
return items.next()
.unwrap()
.rewrite(context, nested_shape)
.map(|s| if context.config.spaces_within_parens {
format!("( {}, )", s)
} else {
format!("({},)", s)
});
.unwrap()
.rewrite(context, nested_shape)
.map(|s| if context.config.spaces_within_parens {
format!("( {}, )", s)
} else {
format!("({},)", s)
});
}
let list_lo = context.codemap.span_after(span, "(");
@ -1946,10 +1946,10 @@ pub fn rewrite_assign_rhs<S: Into<String>>(context: &RewriteContext,
let mut result = lhs.into();
let last_line_width = last_line_width(&result) -
if result.contains('\n') {
shape.indent.width()
} else {
0
};
shape.indent.width()
} else {
0
};
// 1 = space between operator and rhs.
let max_width = try_opt!(shape.width.checked_sub(last_line_width + 1));
let rhs = ex.rewrite(context,
@ -1972,7 +1972,7 @@ pub fn rewrite_assign_rhs<S: Into<String>>(context: &RewriteContext,
// if that works better.
let new_offset = shape.indent.block_indent(context.config);
let max_width = try_opt!((shape.width + shape.indent.width())
.checked_sub(new_offset.width()));
.checked_sub(new_offset.width()));
let new_rhs = ex.rewrite(context, Shape::legacy(max_width, new_offset));
// FIXME: DRY!

View File

@ -120,8 +120,9 @@ impl FileLines {
Some(ref map) => map,
};
match canonicalize_path_string(range.file_name())
.and_then(|canonical| map.get_vec(&canonical).ok_or(())) {
match canonicalize_path_string(range.file_name()).and_then(|canonical| {
map.get_vec(&canonical).ok_or(())
}) {
Ok(ranges) => ranges.iter().any(|r| r.contains(Range::from(range))),
Err(_) => false,
}
@ -182,8 +183,9 @@ impl JsonSpan {
// To allow `collect()`ing into a `MultiMap`.
fn into_tuple(self) -> Result<(String, Range), String> {
let (lo, hi) = self.range;
let canonical = try!(canonicalize_path_string(&self.file)
.map_err(|_| format!("Can't canonicalize {}", &self.file)));
let canonical = try!(canonicalize_path_string(&self.file).map_err(|_| {
format!("Can't canonicalize {}", &self.file)
}));
Ok((canonical, Range::new(lo, hi)))
}
}

View File

@ -142,9 +142,9 @@ impl Rewrite for ast::ViewPath {
let path_str = if path.segments.last().unwrap().identifier.to_string() == "self" &&
path.segments.len() > 1 {
let path = &ast::Path {
span: path.span.clone(),
segments: path.segments[..path.segments.len() - 1].to_owned(),
};
span: path.span.clone(),
segments: path.segments[..path.segments.len() - 1].to_owned(),
};
try_opt!(rewrite_path(context,
PathContext::Import,
None,
@ -159,10 +159,10 @@ impl Rewrite for ast::ViewPath {
};
Some(if path.segments.last().unwrap().identifier == ident {
path_str
} else {
format!("{} as {}", path_str, ident_str)
})
path_str
} else {
format!("{} as {}", path_str, ident_str)
})
}
}
}
@ -348,10 +348,10 @@ pub fn rewrite_use_list(shape: Shape,
let list_str = try_opt!(write_list(&items[first_index..], &fmt));
Some(if path_str.is_empty() {
format!("{{{}}}", list_str)
} else {
format!("{}::{{{}}}", path_str, list_str)
})
format!("{{{}}}", list_str)
} else {
format!("{}::{{{}}}", path_str, list_str)
})
}
// Returns true when self item was found.

View File

@ -128,16 +128,16 @@ impl BadIssueSeeker {
todo_idx += 1;
if todo_idx == TO_DO_CHARS.len() {
return Seeking::Number {
issue: Issue {
issue_type: IssueType::Todo,
missing_number: if let ReportTactic::Unnumbered = self.report_todo {
true
} else {
false
},
},
part: NumberPart::OpenParen,
};
issue: Issue {
issue_type: IssueType::Todo,
missing_number: if let ReportTactic::Unnumbered = self.report_todo {
true
} else {
false
},
},
part: NumberPart::OpenParen,
};
}
fixme_idx = 0;
} else if self.report_fixme.is_enabled() && c == FIX_ME_CHARS[fixme_idx] {
@ -146,16 +146,17 @@ impl BadIssueSeeker {
fixme_idx += 1;
if fixme_idx == FIX_ME_CHARS.len() {
return Seeking::Number {
issue: Issue {
issue_type: IssueType::Fixme,
missing_number: if let ReportTactic::Unnumbered = self.report_fixme {
true
} else {
false
},
},
part: NumberPart::OpenParen,
};
issue: Issue {
issue_type: IssueType::Fixme,
missing_number: if let ReportTactic::Unnumbered =
self.report_fixme {
true
} else {
false
},
},
part: NumberPart::OpenParen,
};
}
todo_idx = 0;
} else {
@ -178,10 +179,10 @@ impl BadIssueSeeker {
return IssueClassification::Bad(issue);
} else if c == ')' {
return if let NumberPart::CloseParen = part {
IssueClassification::Good
} else {
IssueClassification::Bad(issue)
};
IssueClassification::Good
} else {
IssueClassification::Bad(issue)
};
}
match part {
@ -268,9 +269,9 @@ fn find_issue() {
fn issue_type() {
let mut seeker = BadIssueSeeker::new(ReportTactic::Always, ReportTactic::Never);
let expected = Some(Issue {
issue_type: IssueType::Todo,
missing_number: false,
});
issue_type: IssueType::Todo,
missing_number: false,
});
assert_eq!(expected,
"TODO(#100): more awesomeness"
@ -281,9 +282,9 @@ fn issue_type() {
let mut seeker = BadIssueSeeker::new(ReportTactic::Never, ReportTactic::Unnumbered);
let expected = Some(Issue {
issue_type: IssueType::Fixme,
missing_number: true,
});
issue_type: IssueType::Fixme,
missing_number: true,
});
assert_eq!(expected,
"Test. FIXME: bad, bad, not good"

View File

@ -41,7 +41,8 @@ impl Rewrite for ast::Local {
let pattern_width = try_opt!(shape.width.checked_sub(pattern_offset.width() + 1));
let pat_str = try_opt!(self.pat
.rewrite(&context, Shape::legacy(pattern_width, pattern_offset)));
.rewrite(&context,
Shape::legacy(pattern_width, pattern_offset)));
result.push_str(&pat_str);
// String that is placed within the assignment pattern and expression.
@ -376,7 +377,7 @@ impl<'a> FmtVisitor<'a> {
self.block_indent,
self.block_indent.block_indent(self.config),
mk_sp(span.lo, body_start))
.unwrap();
.unwrap();
self.buffer.push_str(&generics_str);
self.last_pos = body_start;
@ -455,9 +456,11 @@ impl<'a> FmtVisitor<'a> {
let indent = self.block_indent;
let mut result = try_opt!(field.node
.attrs
.rewrite(&self.get_context(),
Shape::legacy(self.config.max_width - indent.width(), indent)));
.attrs
.rewrite(&self.get_context(),
Shape::legacy(self.config.max_width -
indent.width(),
indent)));
if !result.is_empty() {
result.push('\n');
result.push_str(&indent.to_string(self.config));
@ -782,8 +785,8 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent)
};
let where_budget = try_opt!(context.config
.max_width
.checked_sub(last_line_width(&result)));
.max_width
.checked_sub(last_line_width(&result)));
let where_clause_str = try_opt!(rewrite_where_clause(context,
&generics.where_clause,
context.config,
@ -937,7 +940,7 @@ fn format_struct_struct(context: &RewriteContext,
|field| field.rewrite(context, Shape::legacy(item_budget, item_indent)),
context.codemap.span_after(span, "{"),
span.hi)
.collect::<Vec<_>>();
.collect::<Vec<_>>();
// 1 = ,
let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
@ -998,8 +1001,8 @@ fn format_tuple_struct(context: &RewriteContext,
result.push_str(&generics_str);
let where_budget = try_opt!(context.config
.max_width
.checked_sub(last_line_width(&result)));
.max_width
.checked_sub(last_line_width(&result)));
try_opt!(rewrite_where_clause(context,
&generics.where_clause,
context.config,
@ -1058,7 +1061,7 @@ fn format_tuple_struct(context: &RewriteContext,
// 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))
.to_string(context.config));
.to_string(context.config));
}
result.push_str(&where_clause_str);
@ -1091,8 +1094,8 @@ pub fn rewrite_type_alias(context: &RewriteContext,
result.push_str(&generics_str);
let where_budget = try_opt!(context.config
.max_width
.checked_sub(last_line_width(&result)));
.max_width
.checked_sub(last_line_width(&result)));
let where_clause_str = try_opt!(rewrite_where_clause(context,
&generics.where_clause,
context.config,
@ -1115,19 +1118,19 @@ pub fn rewrite_type_alias(context: &RewriteContext,
let type_indent = indent + line_width;
// Try to fit the type on the same line
let ty_str = try_opt!(ty.rewrite(context, Shape::legacy(budget, type_indent))
.or_else(|| {
// The line was too short, try to put the type on the next line
.or_else(|| {
// The line was too short, try to put the type on the next line
// Remove the space after '='
result.pop();
let type_indent = indent.block_indent(context.config);
result.push('\n');
result.push_str(&type_indent.to_string(context.config));
let budget = try_opt!(context.config
.max_width
.checked_sub(type_indent.width() + ";".len()));
ty.rewrite(context, Shape::legacy(budget, type_indent))
}));
// Remove the space after '='
result.pop();
let type_indent = indent.block_indent(context.config);
result.push('\n');
result.push_str(&type_indent.to_string(context.config));
let budget = try_opt!(context.config
.max_width
.checked_sub(type_indent.width() + ";".len()));
ty.rewrite(context, Shape::legacy(budget, type_indent))
}));
result.push_str(&ty_str);
result.push_str(";");
Some(result)
@ -1156,9 +1159,10 @@ impl Rewrite for ast::StructField {
let name = self.ident;
let vis = format_visibility(&self.vis);
let mut attr_str = try_opt!(self.attrs
.rewrite(context,
Shape::legacy(context.config.max_width - shape.indent.width(),
shape.indent)));
.rewrite(context,
Shape::legacy(context.config.max_width -
shape.indent.width(),
shape.indent)));
if !attr_str.is_empty() {
attr_str.push('\n');
attr_str.push_str(&shape.indent.to_string(context.config));
@ -1205,8 +1209,7 @@ 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())));
@ -1219,7 +1222,7 @@ pub fn rewrite_static(prefix: &str,
lhs,
expr,
Shape::legacy(remaining_width, offset.block_only()))
.map(|s| s + ";")
.map(|s| s + ";")
} else {
let lhs = format!("{}{};", prefix, ty_str);
Some(lhs)
@ -1237,11 +1240,11 @@ pub fn rewrite_associated_type(ident: ast::Ident,
let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
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(" + ".to_string()))
.collect::<Option<String>>());
.map(|ty_bound| {
ty_bound.rewrite(context, Shape::legacy(context.config.max_width, indent))
})
.intersperse(Some(" + ".to_string()))
.collect::<Option<String>>());
if bounds.len() > 0 {
format!(": {}", bound_str)
} else {
@ -1281,7 +1284,8 @@ impl Rewrite for ast::Arg {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
if is_named_arg(self) {
let mut result = try_opt!(self.pat
.rewrite(context, Shape::legacy(shape.width, shape.indent)));
.rewrite(context,
Shape::legacy(shape.width, shape.indent)));
if self.ty.node != ast::TyKind::Infer {
if context.config.space_before_type_annotation {
@ -1314,7 +1318,8 @@ fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
let mut_str = format_mutability(m);
match lt {
Some(ref l) => {
let lifetime_str = try_opt!(l.rewrite(context,
let lifetime_str =
try_opt!(l.rewrite(context,
Shape::legacy(usize::max_value(), Indent::empty())));
Some(format!("&{} {}self", lifetime_str, mut_str))
}
@ -1325,8 +1330,8 @@ fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
let mutability = explicit_self_mutability(&args[0]);
let type_str =
try_opt!(ty.rewrite(context, Shape::legacy(usize::max_value(), Indent::empty())));
let type_str = try_opt!(ty.rewrite(context,
Shape::legacy(usize::max_value(), Indent::empty())));
Some(format!("{}self: {}", format_mutability(mutability), type_str))
}
@ -1458,8 +1463,10 @@ fn rewrite_fn_base(context: &RewriteContext,
// Note that if the width and indent really matter, we'll re-layout the
// return type later anyway.
let ret_str = try_opt!(fd.output
.rewrite(&context,
Shape::legacy(context.config.max_width - indent.width(), indent)));
.rewrite(&context,
Shape::legacy(context.config.max_width -
indent.width(),
indent)));
let multi_line_ret_str = ret_str.contains('\n');
let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
@ -1662,18 +1669,21 @@ fn rewrite_args(context: &RewriteContext,
variadic: bool)
-> Option<String> {
let mut arg_item_strs = try_opt!(args.iter()
.map(|arg| arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent)))
.collect::<Option<Vec<_>>>());
.map(|arg| {
arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
})
.collect::<Option<Vec<_>>>());
// Account for sugary self.
// FIXME: the comment for the self argument is dropped. This is blocked
// on rust issue #27522.
let min_args =
explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
.map_or(1, |self_str| {
arg_item_strs[0] = self_str;
2
});
let min_args = explicit_self.and_then(|explicit_self| {
rewrite_explicit_self(explicit_self, args, context)
})
.map_or(1, |self_str| {
arg_item_strs[0] = self_str;
2
});
// Comments between args.
let mut arg_items = Vec::new();
@ -1885,10 +1895,10 @@ fn rewrite_generics(context: &RewriteContext,
try_opt!(format_item_list(items, Shape::legacy(h_budget, offset), context.config));
Some(if context.config.spaces_within_angle_brackets {
format!("< {} >", list_str)
} else {
format!("<{}>", list_str)
})
format!("< {} >", list_str)
} else {
format!("<{}>", list_str)
})
}
fn rewrite_trait_bounds(context: &RewriteContext,
@ -1902,9 +1912,9 @@ fn rewrite_trait_bounds(context: &RewriteContext,
}
let bound_str = try_opt!(bounds.iter()
.map(|ty_bound| ty_bound.rewrite(&context, shape))
.intersperse(Some(" + ".to_string()))
.collect::<Option<String>>());
.map(|ty_bound| ty_bound.rewrite(&context, shape))
.intersperse(Some(" + ".to_string()))
.collect::<Option<String>>());
let mut result = String::new();
result.push_str(": ");

View File

@ -256,7 +256,7 @@ impl Shape {
indent: indent,
offset: offset,
}
}
}
pub fn visual_indent(&self, extra_width: usize) -> Shape {
let alignment = self.offset + extra_width;
@ -316,18 +316,18 @@ impl Shape {
pub fn sub_width(&self, width: usize) -> Option<Shape> {
Some(Shape {
width: try_opt!(self.width.checked_sub(width)),
indent: self.indent,
offset: self.offset,
})
width: try_opt!(self.width.checked_sub(width)),
indent: self.indent,
offset: self.offset,
})
}
pub fn shrink_left(&self, width: usize) -> Option<Shape> {
Some(Shape {
width: try_opt!(self.width.checked_sub(width)),
indent: self.indent + width,
offset: self.offset + width,
})
width: try_opt!(self.width.checked_sub(width)),
indent: self.indent + width,
offset: self.offset + width,
})
}
pub fn used_width(&self) -> usize {
@ -477,9 +477,9 @@ fn format_lines(text: &mut StringBuffer, name: &str, config: &Config, report: &m
// Add warnings for bad todos/ fixmes
if let Some(issue) = issue_seeker.inspect(c) {
errors.push(FormattingError {
line: cur_line,
kind: ErrorKind::BadIssue(issue),
});
line: cur_line,
kind: ErrorKind::BadIssue(issue),
});
}
if c == '\n' {
@ -491,9 +491,9 @@ fn format_lines(text: &mut StringBuffer, name: &str, config: &Config, report: &m
// Check for any line width errors we couldn't correct.
if line_len > config.max_width {
errors.push(FormattingError {
line: cur_line,
kind: ErrorKind::LineOverflow(line_len, config.max_width),
});
line: cur_line,
kind: ErrorKind::LineOverflow(line_len, config.max_width),
});
}
line_len = 0;
cur_line += 1;
@ -520,9 +520,9 @@ fn format_lines(text: &mut StringBuffer, name: &str, config: &Config, report: &m
for &(l, _, _) in &trims {
errors.push(FormattingError {
line: l,
kind: ErrorKind::TrailingWhitespace,
});
line: l,
kind: ErrorKind::TrailingWhitespace,
});
}
report.file_error_map.insert(name.to_owned(), errors);

View File

@ -260,8 +260,7 @@ pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
// Post-comments
if tactic != DefinitiveListTactic::Vertical && item.post_comment.is_some() {
let comment = item.post_comment.as_ref().unwrap();
let formatted_comment =
try_opt!(rewrite_comment(comment,
let formatted_comment = try_opt!(rewrite_comment(comment,
true,
Shape::legacy(formatting.shape.width, Indent::empty()),
formatting.config));

View File

@ -92,13 +92,13 @@ pub fn rewrite_macro(mac: &ast::Mac,
if mac.node.tts.is_empty() && !contains_comment(&context.snippet(mac.span)) {
return match style {
MacroStyle::Parens if position == MacroPosition::Item => {
Some(format!("{}();", macro_name))
}
MacroStyle::Parens => Some(format!("{}()", macro_name)),
MacroStyle::Brackets => Some(format!("{}[]", macro_name)),
MacroStyle::Braces => Some(format!("{}{{}}", macro_name)),
};
MacroStyle::Parens if position == MacroPosition::Item => {
Some(format!("{}();", macro_name))
}
MacroStyle::Parens => Some(format!("{}()", macro_name)),
MacroStyle::Brackets => Some(format!("{}[]", macro_name)),
MacroStyle::Braces => Some(format!("{}{{}}", macro_name)),
};
}
let mut parser = tts_to_parser(context.parse_session, mac.node.tts.clone());
@ -181,11 +181,11 @@ pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::
let mut parser = tts_to_parser(context.parse_session, mac.node.tts.clone());
Some(ast::Expr {
id: ast::NodeId::new(0), // dummy value
node: ast::ExprKind::Try(try_opt!(parser.parse_expr().ok())),
span: mac.span, // incorrect span, but shouldn't matter too much
attrs: ThinVec::new(),
})
id: ast::NodeId::new(0), // dummy value
node: ast::ExprKind::Try(try_opt!(parser.parse_expr().ok())),
span: mac.span, // incorrect span, but shouldn't matter too much
attrs: ThinVec::new(),
})
} else {
None
}

View File

@ -147,7 +147,7 @@ impl<'a> FmtVisitor<'a> {
Shape::legacy(comment_width,
self.block_indent),
self.config)
.unwrap());
.unwrap());
last_wspace = None;
line_start = offset + subslice.len();
@ -155,8 +155,8 @@ impl<'a> FmtVisitor<'a> {
if let Some('/') = subslice.chars().skip(1).next() {
// check that there are no contained block comments
if !subslice.split('\n')
.map(|s| s.trim_left())
.any(|s| s.len() > 2 && &s[0..2] == "/*") {
.map(|s| s.trim_left())
.any(|s| s.len() > 2 && &s[0..2] == "/*") {
// Add a newline after line comments
self.buffer.push_str("\n");
}

View File

@ -37,7 +37,9 @@ impl Rewrite for Pat {
Some(ref p) => {
// 3 - ` @ `.
let width = try_opt!(shape.width
.checked_sub(prefix.len() + mut_infix.len() + id_str.len() + 3));
.checked_sub(prefix.len() + mut_infix.len() +
id_str.len() +
3));
format!(" @ {}",
try_opt!(p.rewrite(context, Shape::legacy(width, shape.indent))))
}
@ -81,8 +83,9 @@ impl Rewrite for Pat {
PatKind::Slice(ref prefix, ref slice_pat, ref suffix) => {
// Rewrite all the sub-patterns.
let prefix = prefix.iter().map(|p| p.rewrite(context, shape));
let slice_pat = slice_pat.as_ref()
.map(|p| Some(format!("{}..", try_opt!(p.rewrite(context, shape)))));
let slice_pat =
slice_pat.as_ref()
.map(|p| Some(format!("{}..", try_opt!(p.rewrite(context, shape)))));
let suffix = suffix.iter().map(|p| p.rewrite(context, shape));
// Munge them together.
@ -223,15 +226,14 @@ fn rewrite_tuple_pat(pats: &[ptr::P<ast::Pat>],
let nested_shape = try_opt!(shape.sub_width(path_len + if add_comma { 3 } else { 2 }));
// 1 = "(".len()
let nested_shape = nested_shape.visual_indent(path_len + 1);
let mut items: Vec<_> =
itemize_list(context.codemap,
pat_vec.iter(),
if add_comma { ",)" } else { ")" },
|item| item.span().lo,
|item| item.span().hi,
|item| item.rewrite(context, nested_shape),
context.codemap.span_after(span, "("),
span.hi - BytePos(1))
let mut items: Vec<_> = itemize_list(context.codemap,
pat_vec.iter(),
if add_comma { ",)" } else { ")" },
|item| item.span().lo,
|item| item.span().hi,
|item| item.rewrite(context, nested_shape),
context.codemap.span_after(span, "("),
span.hi - BytePos(1))
.collect();
// Condense wildcard string suffix into a single ..
@ -244,26 +246,24 @@ fn rewrite_tuple_pat(pats: &[ptr::P<ast::Pat>],
let da_iter = items.into_iter().take(new_item_count);
try_opt!(format_item_list(da_iter, nested_shape, context.config))
} else {
try_opt!(format_item_list(items.into_iter(),
nested_shape,
context.config))
try_opt!(format_item_list(items.into_iter(), nested_shape, context.config))
};
match path_str {
Some(path_str) => {
Some(if context.config.spaces_within_parens {
format!("{}( {} )", path_str, list)
} else {
format!("{}({})", path_str, list)
})
format!("{}( {} )", path_str, list)
} else {
format!("{}({})", path_str, list)
})
}
None => {
let comma = if add_comma { "," } else { "" };
Some(if context.config.spaces_within_parens {
format!("( {}{} )", list, comma)
} else {
format!("({}{})", list, comma)
})
format!("( {}{} )", list, comma)
} else {
format!("({}{})", list, comma)
})
}
}
}
@ -273,9 +273,10 @@ fn count_wildcard_suffix_len(items: &[ListItem]) -> usize {
let mut suffix_len = 0;
for item in items.iter().rev().take_while(|i| match i.item {
Some(ref internal_string) if internal_string == "_" => true,
_ => false,
}) {
Some(ref internal_string) if internal_string ==
"_" => true,
_ => false,
}) {
suffix_len += 1;
if item.pre_comment.is_some() || item.post_comment.is_some() {

View File

@ -43,8 +43,8 @@ pub fn rewrite_string<'a>(orig: &str, fmt: &StringFormat<'a>) -> Option<String>
// `cur_start` is the position in `orig` of the start of the current line.
let mut cur_start = 0;
let mut result = String::with_capacity(stripped_str.len()
.checked_next_power_of_two()
.unwrap_or(usize::max_value()));
.checked_next_power_of_two()
.unwrap_or(usize::max_value()));
result.push_str(fmt.opener);
let ender_length = fmt.line_end.len();

View File

@ -162,8 +162,10 @@ impl<'a> Rewrite for SegmentParam<'a> {
SegmentParam::Binding(binding) => {
let mut result = format!("{} = ", binding.ident);
let budget = try_opt!(shape.width.checked_sub(result.len()));
let rewrite = try_opt!(binding.ty
.rewrite(context, Shape::legacy(budget, shape.indent + result.len())));
let rewrite =
try_opt!(binding.ty
.rewrite(context,
Shape::legacy(budget, shape.indent + result.len())));
result.push_str(&rewrite);
Some(result)
}
@ -215,7 +217,8 @@ fn rewrite_segment(path_context: PathContext,
let extra_offset = 1 + separator.len();
// 1 for >
// TODO bad visual indent
let list_shape = try_opt!(try_opt!(shape.shrink_left(extra_offset)).sub_width(1)).visual_indent(0);
let list_shape = try_opt!(try_opt!(shape.shrink_left(extra_offset)).sub_width(1))
.visual_indent(0);
let items = itemize_list(context.codemap,
param_list.into_iter(),
@ -331,10 +334,10 @@ fn format_function_type<'a, I>(inputs: I,
};
Some(if context.config.spaces_within_parens {
format!("( {} ){}{}", list_str, infix, output)
} else {
format!("({}){}{}", list_str, infix, output)
})
format!("( {} ){}{}", list_str, infix, output)
} else {
format!("({}){}{}", list_str, infix, output)
})
}
fn type_bound_colon(context: &RewriteContext) -> &'static str {
@ -411,7 +414,8 @@ impl Rewrite for ast::WherePredicate {
let used_width = 3 + lhs_ty_str.len();
let budget = try_opt!(shape.width.checked_sub(used_width));
let rhs_ty_str = try_opt!(rhs_ty.rewrite(context,
Shape::legacy(budget, shape.indent + used_width)));
Shape::legacy(budget,
shape.indent + used_width)));
format!("{} = {}", lhs_ty_str, rhs_ty_str)
}
};
@ -439,8 +443,8 @@ fn rewrite_bounded_lifetime<'b, I>(lt: &ast::Lifetime,
Some(result)
} else {
let appendix: Vec<_> = try_opt!(bounds.into_iter()
.map(|b| b.rewrite(context, shape))
.collect());
.map(|b| b.rewrite(context, shape))
.collect());
let colon = type_bound_colon(context);
let result = format!("{}{}{}", result, colon, appendix.join(" + "));
wrap_str(result, context.config.max_width, shape)
@ -479,8 +483,8 @@ impl Rewrite for ast::TyParamBounds {
TypeDensity::Wide => " + ",
};
let strs: Vec<_> = try_opt!(self.iter()
.map(|b| b.rewrite(context, shape))
.collect());
.map(|b| b.rewrite(context, shape))
.collect());
wrap_str(strs.join(joiner), context.config.max_width, shape)
}
}
@ -498,11 +502,12 @@ impl Rewrite for ast::TyParam {
result.push_str(" ");
}
let bounds: String = try_opt!(self.bounds
.iter()
.map(|ty_bound| ty_bound.rewrite(context, shape))
.intersperse(Some(" + ".to_string()))
.collect());
let bounds: String =
try_opt!(self.bounds
.iter()
.map(|ty_bound| ty_bound.rewrite(context, shape))
.intersperse(Some(" + ".to_string()))
.collect());
result.push_str(&bounds);
}
@ -514,8 +519,8 @@ impl Rewrite for ast::TyParam {
};
result.push_str(eq_str);
let budget = try_opt!(shape.width.checked_sub(result.len()));
let rewrite =
try_opt!(def.rewrite(context, Shape::legacy(budget, shape.indent + result.len())));
let rewrite = try_opt!(def.rewrite(context,
Shape::legacy(budget, shape.indent + result.len())));
result.push_str(&rewrite);
}
@ -527,23 +532,24 @@ impl Rewrite for ast::PolyTraitRef {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
if !self.bound_lifetimes.is_empty() {
let lifetime_str: String = try_opt!(self.bound_lifetimes
.iter()
.map(|lt| lt.rewrite(context, shape))
.intersperse(Some(", ".to_string()))
.collect());
.iter()
.map(|lt| lt.rewrite(context, shape))
.intersperse(Some(", ".to_string()))
.collect());
// 6 is "for<> ".len()
let extra_offset = lifetime_str.len() + 6;
let max_path_width = try_opt!(shape.width.checked_sub(extra_offset));
let path_str = try_opt!(self.trait_ref
.rewrite(context,
Shape::legacy(max_path_width, shape.indent + extra_offset)));
.rewrite(context,
Shape::legacy(max_path_width,
shape.indent + extra_offset)));
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)
})
format!("for< {} > {}", lifetime_str, path_str)
} else {
format!("for<{}> {}", lifetime_str, path_str)
})
} else {
self.trait_ref.rewrite(context, shape)
}
@ -572,31 +578,32 @@ impl Rewrite for ast::Ty {
let mut_str = format_mutability(mt.mutbl);
let mut_len = mut_str.len();
Some(match *lifetime {
Some(ref lifetime) => {
let lt_budget = try_opt!(shape.width.checked_sub(2 + mut_len));
let lt_str = try_opt!(lifetime.rewrite(context,
Shape::legacy(lt_budget,
shape.indent + 2 +
mut_len)));
let lt_len = lt_str.len();
let budget = try_opt!(shape.width.checked_sub(2 + mut_len + lt_len));
format!("&{} {}{}",
lt_str,
mut_str,
try_opt!(mt.ty
.rewrite(context,
Shape::legacy(budget,
shape.indent + 2 + mut_len + lt_len))))
}
None => {
let budget = try_opt!(shape.width.checked_sub(1 + mut_len));
format!("&{}{}",
mut_str,
try_opt!(mt.ty.rewrite(context,
Shape::legacy(budget,
shape.indent + 1 + mut_len))))
}
})
Some(ref lifetime) => {
let lt_budget = try_opt!(shape.width.checked_sub(2 + mut_len));
let lt_str = try_opt!(lifetime.rewrite(context,
Shape::legacy(lt_budget,
shape.indent + 2 +
mut_len)));
let lt_len = lt_str.len();
let budget = try_opt!(shape.width.checked_sub(2 + mut_len + lt_len));
format!("&{} {}{}",
lt_str,
mut_str,
try_opt!(mt.ty
.rewrite(context,
Shape::legacy(budget,
shape.indent + 2 + mut_len +
lt_len))))
}
None => {
let budget = try_opt!(shape.width.checked_sub(1 + mut_len));
format!("&{}{}",
mut_str,
try_opt!(mt.ty.rewrite(context,
Shape::legacy(budget,
shape.indent + 1 + mut_len))))
}
})
}
// FIXME: we drop any comments here, even though it's a silly place to put
// comments.
@ -604,10 +611,10 @@ impl Rewrite for ast::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 {
format!("( {} )", ty_str)
} else {
format!("({})", ty_str)
})
format!("( {} )", ty_str)
} else {
format!("({})", ty_str)
})
}
ast::TyKind::Slice(ref ty) => {
let budget = if context.config.spaces_within_square_brackets {
@ -617,10 +624,10 @@ impl Rewrite for ast::Ty {
};
ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
.map(|ty_str| if context.config.spaces_within_square_brackets {
format!("[ {} ]", ty_str)
} else {
format!("[{}]", ty_str)
})
format!("[ {} ]", ty_str)
} else {
format!("[{}]", ty_str)
})
}
ast::TyKind::Tup(ref items) => {
rewrite_tuple(context, items.iter().map(|x| &**x), self.span, shape)
@ -666,13 +673,13 @@ fn rewrite_bare_fn(bare_fn: &ast::BareFnTy,
// This doesn't work out so nicely for mutliline situation with lots of
// rightward drift. If that is a problem, we could use the list stuff.
result.push_str(&try_opt!(bare_fn.lifetimes
.iter()
.map(|l| {
l.rewrite(context,
Shape::legacy(try_opt!(shape.width.checked_sub(6)), shape.indent + 4))
})
.intersperse(Some(", ".to_string()))
.collect::<Option<String>>()));
.iter()
.map(|l| {
l.rewrite(context,
Shape::legacy(try_opt!(shape.width.checked_sub(6)), shape.indent + 4))
})
.intersperse(Some(", ".to_string()))
.collect::<Option<String>>()));
result.push_str("> ");
}

View File

@ -264,10 +264,10 @@ impl<'a> FmtVisitor<'a> {
item.span,
indent,
None)
.map(|s| match *def {
ast::VariantData::Tuple(..) => s + ";",
_ => s,
})
.map(|s| match *def {
ast::VariantData::Tuple(..) => s + ";",
_ => s,
})
};
self.push_rewrite(item.span, rewrite);
}