1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use std::cmp::{Ordering, min};
12 use std::iter::ExactSizeIterator;
15 use {Indent, Shape, Spanned};
16 use codemap::SpanUtils;
17 use rewrite::{Rewrite, RewriteContext};
18 use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic,
19 DefinitiveListTactic, definitive_tactic, ListItem, struct_lit_shape,
20 struct_lit_tactic, shape_for_tactic, struct_lit_formatting};
21 use string::{StringFormat, rewrite_string};
22 use utils::{extra_offset, last_line_width, wrap_str, binary_search, first_line_width,
23 semicolon_for_stmt, trimmed_last_line_width, left_most_sub_expr, stmt_expr,
24 colon_spaces, contains_skip, mk_sp, last_line_extendable, paren_overhead};
25 use visitor::FmtVisitor;
26 use config::{Config, IndentStyle, MultilineStyle, ControlBraceStyle, Style};
27 use comment::{FindUncommented, rewrite_comment, contains_comment, recover_comment_removed};
28 use types::{rewrite_path, PathContext, can_be_overflowed_type};
29 use items::{span_lo_for_arg, span_hi_for_arg};
30 use chains::rewrite_chain;
31 use macros::{rewrite_macro, MacroPosition};
32 use patterns::{TuplePatField, can_be_overflowed_pat};
33 use vertical::rewrite_with_alignment;
35 use syntax::{ast, ptr};
36 use syntax::codemap::{CodeMap, Span, BytePos};
37 use syntax::parse::classify;
39 impl Rewrite for ast::Expr {
40 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
41 format_expr(self, ExprType::SubExpression, context, shape)
51 fn combine_attr_and_expr(
52 context: &RewriteContext,
57 let separator = if attr_str.is_empty() {
60 if expr_str.contains('\n') || attr_str.contains('\n') ||
61 attr_str.len() + expr_str.len() > shape.width
63 format!("\n{}", shape.indent.to_string(context.config))
68 format!("{}{}{}", attr_str, separator, expr_str)
74 context: &RewriteContext,
77 let attr_rw = (&*expr.attrs).rewrite(context, shape);
78 if contains_skip(&*expr.attrs) {
79 if let Some(attr_str) = attr_rw {
80 return Some(combine_attr_and_expr(
84 &context.snippet(expr.span),
87 return Some(context.snippet(expr.span));
90 let expr_rw = match expr.node {
91 ast::ExprKind::Array(ref expr_vec) => {
93 expr_vec.iter().map(|e| &**e),
94 mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi),
100 ast::ExprKind::Lit(ref l) => {
102 ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
103 rewrite_string_lit(context, l.span, shape)
107 context.snippet(expr.span),
108 context.config.max_width(),
114 ast::ExprKind::Call(ref callee, ref args) => {
115 let inner_span = mk_sp(callee.span.hi, expr.span.hi);
116 rewrite_call_with_binary_search(
119 &args.iter().map(|x| &**x).collect::<Vec<_>>()[..],
124 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
125 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
126 // FIXME: format comments between operands and operator
131 &format!(" {} ", context.snippet(op.span)),
137 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
138 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
143 base.as_ref().map(|e| &**e),
148 ast::ExprKind::Tup(ref items) => {
151 &items.iter().map(|x| &**x).collect::<Vec<_>>()[..],
156 ast::ExprKind::If(..) |
157 ast::ExprKind::IfLet(..) |
158 ast::ExprKind::ForLoop(..) |
159 ast::ExprKind::Loop(..) |
160 ast::ExprKind::While(..) |
161 ast::ExprKind::WhileLet(..) => {
162 to_control_flow(expr, expr_type)
163 .and_then(|control_flow| control_flow.rewrite(context, shape))
165 ast::ExprKind::Block(ref block) => {
167 ExprType::Statement => {
168 if is_unsafe_block(block) {
169 block.rewrite(context, shape)
171 // Rewrite block without trying to put it in a single line.
172 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
175 let prefix = try_opt!(block_prefix(context, block, shape));
176 rewrite_block_with_visitor(context, &prefix, block, shape)
179 ExprType::SubExpression => block.rewrite(context, shape),
182 ast::ExprKind::Match(ref cond, ref arms) => {
183 rewrite_match(context, cond, arms, shape, expr.span)
185 ast::ExprKind::Path(ref qself, ref path) => {
186 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
188 ast::ExprKind::Assign(ref lhs, ref rhs) => {
189 rewrite_assignment(context, lhs, rhs, None, shape)
191 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
192 rewrite_assignment(context, lhs, rhs, Some(op), shape)
194 ast::ExprKind::Continue(ref opt_ident) => {
195 let id_str = match *opt_ident {
196 Some(ident) => format!(" {}", ident.node),
197 None => String::new(),
200 format!("continue{}", id_str),
201 context.config.max_width(),
205 ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
206 let id_str = match *opt_ident {
207 Some(ident) => format!(" {}", ident.node),
208 None => String::new(),
211 if let Some(ref expr) = *opt_expr {
212 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
215 format!("break{}", id_str),
216 context.config.max_width(),
221 ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
222 rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
224 ast::ExprKind::Try(..) |
225 ast::ExprKind::Field(..) |
226 ast::ExprKind::TupField(..) |
227 ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
228 ast::ExprKind::Mac(ref mac) => {
229 // Failure to rewrite a marco should not imply failure to
230 // rewrite the expression.
231 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
233 context.snippet(expr.span),
234 context.config.max_width(),
239 ast::ExprKind::Ret(None) => {
240 wrap_str("return".to_owned(), context.config.max_width(), shape)
242 ast::ExprKind::Ret(Some(ref expr)) => {
243 rewrite_unary_prefix(context, "return ", &**expr, shape)
245 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
246 ast::ExprKind::AddrOf(mutability, ref expr) => {
247 rewrite_expr_addrof(context, mutability, expr, shape)
249 ast::ExprKind::Cast(ref expr, ref ty) => {
250 rewrite_pair(&**expr, &**ty, "", " as ", "", context, shape)
252 ast::ExprKind::Type(ref expr, ref ty) => {
253 rewrite_pair(&**expr, &**ty, "", ": ", "", context, shape)
255 ast::ExprKind::Index(ref expr, ref index) => {
256 rewrite_index(&**expr, &**index, context, shape)
258 ast::ExprKind::Repeat(ref expr, ref repeats) => {
259 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
264 rewrite_pair(&**expr, &**repeats, lbr, "; ", rbr, context, shape)
266 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
267 let delim = match limits {
268 ast::RangeLimits::HalfOpen => "..",
269 ast::RangeLimits::Closed => "...",
272 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
274 ast::ExprKind::Lit(ref lit) => {
276 ast::LitKind::FloatUnsuffixed(..) => {
277 context.snippet(lit.span).ends_with('.')
286 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
287 (Some(ref lhs), Some(ref rhs)) => {
288 let sp_delim = if context.config.spaces_around_ranges() {
289 format!(" {} ", delim)
290 } else if needs_space_before_range(context, lhs) {
291 format!(" {}", delim)
295 rewrite_pair(&**lhs, &**rhs, "", &sp_delim, "", context, shape)
297 (None, Some(ref rhs)) => {
298 let sp_delim = if context.config.spaces_around_ranges() {
299 format!("{} ", delim)
303 rewrite_unary_prefix(context, &sp_delim, &**rhs, shape)
305 (Some(ref lhs), None) => {
306 let sp_delim = if context.config.spaces_around_ranges() {
307 format!(" {}", delim)
311 rewrite_unary_suffix(context, &sp_delim, &**lhs, shape)
313 (None, None) => wrap_str(delim.into(), context.config.max_width(), shape),
316 // We do not format these expressions yet, but they should still
317 // satisfy our width restrictions.
318 ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => {
320 context.snippet(expr.span),
321 context.config.max_width(),
325 ast::ExprKind::Catch(ref block) => {
326 if let rewrite @ Some(_) =
327 rewrite_single_line_block(context, "do catch ", block, shape)
332 let budget = shape.width.checked_sub(9).unwrap_or(0);
336 try_opt!(block.rewrite(&context, Shape::legacy(budget, shape.indent)))
340 match (attr_rw, expr_rw) {
341 (Some(attr_str), Some(expr_str)) => {
342 recover_comment_removed(
343 combine_attr_and_expr(context, shape, &attr_str, &expr_str),
353 pub fn rewrite_pair<LHS, RHS>(
359 context: &RewriteContext,
366 // Get "full width" rhs and see if it fits on the current line. This
367 // usually works fairly well since it tends to place operands of
368 // operations with high precendence close together.
369 // Note that this is non-conservative, but its just to see if it's even
370 // worth trying to put everything on one line.
371 let rhs_shape = try_opt!(shape.sub_width(suffix.len()));
372 let rhs_result = rhs.rewrite(context, rhs_shape);
374 if let Some(rhs_result) = rhs_result {
375 // This is needed in case of line break not caused by a
376 // shortage of space, but by end-of-line comments, for example.
377 if !rhs_result.contains('\n') {
379 try_opt!(try_opt!(shape.offset_left(prefix.len())).sub_width(infix.len()));
380 let lhs_result = lhs.rewrite(context, lhs_shape);
381 if let Some(lhs_result) = lhs_result {
382 let mut result = format!("{}{}{}", prefix, lhs_result, infix);
384 let remaining_width = shape
386 .checked_sub(last_line_width(&result) + suffix.len())
389 if rhs_result.len() <= remaining_width {
390 result.push_str(&rhs_result);
391 result.push_str(suffix);
395 // Try rewriting the rhs into the remaining space.
396 let rhs_shape = shape.shrink_left(last_line_width(&result) + suffix.len());
397 if let Some(rhs_shape) = rhs_shape {
398 if let Some(rhs_result) = rhs.rewrite(context, rhs_shape) {
399 // FIXME this should always hold.
400 if rhs_result.len() <= remaining_width {
401 result.push_str(&rhs_result);
402 result.push_str(suffix);
411 // We have to use multiple lines.
413 // Re-evaluate the rhs because we have more space now:
414 let infix = infix.trim_right();
415 let rhs_shape = match context.config.control_style() {
417 try_opt!(shape.sub_width(suffix.len() + prefix.len())).visual_indent(prefix.len())
420 // Try to calculate the initial constraint on the right hand side.
421 let rhs_overhead = shape.rhs_overhead(context.config);
423 Shape::indented(shape.indent.block_indent(context.config), context.config)
424 .sub_width(rhs_overhead)
428 let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape));
429 let lhs_overhead = shape.used_width() + prefix.len() + infix.len();
430 let lhs_shape = Shape {
431 width: try_opt!(context.config.max_width().checked_sub(lhs_overhead)),
434 let lhs_result = try_opt!(lhs.rewrite(context, lhs_shape));
440 rhs_shape.indent.to_string(context.config),
446 pub fn rewrite_array<'a, I>(
449 context: &RewriteContext,
451 trailing_comma: bool,
454 I: Iterator<Item = &'a ast::Expr>,
456 let bracket_size = if context.config.spaces_within_square_brackets() {
462 let mut nested_shape = match context.config.array_layout() {
463 IndentStyle::Block => {
467 .block_indent(context.config.tab_spaces())
468 .with_max_width(context.config)
472 IndentStyle::Visual => {
475 .visual_indent(bracket_size)
476 .sub_width(bracket_size * 2)
481 let items = itemize_list(
487 |item| item.rewrite(context, nested_shape),
490 ).collect::<Vec<_>>();
492 if items.is_empty() {
493 if context.config.spaces_within_square_brackets() {
494 return Some("[ ]".to_string());
496 return Some("[]".to_string());
500 let has_long_item = items
502 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
504 let mut tactic = match context.config.array_layout() {
505 IndentStyle::Block => {
506 // FIXME wrong shape in one-line case
507 match shape.width.checked_sub(2 * bracket_size) {
510 ListTactic::LimitedHorizontalVertical(context.config.array_width());
511 definitive_tactic(&items, tactic, width)
513 None => DefinitiveListTactic::Vertical,
516 IndentStyle::Visual => {
517 if has_long_item || items.iter().any(ListItem::is_multiline) {
520 ListTactic::LimitedHorizontalVertical(context.config.array_width()),
524 DefinitiveListTactic::Mixed
528 if context.config.array_horizontal_layout_threshold() > 0 &&
529 items.len() > context.config.array_horizontal_layout_threshold()
531 tactic = DefinitiveListTactic::Mixed;
532 if context.config.array_layout() == IndentStyle::Block {
533 nested_shape = try_opt!(
535 .visual_indent(bracket_size)
536 .sub_width(bracket_size * 2)
541 let fmt = ListFormatting {
544 trailing_separator: if trailing_comma {
545 SeparatorTactic::Always
546 } else if context.inside_macro || context.config.array_layout() == IndentStyle::Visual {
547 SeparatorTactic::Never
549 SeparatorTactic::Vertical
552 ends_with_newline: false,
553 config: context.config,
555 let list_str = try_opt!(write_list(&items, &fmt));
557 let result = if context.config.array_layout() == IndentStyle::Visual ||
558 tactic != DefinitiveListTactic::Vertical
560 if context.config.spaces_within_square_brackets() && list_str.len() > 0 {
561 format!("[ {} ]", list_str)
563 format!("[{}]", list_str)
568 nested_shape.indent.to_string(context.config),
570 shape.block().indent.to_string(context.config)
577 // Return type is (prefix, extra_offset)
578 fn rewrite_closure_fn_decl(
579 capture: ast::CaptureBy,
580 fn_decl: &ast::FnDecl,
583 context: &RewriteContext,
585 ) -> Option<(String, usize)> {
586 let mover = if capture == ast::CaptureBy::Value {
591 // 4 = "|| {".len(), which is overconservative when the closure consists of
592 // a single expression.
593 let nested_shape = try_opt!(try_opt!(shape.shrink_left(mover.len())).sub_width(4));
596 let argument_offset = nested_shape.indent + 1;
597 let arg_shape = try_opt!(nested_shape.shrink_left(1)).visual_indent(0);
598 let ret_str = try_opt!(fn_decl.output.rewrite(context, arg_shape));
600 let arg_items = itemize_list(
602 fn_decl.inputs.iter(),
604 |arg| span_lo_for_arg(arg),
605 |arg| span_hi_for_arg(context, arg),
606 |arg| arg.rewrite(context, arg_shape),
607 context.codemap.span_after(span, "|"),
610 let item_vec = arg_items.collect::<Vec<_>>();
611 // 1 = space between arguments and return type.
612 let horizontal_budget = nested_shape
614 .checked_sub(ret_str.len() + 1)
616 let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
617 let arg_shape = match tactic {
618 DefinitiveListTactic::Horizontal => try_opt!(arg_shape.sub_width(ret_str.len() + 1)),
622 let fmt = ListFormatting {
625 trailing_separator: SeparatorTactic::Never,
627 ends_with_newline: false,
628 config: context.config,
630 let list_str = try_opt!(write_list(&item_vec, &fmt));
631 let mut prefix = format!("{}|{}|", mover, list_str);
632 // 1 = space between `|...|` and body.
633 let extra_offset = extra_offset(&prefix, shape) + 1;
635 if !ret_str.is_empty() {
636 if prefix.contains('\n') {
638 prefix.push_str(&argument_offset.to_string(context.config));
642 prefix.push_str(&ret_str);
645 Some((prefix, extra_offset))
648 // This functions is pretty messy because of the rules around closures and blocks:
649 // FIXME - the below is probably no longer true in full.
650 // * if there is a return type, then there must be braces,
651 // * given a closure with braces, whether that is parsed to give an inner block
652 // or not depends on if there is a return type and if there are statements
654 // * if the first expression in the body ends with a block (i.e., is a
655 // statement without needing a semi-colon), then adding or removing braces
656 // can change whether it is treated as an expression or statement.
658 capture: ast::CaptureBy,
659 fn_decl: &ast::FnDecl,
662 context: &RewriteContext,
664 ) -> Option<String> {
665 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
673 // 1 = space between `|...|` and body.
674 let body_shape = try_opt!(shape.offset_left(extra_offset));
676 if let ast::ExprKind::Block(ref block) = body.node {
677 // The body of the closure is an empty block.
678 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
679 return Some(format!("{} {{}}", prefix));
682 // Figure out if the block is necessary.
683 let needs_block = block.rules != ast::BlockCheckMode::Default ||
684 block.stmts.len() > 1 || context.inside_macro ||
685 block_contains_comment(block, context.codemap) ||
686 prefix.contains('\n');
688 let no_return_type = if let ast::FunctionRetTy::Default(_) = fn_decl.output {
693 if no_return_type && !needs_block {
694 // lock.stmts.len() == 1
695 if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
696 if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
703 // We need braces, but we might still prefer a one-liner.
704 let stmt = &block.stmts[0];
705 // 4 = braces and spaces.
706 if let Some(body_shape) = body_shape.sub_width(4) {
707 // Checks if rewrite succeeded and fits on a single line.
708 if let Some(rewrite) = and_one_line(stmt.rewrite(context, body_shape)) {
709 return Some(format!("{} {{ {} }}", prefix, rewrite));
714 // Either we require a block, or tried without and failed.
715 rewrite_closure_block(&block, &prefix, context, body_shape)
717 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
718 // The closure originally had a non-block expression, but we can't fit on
719 // one line, so we'll insert a block.
720 rewrite_closure_with_block(context, body_shape, &prefix, body)
725 // Rewrite closure with a single expression wrapping its body with block.
726 fn rewrite_closure_with_block(
727 context: &RewriteContext,
731 ) -> Option<String> {
732 let block = ast::Block {
735 id: ast::NodeId::new(0),
736 node: ast::StmtKind::Expr(ptr::P(body.clone())),
740 id: ast::NodeId::new(0),
741 rules: ast::BlockCheckMode::Default,
744 rewrite_closure_block(&block, prefix, context, shape)
747 // Rewrite closure with a single expression without wrapping its body with block.
748 fn rewrite_closure_expr(
751 context: &RewriteContext,
753 ) -> Option<String> {
754 let mut rewrite = expr.rewrite(context, shape);
755 if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
756 rewrite = and_one_line(rewrite);
758 rewrite.map(|rw| format!("{} {}", prefix, rw))
761 // Rewrite closure whose body is block.
762 fn rewrite_closure_block(
765 context: &RewriteContext,
767 ) -> Option<String> {
768 // Start with visual indent, then fall back to block indent if the
770 let block_threshold = context.config.closure_block_indent_threshold();
771 if block_threshold >= 0 {
772 if let Some(block_str) = block.rewrite(&context, shape) {
773 if block_str.matches('\n').count() <= block_threshold as usize &&
774 !need_block_indent(&block_str, shape)
776 if let Some(block_str) = block_str.rewrite(context, shape) {
777 return Some(format!("{} {}", prefix, block_str));
783 // The body of the closure is big enough to be block indented, that
784 // means we must re-format.
785 let block_shape = shape.block();
786 let block_str = try_opt!(block.rewrite(&context, block_shape));
787 Some(format!("{} {}", prefix, block_str))
790 fn and_one_line(x: Option<String>) -> Option<String> {
791 x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
794 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
795 debug!("nop_block_collapse {:?} {}", block_str, budget);
796 block_str.map(|block_str| {
797 if block_str.starts_with('{') && budget >= 2 &&
798 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
807 fn rewrite_empty_block(
808 context: &RewriteContext,
811 ) -> Option<String> {
812 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) &&
815 return Some("{}".to_owned());
818 // If a block contains only a single-line comment, then leave it on one line.
819 let user_str = context.snippet(block.span);
820 let user_str = user_str.trim();
821 if user_str.starts_with('{') && user_str.ends_with('}') {
822 let comment_str = user_str[1..user_str.len() - 1].trim();
823 if block.stmts.is_empty() && !comment_str.contains('\n') &&
824 !comment_str.starts_with("//") && comment_str.len() + 4 <= shape.width
826 return Some(format!("{{ {} }}", comment_str));
833 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
834 Some(match block.rules {
835 ast::BlockCheckMode::Unsafe(..) => {
836 let snippet = context.snippet(block.span);
837 let open_pos = try_opt!(snippet.find_uncommented("{"));
838 // Extract comment between unsafe and block start.
839 let trimmed = &snippet[6..open_pos].trim();
841 if !trimmed.is_empty() {
842 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
843 let budget = try_opt!(shape.width.checked_sub(9));
846 try_opt!(rewrite_comment(
849 Shape::legacy(budget, shape.indent + 7),
857 ast::BlockCheckMode::Default => String::new(),
861 fn rewrite_single_line_block(
862 context: &RewriteContext,
866 ) -> Option<String> {
867 if is_simple_block(block, context.codemap) {
868 let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
869 let expr_str = try_opt!(block.stmts[0].rewrite(context, expr_shape));
870 let result = format!("{}{{ {} }}", prefix, expr_str);
871 if result.len() <= shape.width && !result.contains('\n') {
878 fn rewrite_block_with_visitor(
879 context: &RewriteContext,
883 ) -> Option<String> {
884 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
888 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
889 visitor.block_indent = shape.indent;
890 visitor.is_if_else_block = context.is_if_else_block;
892 ast::BlockCheckMode::Unsafe(..) => {
893 let snippet = context.snippet(block.span);
894 let open_pos = try_opt!(snippet.find_uncommented("{"));
895 visitor.last_pos = block.span.lo + BytePos(open_pos as u32)
897 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo,
900 visitor.visit_block(block);
901 if visitor.failed && shape.indent.alignment != 0 {
904 Shape::indented(shape.indent.block_only(), context.config),
907 Some(format!("{}{}", prefix, visitor.buffer))
911 impl Rewrite for ast::Block {
912 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
913 // shape.width is used only for the single line case: either the empty block `{}`,
914 // or an unsafe expression `unsafe { e }`.
915 if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
919 let prefix = try_opt!(block_prefix(context, self, shape));
920 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
924 rewrite_block_with_visitor(context, &prefix, self, shape)
928 impl Rewrite for ast::Stmt {
929 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
930 let result = match self.node {
931 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
932 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
933 let suffix = if semicolon_for_stmt(self) { ";" } else { "" };
938 ast::StmtKind::Expr(_) => ExprType::SubExpression,
939 ast::StmtKind::Semi(_) => ExprType::Statement,
943 try_opt!(shape.sub_width(suffix.len())),
944 ).map(|s| s + suffix)
946 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
948 result.and_then(|res| {
949 recover_comment_removed(res, self.span, context, shape)
954 // Rewrite condition if the given expression has one.
955 fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
957 ast::ExprKind::Match(ref cond, _) => {
959 let cond_shape = match context.config.control_style() {
960 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
961 Style::Rfc => try_opt!(shape.offset_left(8)),
963 cond.rewrite(context, cond_shape)
965 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
966 stmt_expr(&block.stmts[0]).and_then(|e| rewrite_cond(context, e, shape))
969 to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
971 String::from("\n") + &shape.indent.block_only().to_string(context.config);
973 .rewrite_cond(context, shape, &alt_block_sep)
974 .and_then(|rw| Some(rw.0))
980 // Abstraction over control flow expressions
982 struct ControlFlow<'a> {
983 cond: Option<&'a ast::Expr>,
984 block: &'a ast::Block,
985 else_block: Option<&'a ast::Expr>,
986 label: Option<ast::SpannedIdent>,
987 pat: Option<&'a ast::Pat>,
991 allow_single_line: bool,
992 // True if this is an `if` expression in an `else if` :-( hacky
997 fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'a>> {
999 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
1000 Some(ControlFlow::new_if(
1004 else_block.as_ref().map(|e| &**e),
1005 expr_type == ExprType::SubExpression,
1010 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
1011 Some(ControlFlow::new_if(
1015 else_block.as_ref().map(|e| &**e),
1016 expr_type == ExprType::SubExpression,
1021 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
1022 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
1024 ast::ExprKind::Loop(ref block, label) => Some(
1025 ControlFlow::new_loop(block, label, expr.span),
1027 ast::ExprKind::While(ref cond, ref block, label) => Some(
1028 ControlFlow::new_while(None, cond, block, label, expr.span),
1030 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => {
1031 Some(ControlFlow::new_while(
1043 impl<'a> ControlFlow<'a> {
1045 cond: &'a ast::Expr,
1046 pat: Option<&'a ast::Pat>,
1047 block: &'a ast::Block,
1048 else_block: Option<&'a ast::Expr>,
1049 allow_single_line: bool,
1052 ) -> ControlFlow<'a> {
1056 else_block: else_block,
1060 matcher: match pat {
1065 allow_single_line: allow_single_line,
1066 nested_if: nested_if,
1072 block: &'a ast::Block,
1073 label: Option<ast::SpannedIdent>,
1075 ) -> ControlFlow<'a> {
1085 allow_single_line: false,
1092 pat: Option<&'a ast::Pat>,
1093 cond: &'a ast::Expr,
1094 block: &'a ast::Block,
1095 label: Option<ast::SpannedIdent>,
1097 ) -> ControlFlow<'a> {
1105 matcher: match pat {
1110 allow_single_line: false,
1118 cond: &'a ast::Expr,
1119 block: &'a ast::Block,
1120 label: Option<ast::SpannedIdent>,
1122 ) -> ControlFlow<'a> {
1132 allow_single_line: false,
1138 fn rewrite_single_line(
1141 context: &RewriteContext,
1143 ) -> Option<String> {
1144 assert!(self.allow_single_line);
1145 let else_block = try_opt!(self.else_block);
1146 let fixed_cost = self.keyword.len() + " { } else { }".len();
1148 if let ast::ExprKind::Block(ref else_node) = else_block.node {
1149 if !is_simple_block(self.block, context.codemap) ||
1150 !is_simple_block(else_node, context.codemap) ||
1151 pat_expr_str.contains('\n')
1156 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
1157 let expr = &self.block.stmts[0];
1158 let if_str = try_opt!(expr.rewrite(
1160 Shape::legacy(new_width, Indent::empty()),
1163 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
1164 let else_expr = &else_node.stmts[0];
1166 try_opt!(else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
1168 if if_str.contains('\n') || else_str.contains('\n') {
1172 let result = format!(
1173 "{} {} {{ {} }} else {{ {} }}",
1180 if result.len() <= width {
1181 return Some(result);
1189 impl<'a> ControlFlow<'a> {
1192 context: &RewriteContext,
1194 alt_block_sep: &str,
1195 ) -> Option<(String, usize)> {
1196 let constr_shape = if self.nested_if {
1197 // We are part of an if-elseif-else chain. Our constraints are tightened.
1198 // 7 = "} else " .len()
1199 try_opt!(shape.shrink_left(7))
1204 let label_string = rewrite_label(self.label);
1205 // 1 = space after keyword.
1206 let offset = self.keyword.len() + label_string.len() + 1;
1208 let pat_expr_string = match self.cond {
1210 let mut cond_shape = match context.config.control_style() {
1211 Style::Legacy => try_opt!(constr_shape.shrink_left(offset)),
1212 Style::Rfc => try_opt!(constr_shape.offset_left(offset)),
1214 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1216 cond_shape = try_opt!(cond_shape.sub_width(2));
1219 try_opt!(rewrite_pat_expr(
1229 None => String::new(),
1232 let force_newline_brace = context.config.control_style() == Style::Rfc &&
1233 pat_expr_string.contains('\n') &&
1234 !last_line_extendable(&pat_expr_string);
1236 // Try to format if-else on single line.
1237 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1238 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1240 if let Some(cond_str) = trial {
1241 if cond_str.len() <= context.config.single_line_if_else_max_width() {
1242 return Some((cond_str, 0));
1247 let cond_span = if let Some(cond) = self.cond {
1250 mk_sp(self.block.span.lo, self.block.span.lo)
1253 // for event in event
1254 let between_kwd_cond = mk_sp(
1255 context.codemap.span_after(self.span, self.keyword.trim()),
1258 |p| if self.matcher.is_empty() {
1261 context.codemap.span_before(self.span, self.matcher.trim())
1266 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1268 let after_cond_comment =
1269 extract_comment(mk_sp(cond_span.hi, self.block.span.lo), context, shape);
1271 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1273 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine ||
1281 let used_width = if pat_expr_string.contains('\n') {
1282 last_line_width(&pat_expr_string)
1284 // 2 = spaces after keyword and condition.
1285 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1293 between_kwd_cond_comment.as_ref().map_or(
1294 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1302 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1309 impl<'a> Rewrite for ControlFlow<'a> {
1310 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1311 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1314 String::from("\n") + &shape.indent.block_only().to_string(context.config);
1315 let (cond_str, used_width) = try_opt!(self.rewrite_cond(context, shape, &alt_block_sep));
1316 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1317 if used_width == 0 {
1318 return Some(cond_str);
1321 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1322 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1323 // we should avoid the single line case.
1324 let block_width = if self.else_block.is_some() || self.nested_if {
1329 let block_shape = Shape {
1333 let mut block_context = context.clone();
1334 block_context.is_if_else_block = self.else_block.is_some();
1335 let block_str = try_opt!(rewrite_block_with_visitor(
1342 let mut result = format!("{}{}", cond_str, block_str);
1344 if let Some(else_block) = self.else_block {
1345 let shape = Shape::indented(shape.indent, context.config);
1346 let mut last_in_chain = false;
1347 let rewrite = match else_block.node {
1348 // If the else expression is another if-else expression, prevent it
1349 // from being formatted on a single line.
1350 // Note how we're passing the original shape, as the
1351 // cost of "else" should not cascade.
1352 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1353 ControlFlow::new_if(
1357 next_else_block.as_ref().map(|e| &**e),
1360 mk_sp(else_block.span.lo, self.span.hi),
1361 ).rewrite(context, shape)
1363 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1364 ControlFlow::new_if(
1368 next_else_block.as_ref().map(|e| &**e),
1371 mk_sp(else_block.span.lo, self.span.hi),
1372 ).rewrite(context, shape)
1375 last_in_chain = true;
1376 // When rewriting a block, the width is only used for single line
1377 // blocks, passing 1 lets us avoid that.
1378 let else_shape = Shape {
1379 width: min(1, shape.width),
1382 format_expr(else_block, ExprType::Statement, context, else_shape)
1386 let between_kwd_else_block = mk_sp(
1390 .span_before(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1392 let between_kwd_else_block_comment =
1393 extract_comment(between_kwd_else_block, context, shape);
1395 let after_else = mk_sp(
1398 .span_after(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1401 let after_else_comment = extract_comment(after_else, context, shape);
1403 let between_sep = match context.config.control_brace_style() {
1404 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1407 ControlBraceStyle::AlwaysSameLine => " ",
1409 let after_sep = match context.config.control_brace_style() {
1410 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1417 between_kwd_else_block_comment
1419 .map_or(between_sep, |s| &**s),
1420 after_else_comment.as_ref().map_or(after_sep, |s| &**s)
1423 result.push_str(&try_opt!(rewrite));
1430 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
1432 Some(ident) => format!("{}: ", ident.node),
1433 None => "".to_owned(),
1437 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1438 let comment_str = context.snippet(span);
1439 if contains_comment(&comment_str) {
1440 let comment = try_opt!(rewrite_comment(
1447 "\n{indent}{}\n{indent}",
1449 indent = shape.indent.to_string(context.config)
1456 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1457 let snippet = codemap.span_to_snippet(block.span).unwrap();
1458 contains_comment(&snippet)
1461 // Checks that a block contains no statements, an expression and no comments.
1462 // FIXME: incorrectly returns false when comment is contained completely within
1464 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1465 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) &&
1466 !block_contains_comment(block, codemap))
1469 /// Checks whether a block contains at most one statement or expression, and no comments.
1470 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1471 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1474 /// Checks whether a block contains no statements, expressions, or comments.
1475 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1476 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1479 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1481 ast::StmtKind::Expr(..) => true,
1486 fn is_unsafe_block(block: &ast::Block) -> bool {
1487 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1494 // inter-match-arm-comment-rules:
1495 // - all comments following a match arm before the start of the next arm
1496 // are about the second arm
1497 fn rewrite_match_arm_comment(
1498 context: &RewriteContext,
1501 arm_indent_str: &str,
1502 ) -> Option<String> {
1503 // The leading "," is not part of the arm-comment
1504 let missed_str = match missed_str.find_uncommented(",") {
1505 Some(n) => &missed_str[n + 1..],
1506 None => &missed_str[..],
1509 let mut result = String::new();
1510 // any text not preceeded by a newline is pushed unmodified to the block
1511 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
1512 result.push_str(&missed_str[..first_brk]);
1513 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
1515 let first = missed_str
1516 .find(|c: char| !c.is_whitespace())
1517 .unwrap_or(missed_str.len());
1518 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
1519 // Excessive vertical whitespace before comment should be preserved
1520 // FIXME handle vertical whitespace better
1523 let missed_str = missed_str[first..].trim();
1524 if !missed_str.is_empty() {
1525 let comment = try_opt!(rewrite_comment(&missed_str, false, shape, context.config));
1527 result.push_str(arm_indent_str);
1528 result.push_str(&comment);
1535 context: &RewriteContext,
1540 ) -> Option<String> {
1541 if arms.is_empty() {
1546 let cond_shape = match context.config.control_style() {
1547 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
1548 Style::Rfc => try_opt!(shape.offset_left(8)),
1550 let cond_str = try_opt!(cond.rewrite(context, cond_shape));
1551 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1552 let block_sep = match context.config.control_brace_style() {
1553 ControlBraceStyle::AlwaysNextLine => alt_block_sep.as_str(),
1556 let mut result = format!("match {}{}{{", cond_str, block_sep);
1558 let arm_shape = if context.config.indent_match_arms() {
1559 shape.block_indent(context.config.tab_spaces())
1561 shape.block_indent(0)
1564 let arm_indent_str = arm_shape.indent.to_string(context.config);
1566 let open_brace_pos = context
1568 .span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])), "{");
1570 let arm_num = arms.len();
1571 for (i, arm) in arms.iter().enumerate() {
1572 // Make sure we get the stuff between arms.
1573 let missed_str = if i == 0 {
1574 context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
1576 context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
1578 let comment = try_opt!(rewrite_match_arm_comment(
1584 result.push_str(&comment);
1586 result.push_str(&arm_indent_str);
1588 let arm_str = arm.rewrite(&context, arm_shape.with_max_width(context.config));
1589 if let Some(ref arm_str) = arm_str {
1590 // Trim the trailing comma if necessary.
1591 if i == arm_num - 1 && context.config.trailing_comma() == SeparatorTactic::Never &&
1592 arm_str.ends_with(',')
1594 result.push_str(&arm_str[0..arm_str.len() - 1])
1596 result.push_str(arm_str)
1599 // We couldn't format the arm, just reproduce the source.
1600 let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
1601 result.push_str(&snippet);
1602 if context.config.trailing_comma() != SeparatorTactic::Never {
1603 result.push_str(arm_comma(context.config, &arm.body))
1607 // BytePos(1) = closing match brace.
1608 let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
1609 let last_comment = context.snippet(last_span);
1610 let comment = try_opt!(rewrite_match_arm_comment(
1616 result.push_str(&comment);
1618 result.push_str(&shape.indent.to_string(context.config));
1623 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
1629 if !attrs.is_empty() {
1630 return attrs[0].span.lo;
1636 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
1640 fn arm_comma(config: &Config, body: &ast::Expr) -> &'static str {
1641 if config.match_block_trailing_comma() {
1643 } else if let ast::ExprKind::Block(ref block) = body.node {
1644 if let ast::BlockCheckMode::Default = block.rules {
1655 impl Rewrite for ast::Arm {
1656 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1657 debug!("Arm::rewrite {:?} {:?}", self, shape);
1665 let attr_str = if !attrs.is_empty() {
1666 if contains_skip(attrs) {
1671 try_opt!(attrs.rewrite(context, shape)),
1672 shape.indent.to_string(context.config)
1680 let pat_shape = try_opt!(shape.sub_width(5));
1682 let pat_strs = try_opt!(
1684 .map(|p| p.rewrite(context, pat_shape))
1685 .collect::<Option<Vec<_>>>()
1688 let all_simple = pat_strs.iter().all(|p| !p.contains('\n'));
1689 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1690 let mut tactic = definitive_tactic(&items, ListTactic::HorizontalVertical, pat_shape.width);
1691 if tactic == DefinitiveListTactic::Horizontal && all_simple {
1692 tactic = DefinitiveListTactic::Mixed;
1694 let fmt = ListFormatting {
1697 trailing_separator: SeparatorTactic::Never,
1699 ends_with_newline: false,
1700 config: context.config,
1702 let pats_str = try_opt!(write_list(&items, &fmt));
1704 let guard_shape = if pats_str.contains('\n') {
1705 shape.with_max_width(context.config)
1710 let guard_str = try_opt!(rewrite_guard(
1714 trimmed_last_line_width(&pats_str),
1717 let pats_str = format!("{}{}", pats_str, guard_str);
1719 let (mut extend, body) = match body.node {
1720 ast::ExprKind::Block(ref block)
1721 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) &&
1722 context.config.wrap_match_arms() => {
1723 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1729 ast::ExprKind::Call(_, ref args) => (args.len() == 1, &**body),
1730 ast::ExprKind::Closure(..) | ast::ExprKind::Struct(..) | ast::ExprKind::Tup(..) => (
1734 _ => (false, &**body),
1736 extend &= context.use_block_indent();
1738 let comma = arm_comma(&context.config, body);
1740 String::from("\n") + &shape.indent.block_only().to_string(context.config);
1742 let pat_width = extra_offset(&pats_str, shape);
1743 // Let's try and get the arm body on the same line as the condition.
1745 if shape.width > pat_width + comma.len() + 4 {
1746 let arm_shape = shape
1747 .offset_left(pat_width + 4)
1749 .sub_width(comma.len())
1751 let rewrite = nop_block_collapse(
1752 format_expr(body, ExprType::Statement, context, arm_shape),
1755 let is_block = if let ast::ExprKind::Block(..) = body.node {
1763 if (!body_str.contains('\n') && body_str.len() <= arm_shape.width) ||
1764 !context.config.wrap_match_arms() ||
1765 (extend && first_line_width(body_str) <= arm_shape.width) ||
1767 let block_sep = match context.config.control_brace_style() {
1768 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep.as_str(),
1772 return Some(format!(
1774 attr_str.trim_left(),
1785 // FIXME: we're doing a second rewrite of the expr; This may not be
1787 let body_shape = try_opt!(shape.block_left(context.config.tab_spaces()));
1788 let next_line_body = try_opt!(nop_block_collapse(
1789 format_expr(body, ExprType::Statement, context, body_shape),
1792 let indent_str = shape
1794 .block_indent(context.config)
1795 .to_string(context.config);
1796 let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1797 if context.config.match_block_trailing_comma() {
1807 let block_sep = match context.config.control_brace_style() {
1808 ControlBraceStyle::AlwaysNextLine => alt_block_sep + body_prefix + "\n",
1809 _ if body_prefix.is_empty() => "\n".to_owned(),
1810 _ => " ".to_owned() + body_prefix + "\n",
1813 if context.config.wrap_match_arms() {
1815 "{}{} =>{}{}{}\n{}{}",
1816 attr_str.trim_left(),
1821 shape.indent.to_string(context.config),
1827 attr_str.trim_left(),
1838 // The `if ...` guard on a match arm.
1840 context: &RewriteContext,
1841 guard: &Option<ptr::P<ast::Expr>>,
1843 // The amount of space used up on this line for the pattern in
1844 // the arm (excludes offset).
1845 pattern_width: usize,
1846 ) -> Option<String> {
1847 if let Some(ref guard) = *guard {
1848 // First try to fit the guard string on the same line as the pattern.
1849 // 4 = ` if `, 5 = ` => {`
1850 if let Some(cond_shape) = shape
1851 .shrink_left(pattern_width + 4)
1852 .and_then(|s| s.sub_width(5))
1854 if let Some(cond_str) = guard
1855 .rewrite(context, cond_shape)
1856 .and_then(|s| s.rewrite(context, cond_shape))
1858 if !cond_str.contains('\n') {
1859 return Some(format!(" if {}", cond_str));
1864 // Not enough space to put the guard after the pattern, try a newline.
1866 if let Some(cond_shape) = Shape::indented(
1867 shape.indent.block_indent(context.config) + 3,
1871 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1872 return Some(format!(
1876 .block_indent(context.config)
1877 .to_string(context.config),
1889 fn rewrite_pat_expr(
1890 context: &RewriteContext,
1891 pat: Option<&ast::Pat>,
1894 // Connecting piece between pattern and expression,
1895 // *without* trailing space.
1899 ) -> Option<String> {
1900 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1901 if let Some(pat) = pat {
1902 let matcher = if matcher.is_empty() {
1905 format!("{} ", matcher)
1908 try_opt!(try_opt!(shape.offset_left(matcher.len())).sub_width(connector.len()));
1909 let pat_string = try_opt!(pat.rewrite(context, pat_shape));
1910 let result = format!("{}{}{}", matcher, pat_string, connector);
1911 return rewrite_assign_rhs(context, result, expr, shape);
1914 let expr_rw = expr.rewrite(context, shape);
1915 // The expression may (partially) fit on the current line.
1916 // We do not allow splitting between `if` and condition.
1917 if keyword == "if" || expr_rw.is_some() {
1921 // The expression won't fit on the current line, jump to next.
1922 let nested_shape = shape
1924 .block_indent(context.config.tab_spaces())
1925 .with_max_width(context.config);
1926 let nested_indent_str = nested_shape.indent.to_string(context.config);
1927 expr.rewrite(context, nested_shape)
1928 .map(|expr_rw| format!("\n{}{}", nested_indent_str, expr_rw))
1931 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1932 let string_lit = context.snippet(span);
1934 if !context.config.format_strings() && !context.config.force_format_strings() {
1939 .all(|line| line.ends_with('\\'))
1941 let new_indent = shape.visual_indent(1).indent;
1942 return Some(String::from(
1946 new_indent.to_string(context.config) + line.trim_left()
1948 .collect::<Vec<_>>()
1953 return Some(string_lit);
1957 if !context.config.force_format_strings() &&
1958 !string_requires_rewrite(context, span, &string_lit, shape)
1960 return Some(string_lit);
1963 let fmt = StringFormat {
1970 config: context.config,
1973 // Remove the quote characters.
1974 let str_lit = &string_lit[1..string_lit.len() - 1];
1976 rewrite_string(str_lit, &fmt)
1979 fn string_requires_rewrite(
1980 context: &RewriteContext,
1985 if context.codemap.lookup_char_pos(span.lo).col.0 != shape.indent.width() {
1989 for (i, line) in string.lines().enumerate() {
1991 if line.len() > shape.width {
1995 if line.len() > shape.width + shape.indent.width() {
2004 pub fn rewrite_call_with_binary_search<R>(
2005 context: &RewriteContext,
2007 args: &[&ast::Expr],
2014 let force_trailing_comma = if context.inside_macro {
2015 span_ends_with_comma(context, span)
2019 let closure = |callee_max_width| {
2020 // FIXME using byte lens instead of char lens (and probably all over the
2022 let callee_shape = Shape {
2023 width: callee_max_width,
2026 let callee_str = callee
2027 .rewrite(context, callee_shape)
2028 .ok_or(Ordering::Greater)?;
2036 context.config.fn_call_width(),
2037 force_trailing_comma,
2041 binary_search(1, shape.width, closure)
2044 pub fn rewrite_call(
2045 context: &RewriteContext,
2047 args: &[ptr::P<ast::Expr>],
2050 ) -> Option<String> {
2051 let force_trailing_comma = if context.inside_macro {
2052 span_ends_with_comma(context, span)
2059 &args.iter().map(|x| &**x).collect::<Vec<_>>(),
2062 context.config.fn_call_width(),
2063 force_trailing_comma,
2067 pub fn rewrite_call_inner<'a, T>(
2068 context: &RewriteContext,
2073 args_max_width: usize,
2074 force_trailing_comma: bool,
2075 ) -> Result<String, Ordering>
2077 T: Rewrite + Spanned + ToExpr + 'a,
2079 // 2 = `( `, 1 = `(`
2080 let paren_overhead = if context.config.spaces_within_parens() {
2085 let used_width = extra_offset(&callee_str, shape);
2086 let one_line_width = shape
2088 .checked_sub(used_width + 2 * paren_overhead)
2089 .ok_or(Ordering::Greater)?;
2091 let nested_shape = shape_from_fn_call_style(
2094 used_width + 2 * paren_overhead,
2095 used_width + paren_overhead,
2096 ).ok_or(Ordering::Greater)?;
2098 let span_lo = context.codemap.span_after(span, "(");
2099 let args_span = mk_sp(span_lo, span.hi);
2101 let (extendable, list_str) = rewrite_call_args(
2108 force_trailing_comma,
2109 ).or_else(|| if context.use_block_indent() {
2115 shape.block().indent.block_indent(context.config),
2120 force_trailing_comma,
2125 .ok_or(Ordering::Less)?;
2127 if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
2128 let mut new_context = context.clone();
2129 new_context.use_block = true;
2130 return rewrite_call_inner(
2137 force_trailing_comma,
2141 let args_shape = shape
2142 .sub_width(last_line_width(&callee_str))
2143 .ok_or(Ordering::Less)?;
2147 wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2151 fn need_block_indent(s: &str, shape: Shape) -> bool {
2152 s.lines().skip(1).any(|s| {
2153 s.find(|c| !char::is_whitespace(c))
2154 .map_or(false, |w| w + 1 < shape.indent.width())
2158 fn rewrite_call_args<'a, T>(
2159 context: &RewriteContext,
2163 one_line_width: usize,
2164 args_max_width: usize,
2165 force_trailing_comma: bool,
2166 ) -> Option<(bool, String)>
2168 T: Rewrite + Spanned + ToExpr + 'a,
2170 let items = itemize_list(
2174 |item| item.span().lo,
2175 |item| item.span().hi,
2176 |item| item.rewrite(context, shape),
2180 let mut item_vec: Vec<_> = items.collect();
2182 // Try letting the last argument overflow to the next line with block
2183 // indentation. If its first line fits on one line with the other arguments,
2184 // we format the function arguments horizontally.
2185 let tactic = try_overflow_last_arg(
2194 let fmt = ListFormatting {
2197 trailing_separator: if force_trailing_comma {
2198 SeparatorTactic::Always
2199 } else if context.inside_macro || !context.use_block_indent() {
2200 SeparatorTactic::Never
2202 context.config.trailing_comma()
2205 ends_with_newline: context.use_block_indent() && tactic == DefinitiveListTactic::Vertical,
2206 config: context.config,
2209 write_list(&item_vec, &fmt).map(|args_str| {
2210 (tactic != DefinitiveListTactic::Vertical, args_str)
2214 fn try_overflow_last_arg<'a, T>(
2215 context: &RewriteContext,
2216 item_vec: &mut Vec<ListItem>,
2219 one_line_width: usize,
2220 args_max_width: usize,
2221 ) -> DefinitiveListTactic
2223 T: Rewrite + Spanned + ToExpr + 'a,
2225 let overflow_last = can_be_overflowed(&context, args);
2227 // Replace the last item with its first line to see if it fits with
2229 let (orig_last, placeholder) = if overflow_last {
2230 let mut context = context.clone();
2231 if let Some(expr) = args[args.len() - 1].to_expr() {
2233 ast::ExprKind::MethodCall(..) => context.force_one_line_chain = true,
2237 last_arg_shape(&context, &item_vec, shape, args_max_width)
2238 .map_or((None, None), |arg_shape| {
2239 rewrite_last_arg_with_overflow(
2242 &mut item_vec[args.len() - 1],
2250 let tactic = definitive_tactic(
2252 ListTactic::LimitedHorizontalVertical(args_max_width),
2256 // Replace the stub with the full overflowing last argument if the rewrite
2257 // succeeded and its first line fits with the other arguments.
2258 match (overflow_last, tactic, placeholder) {
2259 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2260 item_vec[args.len() - 1].item = placeholder;
2263 item_vec[args.len() - 1].item = orig_last;
2272 context: &RewriteContext,
2273 items: &Vec<ListItem>,
2275 args_max_width: usize,
2276 ) -> Option<Shape> {
2277 let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
2278 acc + i.item.as_ref().map_or(0, |s| first_line_width(&s))
2280 let max_width = min(args_max_width, shape.width);
2281 let arg_indent = if context.use_block_indent() {
2282 shape.block().indent.block_unindent(context.config)
2284 shape.block().indent
2287 width: try_opt!(max_width.checked_sub(overhead)),
2293 // Rewriting closure which is placed at the end of the function call's arg.
2294 // Returns `None` if the reformatted closure 'looks bad'.
2295 fn rewrite_last_closure(
2296 context: &RewriteContext,
2299 ) -> Option<String> {
2300 if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
2301 let body = match body.node {
2302 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
2303 stmt_expr(&block.stmts[0]).unwrap_or(body)
2307 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
2315 // If the closure goes multi line before its body, do not overflow the closure.
2316 if prefix.contains('\n') {
2319 let body_shape = try_opt!(shape.offset_left(extra_offset));
2320 // When overflowing the closure which consists of a single control flow expression,
2321 // force to use block if its condition uses multi line.
2322 if rewrite_cond(context, body, body_shape)
2323 .map(|cond| cond.contains('\n'))
2326 return rewrite_closure_with_block(context, body_shape, &prefix, body);
2329 // Seems fine, just format the closure in usual manner.
2330 return expr.rewrite(context, shape);
2335 fn rewrite_last_arg_with_overflow<'a, T>(
2336 context: &RewriteContext,
2338 last_item: &mut ListItem,
2340 ) -> (Option<String>, Option<String>)
2342 T: Rewrite + Spanned + ToExpr + 'a,
2344 let last_arg = args[args.len() - 1];
2345 let rewrite = if let Some(expr) = last_arg.to_expr() {
2347 // When overflowing the closure which consists of a single control flow expression,
2348 // force to use block if its condition uses multi line.
2349 ast::ExprKind::Closure(..) => {
2350 // If the argument consists of multiple closures, we do not overflow
2351 // the last closure.
2352 if args.len() > 1 &&
2356 .filter_map(|arg| arg.to_expr())
2357 .any(|expr| match expr.node {
2358 ast::ExprKind::Closure(..) => true,
2363 rewrite_last_closure(context, expr, shape)
2366 _ => expr.rewrite(context, shape),
2369 last_arg.rewrite(context, shape)
2371 let orig_last = last_item.item.clone();
2373 if let Some(rewrite) = rewrite {
2374 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2375 last_item.item = rewrite_first_line;
2376 (orig_last, Some(rewrite))
2382 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2384 T: Rewrite + Spanned + ToExpr + 'a,
2387 .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2390 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2392 ast::ExprKind::Match(..) => {
2393 (context.use_block_indent() && args_len == 1) ||
2394 (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
2396 ast::ExprKind::If(..) |
2397 ast::ExprKind::IfLet(..) |
2398 ast::ExprKind::ForLoop(..) |
2399 ast::ExprKind::Loop(..) |
2400 ast::ExprKind::While(..) |
2401 ast::ExprKind::WhileLet(..) => {
2402 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2404 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
2405 context.use_block_indent() ||
2406 context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
2408 ast::ExprKind::Array(..) |
2409 ast::ExprKind::Call(..) |
2410 ast::ExprKind::Mac(..) |
2411 ast::ExprKind::MethodCall(..) |
2412 ast::ExprKind::Struct(..) |
2413 ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2414 ast::ExprKind::AddrOf(_, ref expr) |
2415 ast::ExprKind::Box(ref expr) |
2416 ast::ExprKind::Try(ref expr) |
2417 ast::ExprKind::Unary(_, ref expr) |
2418 ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2423 pub fn wrap_args_with_parens(
2424 context: &RewriteContext,
2426 is_extendable: bool,
2428 nested_shape: Shape,
2430 if !context.use_block_indent() ||
2431 (context.inside_macro && !args_str.contains('\n') &&
2432 args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2434 if context.config.spaces_within_parens() && args_str.len() > 0 {
2435 format!("( {} )", args_str)
2437 format!("({})", args_str)
2442 nested_shape.indent.to_string(context.config),
2444 shape.block().indent.to_string(context.config)
2449 fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2450 let snippet = context.snippet(span);
2452 .trim_right_matches(|c: char| c == ')' || c.is_whitespace())
2456 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2457 debug!("rewrite_paren, shape: {:?}", shape);
2458 let paren_overhead = paren_overhead(context);
2459 let sub_shape = try_opt!(shape.sub_width(paren_overhead / 2)).visual_indent(paren_overhead / 2);
2461 let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && s.len() > 0 {
2462 format!("( {} )", s)
2467 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2468 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2470 if subexpr_str.contains('\n') {
2471 Some(paren_wrapper(&subexpr_str))
2473 if subexpr_str.len() + paren_overhead <= shape.width {
2474 Some(paren_wrapper(&subexpr_str))
2476 let sub_shape = try_opt!(shape.offset_left(2));
2477 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2478 Some(paren_wrapper(&subexpr_str))
2486 context: &RewriteContext,
2488 ) -> Option<String> {
2489 let expr_str = try_opt!(expr.rewrite(context, shape));
2491 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
2497 let offset = expr_str.len() + lbr.len();
2498 let orig_index_rw = shape
2499 .visual_indent(offset)
2500 .sub_width(offset + rbr.len())
2501 .and_then(|index_shape| index.rewrite(context, index_shape));
2503 // Return if everything fits in a single line.
2504 match orig_index_rw {
2505 Some(ref index_str) if !index_str.contains('\n') => {
2506 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2511 // Try putting index on the next line and see if it fits in a single line.
2512 let indent = shape.indent.block_indent(context.config);
2513 let rhs_overhead = shape.rhs_overhead(context.config);
2514 let index_shape = try_opt!(Shape::indented(indent, context.config).offset_left(lbr.len()));
2515 let index_shape = try_opt!(index_shape.sub_width(rbr.len() + rhs_overhead));
2516 let new_index_rw = index.rewrite(context, index_shape);
2517 match (orig_index_rw, new_index_rw) {
2518 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => {
2522 indent.to_string(&context.config),
2528 (None, Some(ref new_index_str)) => {
2532 indent.to_string(&context.config),
2538 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2543 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2548 fields.iter().all(|field| !field.is_shorthand)
2551 fn rewrite_struct_lit<'a>(
2552 context: &RewriteContext,
2554 fields: &'a [ast::Field],
2555 base: Option<&'a ast::Expr>,
2558 ) -> Option<String> {
2559 debug!("rewrite_struct_lit: shape {:?}", shape);
2561 enum StructLitField<'a> {
2562 Regular(&'a ast::Field),
2563 Base(&'a ast::Expr),
2567 let path_shape = try_opt!(shape.sub_width(2));
2568 let path_str = try_opt!(rewrite_path(
2576 if fields.len() == 0 && base.is_none() {
2577 return Some(format!("{} {{}}", path_str));
2580 // Foo { a: Foo } - indent is +3, width is -5.
2581 let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
2583 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2584 let body_lo = context.codemap.span_after(span, "{");
2585 let fields_str = if struct_lit_can_be_aligned(fields, &base) &&
2586 context.config.struct_field_align_threshold() > 0
2588 try_opt!(rewrite_with_alignment(
2592 mk_sp(body_lo, span.hi),
2596 let field_iter = fields
2598 .map(StructLitField::Regular)
2599 .chain(base.into_iter().map(StructLitField::Base));
2601 let span_lo = |item: &StructLitField| match *item {
2602 StructLitField::Regular(field) => field.span().lo,
2603 StructLitField::Base(expr) => {
2604 let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
2605 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
2606 let pos = snippet.find_uncommented("..").unwrap();
2607 last_field_hi + BytePos(pos as u32)
2610 let span_hi = |item: &StructLitField| match *item {
2611 StructLitField::Regular(field) => field.span().hi,
2612 StructLitField::Base(expr) => expr.span.hi,
2614 let rewrite = |item: &StructLitField| match *item {
2615 StructLitField::Regular(field) => {
2616 // The 1 taken from the v_budget is for the comma.
2617 rewrite_field(context, field, try_opt!(v_shape.sub_width(1)), 0)
2619 StructLitField::Base(expr) => {
2621 expr.rewrite(context, try_opt!(v_shape.shrink_left(2)))
2622 .map(|s| format!("..{}", s))
2626 let items = itemize_list(
2636 let item_vec = items.collect::<Vec<_>>();
2638 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2639 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2640 let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2642 try_opt!(write_list(&item_vec, &fmt))
2645 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2646 Some(format!("{} {{{}}}", path_str, fields_str))
2648 // FIXME if context.config.struct_lit_style() == Visual, but we run out
2649 // of space, we should fall back to BlockIndent.
2652 pub fn wrap_struct_field(
2653 context: &RewriteContext,
2656 nested_shape: Shape,
2657 one_line_width: usize,
2659 if context.config.struct_lit_style() == IndentStyle::Block &&
2660 (fields_str.contains('\n') ||
2661 context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti ||
2662 fields_str.len() > one_line_width)
2666 nested_shape.indent.to_string(context.config),
2668 shape.indent.to_string(context.config)
2671 // One liner or visual indent.
2672 format!(" {} ", fields_str)
2676 pub fn struct_lit_field_separator(config: &Config) -> &str {
2678 config.space_before_struct_lit_field_colon(),
2679 config.space_after_struct_lit_field_colon(),
2683 pub fn rewrite_field(
2684 context: &RewriteContext,
2687 prefix_max_width: usize,
2688 ) -> Option<String> {
2689 if contains_skip(&field.attrs) {
2691 context.snippet(field.span()),
2692 context.config.max_width(),
2696 let name = &field.ident.node.to_string();
2697 if field.is_shorthand {
2698 Some(name.to_string())
2700 let mut separator = String::from(struct_lit_field_separator(context.config));
2701 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2702 separator.push(' ');
2704 let overhead = name.len() + separator.len();
2705 let expr_shape = try_opt!(shape.offset_left(overhead));
2706 let expr = field.expr.rewrite(context, expr_shape);
2708 let mut attrs_str = try_opt!(field.attrs.rewrite(context, shape));
2709 if !attrs_str.is_empty() {
2710 attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2714 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2716 let expr_offset = shape.indent.block_indent(context.config);
2719 .rewrite(context, Shape::indented(expr_offset, context.config));
2725 expr_offset.to_string(&context.config),
2734 fn shape_from_fn_call_style(
2735 context: &RewriteContext,
2739 ) -> Option<Shape> {
2740 if context.use_block_indent() {
2744 .block_indent(context.config.tab_spaces())
2745 .with_max_width(context.config)
2748 shape.visual_indent(offset).sub_width(overhead)
2752 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2753 context: &RewriteContext,
2759 T: Rewrite + Spanned + ToExpr + 'a,
2761 let mut items = items.iter();
2762 // In case of length 1, need a trailing comma
2763 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2764 if items.len() == 1 {
2766 let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
2767 return items.next().unwrap().rewrite(context, nested_shape).map(
2768 |s| if context.config.spaces_within_parens() {
2769 format!("( {}, )", s)
2776 let list_lo = context.codemap.span_after(span, "(");
2777 let nested_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
2778 let items = itemize_list(
2782 |item| item.span().lo,
2783 |item| item.span().hi,
2784 |item| item.rewrite(context, nested_shape),
2786 span.hi - BytePos(1),
2788 let item_vec: Vec<_> = items.collect();
2789 let tactic = definitive_tactic(
2791 ListTactic::HorizontalVertical,
2794 let fmt = ListFormatting {
2797 trailing_separator: SeparatorTactic::Never,
2799 ends_with_newline: false,
2800 config: context.config,
2802 let list_str = try_opt!(write_list(&item_vec, &fmt));
2804 if context.config.spaces_within_parens() && list_str.len() > 0 {
2805 Some(format!("( {} )", list_str))
2807 Some(format!("({})", list_str))
2811 pub fn rewrite_tuple<'a, T>(
2812 context: &RewriteContext,
2818 T: Rewrite + Spanned + ToExpr + 'a,
2820 debug!("rewrite_tuple {:?}", shape);
2821 if context.use_block_indent() {
2822 // We use the same rule as funcation call for rewriting tuple.
2823 let force_trailing_comma = if context.inside_macro {
2824 span_ends_with_comma(context, span)
2834 context.config.fn_call_width(),
2835 force_trailing_comma,
2838 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2842 pub fn rewrite_unary_prefix<R: Rewrite>(
2843 context: &RewriteContext,
2847 ) -> Option<String> {
2849 .rewrite(context, try_opt!(shape.offset_left(prefix.len())))
2850 .map(|r| format!("{}{}", prefix, r))
2853 // FIXME: this is probably not correct for multi-line Rewrites. we should
2854 // subtract suffix.len() from the last line budget, not the first!
2855 pub fn rewrite_unary_suffix<R: Rewrite>(
2856 context: &RewriteContext,
2860 ) -> Option<String> {
2862 .rewrite(context, try_opt!(shape.sub_width(suffix.len())))
2869 fn rewrite_unary_op(
2870 context: &RewriteContext,
2874 ) -> Option<String> {
2875 // For some reason, an UnOp is not spanned like BinOp!
2876 let operator_str = match *op {
2877 ast::UnOp::Deref => "*",
2878 ast::UnOp::Not => "!",
2879 ast::UnOp::Neg => "-",
2881 rewrite_unary_prefix(context, operator_str, expr, shape)
2884 fn rewrite_assignment(
2885 context: &RewriteContext,
2888 op: Option<&ast::BinOp>,
2890 ) -> Option<String> {
2891 let operator_str = match op {
2892 Some(op) => context.snippet(op.span),
2893 None => "=".to_owned(),
2896 // 1 = space between lhs and operator.
2897 let lhs_shape = try_opt!(shape.sub_width(operator_str.len() + 1));
2898 let lhs_str = format!(
2900 try_opt!(lhs.rewrite(context, lhs_shape)),
2904 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2907 // The left hand side must contain everything up to, and including, the
2908 // assignment operator.
2909 pub fn rewrite_assign_rhs<S: Into<String>>(
2910 context: &RewriteContext,
2914 ) -> Option<String> {
2915 let lhs = lhs.into();
2916 let last_line_width = last_line_width(&lhs) -
2917 if lhs.contains('\n') {
2918 shape.indent.width()
2922 // 1 = space between operator and rhs.
2923 let orig_shape = try_opt!(shape.offset_left(last_line_width + 1));
2924 let rhs = try_opt!(choose_rhs(
2928 ex.rewrite(context, orig_shape)
2934 context: &RewriteContext,
2937 orig_rhs: Option<String>,
2938 ) -> Option<String> {
2940 Some(ref new_str) if !new_str.contains('\n') => Some(format!(" {}", new_str)),
2942 // Expression did not fit on the same line as the identifier.
2943 // Try splitting the line and see if that works better.
2944 let new_shape = try_opt!(
2946 shape.block().indent.block_indent(context.config),
2948 ).sub_width(shape.rhs_overhead(context.config))
2950 let new_rhs = expr.rewrite(context, new_shape);
2951 let new_indent_str = &new_shape.indent.to_string(context.config);
2953 match (orig_rhs, new_rhs) {
2954 (Some(ref orig_rhs), Some(ref new_rhs)) if prefer_next_line(orig_rhs, new_rhs) => {
2955 Some(format!("\n{}{}", new_indent_str, new_rhs))
2957 (None, Some(ref new_rhs)) => Some(format!("\n{}{}", new_indent_str, new_rhs)),
2958 (None, None) => None,
2959 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2965 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {
2967 fn count_line_breaks(src: &str) -> usize {
2968 src.chars().filter(|&x| x == '\n').count()
2971 !next_line_rhs.contains('\n') ||
2972 count_line_breaks(orig_rhs) > count_line_breaks(next_line_rhs) + 1
2975 fn rewrite_expr_addrof(
2976 context: &RewriteContext,
2977 mutability: ast::Mutability,
2980 ) -> Option<String> {
2981 let operator_str = match mutability {
2982 ast::Mutability::Immutable => "&",
2983 ast::Mutability::Mutable => "&mut ",
2985 rewrite_unary_prefix(context, operator_str, expr, shape)
2989 fn to_expr(&self) -> Option<&ast::Expr>;
2990 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2993 impl ToExpr for ast::Expr {
2994 fn to_expr(&self) -> Option<&ast::Expr> {
2998 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2999 can_be_overflowed_expr(context, self, len)
3003 impl ToExpr for ast::Ty {
3004 fn to_expr(&self) -> Option<&ast::Expr> {
3008 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
3009 can_be_overflowed_type(context, self, len)
3013 impl<'a> ToExpr for TuplePatField<'a> {
3014 fn to_expr(&self) -> Option<&ast::Expr> {
3018 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
3019 can_be_overflowed_pat(context, self, len)
3023 impl<'a> ToExpr for ast::StructField {
3024 fn to_expr(&self) -> Option<&ast::Expr> {
3028 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {