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::{min, Ordering};
13 use std::iter::ExactSizeIterator;
15 use syntax::{ast, ptr};
16 use syntax::codemap::{BytePos, CodeMap, Span};
17 use syntax::parse::classify;
19 use {Indent, Shape, Spanned};
20 use chains::rewrite_chain;
21 use codemap::SpanUtils;
22 use comment::{contains_comment, recover_comment_removed, rewrite_comment, FindUncommented};
23 use config::{Config, ControlBraceStyle, IndentStyle, MultilineStyle, Style};
24 use items::{span_hi_for_arg, span_lo_for_arg};
25 use lists::{definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting,
26 struct_lit_shape, struct_lit_tactic, write_list, DefinitiveListTactic, ListFormatting,
27 ListItem, ListTactic, SeparatorTactic};
28 use macros::{rewrite_macro, MacroPosition};
29 use patterns::{can_be_overflowed_pat, TuplePatField};
30 use rewrite::{Rewrite, RewriteContext};
31 use string::{rewrite_string, StringFormat};
32 use types::{can_be_overflowed_type, rewrite_path, PathContext};
33 use utils::{binary_search, colon_spaces, contains_skip, extra_offset, first_line_width,
34 last_line_extendable, last_line_width, left_most_sub_expr, mk_sp, paren_overhead,
35 semicolon_for_stmt, stmt_expr, trimmed_last_line_width, wrap_str};
36 use vertical::rewrite_with_alignment;
37 use visitor::FmtVisitor;
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) => rewrite_array(
92 expr_vec.iter().map(|e| &**e),
93 mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi),
98 ast::ExprKind::Lit(ref l) => match l.node {
99 ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
100 rewrite_string_lit(context, l.span, shape)
103 context.snippet(expr.span),
104 context.config.max_width(),
108 ast::ExprKind::Call(ref callee, ref args) => {
109 let inner_span = mk_sp(callee.span.hi, expr.span.hi);
110 rewrite_call_with_binary_search(
113 &args.iter().map(|x| &**x).collect::<Vec<_>>()[..],
118 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
119 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
120 // FIXME: format comments between operands and operator
125 &format!(" {} ", context.snippet(op.span)),
131 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
132 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
136 base.as_ref().map(|e| &**e),
140 ast::ExprKind::Tup(ref items) => rewrite_tuple(
142 &items.iter().map(|x| &**x).collect::<Vec<_>>()[..],
146 ast::ExprKind::If(..) |
147 ast::ExprKind::IfLet(..) |
148 ast::ExprKind::ForLoop(..) |
149 ast::ExprKind::Loop(..) |
150 ast::ExprKind::While(..) |
151 ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
152 .and_then(|control_flow| control_flow.rewrite(context, shape)),
153 ast::ExprKind::Block(ref block) => {
155 ExprType::Statement => {
156 if is_unsafe_block(block) {
157 block.rewrite(context, shape)
159 // Rewrite block without trying to put it in a single line.
160 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
163 let prefix = try_opt!(block_prefix(context, block, shape));
164 rewrite_block_with_visitor(context, &prefix, block, shape)
167 ExprType::SubExpression => block.rewrite(context, shape),
170 ast::ExprKind::Match(ref cond, ref arms) => {
171 rewrite_match(context, cond, arms, shape, expr.span)
173 ast::ExprKind::Path(ref qself, ref path) => {
174 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
176 ast::ExprKind::Assign(ref lhs, ref rhs) => {
177 rewrite_assignment(context, lhs, rhs, None, shape)
179 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
180 rewrite_assignment(context, lhs, rhs, Some(op), shape)
182 ast::ExprKind::Continue(ref opt_ident) => {
183 let id_str = match *opt_ident {
184 Some(ident) => format!(" {}", ident.node),
185 None => String::new(),
188 format!("continue{}", id_str),
189 context.config.max_width(),
193 ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
194 let id_str = match *opt_ident {
195 Some(ident) => format!(" {}", ident.node),
196 None => String::new(),
199 if let Some(ref expr) = *opt_expr {
200 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
203 format!("break{}", id_str),
204 context.config.max_width(),
209 ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
210 rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
212 ast::ExprKind::Try(..) |
213 ast::ExprKind::Field(..) |
214 ast::ExprKind::TupField(..) |
215 ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
216 ast::ExprKind::Mac(ref mac) => {
217 // Failure to rewrite a marco should not imply failure to
218 // rewrite the expression.
219 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
221 context.snippet(expr.span),
222 context.config.max_width(),
227 ast::ExprKind::Ret(None) => {
228 wrap_str("return".to_owned(), context.config.max_width(), shape)
230 ast::ExprKind::Ret(Some(ref expr)) => {
231 rewrite_unary_prefix(context, "return ", &**expr, shape)
233 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
234 ast::ExprKind::AddrOf(mutability, ref expr) => {
235 rewrite_expr_addrof(context, mutability, expr, shape)
237 ast::ExprKind::Cast(ref expr, ref ty) => {
238 rewrite_pair(&**expr, &**ty, "", " as ", "", context, shape)
240 ast::ExprKind::Type(ref expr, ref ty) => {
241 rewrite_pair(&**expr, &**ty, "", ": ", "", context, shape)
243 ast::ExprKind::Index(ref expr, ref index) => {
244 rewrite_index(&**expr, &**index, context, shape)
246 ast::ExprKind::Repeat(ref expr, ref repeats) => {
247 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
252 rewrite_pair(&**expr, &**repeats, lbr, "; ", rbr, context, shape)
254 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
255 let delim = match limits {
256 ast::RangeLimits::HalfOpen => "..",
257 ast::RangeLimits::Closed => "...",
260 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
262 ast::ExprKind::Lit(ref lit) => match lit.node {
263 ast::LitKind::FloatUnsuffixed(..) => {
264 context.snippet(lit.span).ends_with('.')
272 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
273 (Some(ref lhs), Some(ref rhs)) => {
274 let sp_delim = if context.config.spaces_around_ranges() {
275 format!(" {} ", delim)
276 } else if needs_space_before_range(context, lhs) {
277 format!(" {}", delim)
281 rewrite_pair(&**lhs, &**rhs, "", &sp_delim, "", context, shape)
283 (None, Some(ref rhs)) => {
284 let sp_delim = if context.config.spaces_around_ranges() {
285 format!("{} ", delim)
289 rewrite_unary_prefix(context, &sp_delim, &**rhs, shape)
291 (Some(ref lhs), None) => {
292 let sp_delim = if context.config.spaces_around_ranges() {
293 format!(" {}", delim)
297 rewrite_unary_suffix(context, &sp_delim, &**lhs, shape)
299 (None, None) => wrap_str(delim.into(), context.config.max_width(), shape),
302 // We do not format these expressions yet, but they should still
303 // satisfy our width restrictions.
304 ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => wrap_str(
305 context.snippet(expr.span),
306 context.config.max_width(),
309 ast::ExprKind::Catch(ref block) => {
310 if let rewrite @ Some(_) =
311 rewrite_single_line_block(context, "do catch ", block, shape)
316 let budget = shape.width.checked_sub(9).unwrap_or(0);
320 try_opt!(block.rewrite(&context, Shape::legacy(budget, shape.indent)))
324 match (attr_rw, expr_rw) {
325 (Some(attr_str), Some(expr_str)) => recover_comment_removed(
326 combine_attr_and_expr(context, shape, &attr_str, &expr_str),
335 pub fn rewrite_pair<LHS, RHS>(
341 context: &RewriteContext,
348 // Get "full width" rhs and see if it fits on the current line. This
349 // usually works fairly well since it tends to place operands of
350 // operations with high precendence close together.
351 // Note that this is non-conservative, but its just to see if it's even
352 // worth trying to put everything on one line.
353 let rhs_shape = try_opt!(shape.sub_width(suffix.len()));
354 let rhs_result = rhs.rewrite(context, rhs_shape);
356 if let Some(rhs_result) = rhs_result {
357 // This is needed in case of line break not caused by a
358 // shortage of space, but by end-of-line comments, for example.
359 if !rhs_result.contains('\n') {
361 try_opt!(try_opt!(shape.offset_left(prefix.len())).sub_width(infix.len()));
362 let lhs_result = lhs.rewrite(context, lhs_shape);
363 if let Some(lhs_result) = lhs_result {
364 let mut result = format!("{}{}{}", prefix, lhs_result, infix);
366 let remaining_width = shape
368 .checked_sub(last_line_width(&result) + suffix.len())
371 if rhs_result.len() <= remaining_width {
372 result.push_str(&rhs_result);
373 result.push_str(suffix);
377 // Try rewriting the rhs into the remaining space.
378 let rhs_shape = shape.shrink_left(last_line_width(&result) + suffix.len());
379 if let Some(rhs_shape) = rhs_shape {
380 if let Some(rhs_result) = rhs.rewrite(context, rhs_shape) {
381 // FIXME this should always hold.
382 if rhs_result.len() <= remaining_width {
383 result.push_str(&rhs_result);
384 result.push_str(suffix);
393 // We have to use multiple lines.
395 // Re-evaluate the rhs because we have more space now:
396 let infix = infix.trim_right();
397 let rhs_shape = match context.config.control_style() {
399 try_opt!(shape.sub_width(suffix.len() + prefix.len())).visual_indent(prefix.len())
402 // Try to calculate the initial constraint on the right hand side.
403 let rhs_overhead = shape.rhs_overhead(context.config);
405 Shape::indented(shape.indent.block_indent(context.config), context.config)
406 .sub_width(rhs_overhead)
410 let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape));
411 let lhs_overhead = shape.used_width() + prefix.len() + infix.len();
412 let lhs_shape = Shape {
413 width: try_opt!(context.config.max_width().checked_sub(lhs_overhead)),
416 let lhs_result = try_opt!(lhs.rewrite(context, lhs_shape));
422 rhs_shape.indent.to_string(context.config),
428 pub fn rewrite_array<'a, I>(
431 context: &RewriteContext,
433 trailing_comma: bool,
436 I: Iterator<Item = &'a ast::Expr>,
438 let bracket_size = if context.config.spaces_within_square_brackets() {
444 let mut nested_shape = match context.config.array_layout() {
445 IndentStyle::Block => try_opt!(
448 .block_indent(context.config.tab_spaces())
449 .with_max_width(context.config)
452 IndentStyle::Visual => try_opt!(
454 .visual_indent(bracket_size)
455 .sub_width(bracket_size * 2)
459 let items = itemize_list(
465 |item| item.rewrite(context, nested_shape),
468 ).collect::<Vec<_>>();
470 if items.is_empty() {
471 if context.config.spaces_within_square_brackets() {
472 return Some("[ ]".to_string());
474 return Some("[]".to_string());
478 let has_long_item = items
480 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
482 let mut tactic = match context.config.array_layout() {
483 IndentStyle::Block => {
484 // FIXME wrong shape in one-line case
485 match shape.width.checked_sub(2 * bracket_size) {
488 ListTactic::LimitedHorizontalVertical(context.config.array_width());
489 definitive_tactic(&items, tactic, width)
491 None => DefinitiveListTactic::Vertical,
494 IndentStyle::Visual => if has_long_item || items.iter().any(ListItem::is_multiline) {
497 ListTactic::LimitedHorizontalVertical(context.config.array_width()),
501 DefinitiveListTactic::Mixed
504 let mut ends_with_newline = tactic.ends_with_newline(context.config.array_layout());
505 if context.config.array_horizontal_layout_threshold() > 0 &&
506 items.len() > context.config.array_horizontal_layout_threshold()
508 tactic = DefinitiveListTactic::Mixed;
509 ends_with_newline = false;
510 if context.config.array_layout() == IndentStyle::Block {
511 nested_shape = try_opt!(
513 .visual_indent(bracket_size)
514 .sub_width(bracket_size * 2)
519 let fmt = ListFormatting {
522 trailing_separator: if trailing_comma {
523 SeparatorTactic::Always
524 } else if context.inside_macro || context.config.array_layout() == IndentStyle::Visual {
525 SeparatorTactic::Never
527 SeparatorTactic::Vertical
530 ends_with_newline: ends_with_newline,
531 config: context.config,
533 let list_str = try_opt!(write_list(&items, &fmt));
535 let result = if context.config.array_layout() == IndentStyle::Visual ||
536 tactic != DefinitiveListTactic::Vertical
538 if context.config.spaces_within_square_brackets() && list_str.len() > 0 {
539 format!("[ {} ]", list_str)
541 format!("[{}]", list_str)
546 nested_shape.indent.to_string(context.config),
548 shape.block().indent.to_string(context.config)
555 // Return type is (prefix, extra_offset)
556 fn rewrite_closure_fn_decl(
557 capture: ast::CaptureBy,
558 fn_decl: &ast::FnDecl,
561 context: &RewriteContext,
563 ) -> Option<(String, usize)> {
564 let mover = if capture == ast::CaptureBy::Value {
569 // 4 = "|| {".len(), which is overconservative when the closure consists of
570 // a single expression.
571 let nested_shape = try_opt!(try_opt!(shape.shrink_left(mover.len())).sub_width(4));
574 let argument_offset = nested_shape.indent + 1;
575 let arg_shape = try_opt!(nested_shape.shrink_left(1)).visual_indent(0);
576 let ret_str = try_opt!(fn_decl.output.rewrite(context, arg_shape));
578 let arg_items = itemize_list(
580 fn_decl.inputs.iter(),
582 |arg| span_lo_for_arg(arg),
583 |arg| span_hi_for_arg(context, arg),
584 |arg| arg.rewrite(context, arg_shape),
585 context.codemap.span_after(span, "|"),
588 let item_vec = arg_items.collect::<Vec<_>>();
589 // 1 = space between arguments and return type.
590 let horizontal_budget = nested_shape
592 .checked_sub(ret_str.len() + 1)
594 let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
595 let arg_shape = match tactic {
596 DefinitiveListTactic::Horizontal => try_opt!(arg_shape.sub_width(ret_str.len() + 1)),
600 let fmt = ListFormatting {
603 trailing_separator: SeparatorTactic::Never,
605 ends_with_newline: false,
606 config: context.config,
608 let list_str = try_opt!(write_list(&item_vec, &fmt));
609 let mut prefix = format!("{}|{}|", mover, list_str);
610 // 1 = space between `|...|` and body.
611 let extra_offset = extra_offset(&prefix, shape) + 1;
613 if !ret_str.is_empty() {
614 if prefix.contains('\n') {
616 prefix.push_str(&argument_offset.to_string(context.config));
620 prefix.push_str(&ret_str);
623 Some((prefix, extra_offset))
626 // This functions is pretty messy because of the rules around closures and blocks:
627 // FIXME - the below is probably no longer true in full.
628 // * if there is a return type, then there must be braces,
629 // * given a closure with braces, whether that is parsed to give an inner block
630 // or not depends on if there is a return type and if there are statements
632 // * if the first expression in the body ends with a block (i.e., is a
633 // statement without needing a semi-colon), then adding or removing braces
634 // can change whether it is treated as an expression or statement.
636 capture: ast::CaptureBy,
637 fn_decl: &ast::FnDecl,
640 context: &RewriteContext,
642 ) -> Option<String> {
643 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
651 // 1 = space between `|...|` and body.
652 let body_shape = try_opt!(shape.offset_left(extra_offset));
654 if let ast::ExprKind::Block(ref block) = body.node {
655 // The body of the closure is an empty block.
656 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
657 return Some(format!("{} {{}}", prefix));
660 // Figure out if the block is necessary.
661 let needs_block = block.rules != ast::BlockCheckMode::Default ||
662 block.stmts.len() > 1 || context.inside_macro ||
663 block_contains_comment(block, context.codemap) ||
664 prefix.contains('\n');
666 let no_return_type = if let ast::FunctionRetTy::Default(_) = fn_decl.output {
671 if no_return_type && !needs_block {
672 // lock.stmts.len() == 1
673 if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
674 if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
681 // We need braces, but we might still prefer a one-liner.
682 let stmt = &block.stmts[0];
683 // 4 = braces and spaces.
684 if let Some(body_shape) = body_shape.sub_width(4) {
685 // Checks if rewrite succeeded and fits on a single line.
686 if let Some(rewrite) = and_one_line(stmt.rewrite(context, body_shape)) {
687 return Some(format!("{} {{ {} }}", prefix, rewrite));
692 // Either we require a block, or tried without and failed.
693 rewrite_closure_block(&block, &prefix, context, body_shape)
695 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
696 // The closure originally had a non-block expression, but we can't fit on
697 // one line, so we'll insert a block.
698 rewrite_closure_with_block(context, body_shape, &prefix, body)
703 // Rewrite closure with a single expression wrapping its body with block.
704 fn rewrite_closure_with_block(
705 context: &RewriteContext,
709 ) -> Option<String> {
710 let block = ast::Block {
713 id: ast::NodeId::new(0),
714 node: ast::StmtKind::Expr(ptr::P(body.clone())),
718 id: ast::NodeId::new(0),
719 rules: ast::BlockCheckMode::Default,
722 rewrite_closure_block(&block, prefix, context, shape)
725 // Rewrite closure with a single expression without wrapping its body with block.
726 fn rewrite_closure_expr(
729 context: &RewriteContext,
731 ) -> Option<String> {
732 let mut rewrite = expr.rewrite(context, shape);
733 if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
734 rewrite = and_one_line(rewrite);
736 rewrite.map(|rw| format!("{} {}", prefix, rw))
739 // Rewrite closure whose body is block.
740 fn rewrite_closure_block(
743 context: &RewriteContext,
745 ) -> Option<String> {
746 // Start with visual indent, then fall back to block indent if the
748 let block_threshold = context.config.closure_block_indent_threshold();
749 if block_threshold >= 0 {
750 if let Some(block_str) = block.rewrite(&context, shape) {
751 if block_str.matches('\n').count() <= block_threshold as usize &&
752 !need_block_indent(&block_str, shape)
754 if let Some(block_str) = block_str.rewrite(context, shape) {
755 return Some(format!("{} {}", prefix, block_str));
761 // The body of the closure is big enough to be block indented, that
762 // means we must re-format.
763 let block_shape = shape.block();
764 let block_str = try_opt!(block.rewrite(&context, block_shape));
765 Some(format!("{} {}", prefix, block_str))
768 fn and_one_line(x: Option<String>) -> Option<String> {
769 x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
772 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
773 debug!("nop_block_collapse {:?} {}", block_str, budget);
774 block_str.map(|block_str| {
775 if block_str.starts_with('{') && budget >= 2 &&
776 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
785 fn rewrite_empty_block(
786 context: &RewriteContext,
789 ) -> Option<String> {
790 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) &&
793 return Some("{}".to_owned());
796 // If a block contains only a single-line comment, then leave it on one line.
797 let user_str = context.snippet(block.span);
798 let user_str = user_str.trim();
799 if user_str.starts_with('{') && user_str.ends_with('}') {
800 let comment_str = user_str[1..user_str.len() - 1].trim();
801 if block.stmts.is_empty() && !comment_str.contains('\n') &&
802 !comment_str.starts_with("//") && comment_str.len() + 4 <= shape.width
804 return Some(format!("{{ {} }}", comment_str));
811 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
812 Some(match block.rules {
813 ast::BlockCheckMode::Unsafe(..) => {
814 let snippet = context.snippet(block.span);
815 let open_pos = try_opt!(snippet.find_uncommented("{"));
816 // Extract comment between unsafe and block start.
817 let trimmed = &snippet[6..open_pos].trim();
819 if !trimmed.is_empty() {
820 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
821 let budget = try_opt!(shape.width.checked_sub(9));
824 try_opt!(rewrite_comment(
827 Shape::legacy(budget, shape.indent + 7),
835 ast::BlockCheckMode::Default => String::new(),
839 fn rewrite_single_line_block(
840 context: &RewriteContext,
844 ) -> Option<String> {
845 if is_simple_block(block, context.codemap) {
846 let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
847 let expr_str = try_opt!(block.stmts[0].rewrite(context, expr_shape));
848 let result = format!("{}{{ {} }}", prefix, expr_str);
849 if result.len() <= shape.width && !result.contains('\n') {
856 fn rewrite_block_with_visitor(
857 context: &RewriteContext,
861 ) -> Option<String> {
862 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
866 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
867 visitor.block_indent = shape.indent;
868 visitor.is_if_else_block = context.is_if_else_block;
870 ast::BlockCheckMode::Unsafe(..) => {
871 let snippet = context.snippet(block.span);
872 let open_pos = try_opt!(snippet.find_uncommented("{"));
873 visitor.last_pos = block.span.lo + BytePos(open_pos as u32)
875 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo,
878 visitor.visit_block(block);
879 if visitor.failed && shape.indent.alignment != 0 {
882 Shape::indented(shape.indent.block_only(), context.config),
885 Some(format!("{}{}", prefix, visitor.buffer))
889 impl Rewrite for ast::Block {
890 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
891 // shape.width is used only for the single line case: either the empty block `{}`,
892 // or an unsafe expression `unsafe { e }`.
893 if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
897 let prefix = try_opt!(block_prefix(context, self, shape));
898 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
902 rewrite_block_with_visitor(context, &prefix, self, shape)
906 impl Rewrite for ast::Stmt {
907 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
908 let result = match self.node {
909 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
910 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
911 let suffix = if semicolon_for_stmt(context, self) {
920 ast::StmtKind::Expr(_) => ExprType::SubExpression,
921 ast::StmtKind::Semi(_) => ExprType::Statement,
925 try_opt!(shape.sub_width(suffix.len())),
926 ).map(|s| s + suffix)
928 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
930 result.and_then(|res| {
931 recover_comment_removed(res, self.span, context, shape)
936 // Rewrite condition if the given expression has one.
937 fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
939 ast::ExprKind::Match(ref cond, _) => {
941 let cond_shape = match context.config.control_style() {
942 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
943 Style::Rfc => try_opt!(shape.offset_left(8)),
945 cond.rewrite(context, cond_shape)
947 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
948 stmt_expr(&block.stmts[0]).and_then(|e| rewrite_cond(context, e, shape))
950 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
952 String::from("\n") + &shape.indent.block_only().to_string(context.config);
954 .rewrite_cond(context, shape, &alt_block_sep)
955 .and_then(|rw| Some(rw.0))
960 // Abstraction over control flow expressions
962 struct ControlFlow<'a> {
963 cond: Option<&'a ast::Expr>,
964 block: &'a ast::Block,
965 else_block: Option<&'a ast::Expr>,
966 label: Option<ast::SpannedIdent>,
967 pat: Option<&'a ast::Pat>,
971 allow_single_line: bool,
972 // True if this is an `if` expression in an `else if` :-( hacky
977 fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'a>> {
979 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
983 else_block.as_ref().map(|e| &**e),
984 expr_type == ExprType::SubExpression,
988 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
989 Some(ControlFlow::new_if(
993 else_block.as_ref().map(|e| &**e),
994 expr_type == ExprType::SubExpression,
999 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
1000 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
1002 ast::ExprKind::Loop(ref block, label) => {
1003 Some(ControlFlow::new_loop(block, label, expr.span))
1005 ast::ExprKind::While(ref cond, ref block, label) => {
1006 Some(ControlFlow::new_while(None, cond, block, label, expr.span))
1008 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
1009 ControlFlow::new_while(Some(pat), cond, block, label, expr.span),
1015 impl<'a> ControlFlow<'a> {
1017 cond: &'a ast::Expr,
1018 pat: Option<&'a ast::Pat>,
1019 block: &'a ast::Block,
1020 else_block: Option<&'a ast::Expr>,
1021 allow_single_line: bool,
1024 ) -> ControlFlow<'a> {
1028 else_block: else_block,
1032 matcher: match pat {
1037 allow_single_line: allow_single_line,
1038 nested_if: nested_if,
1044 block: &'a ast::Block,
1045 label: Option<ast::SpannedIdent>,
1047 ) -> ControlFlow<'a> {
1057 allow_single_line: false,
1064 pat: Option<&'a ast::Pat>,
1065 cond: &'a ast::Expr,
1066 block: &'a ast::Block,
1067 label: Option<ast::SpannedIdent>,
1069 ) -> ControlFlow<'a> {
1077 matcher: match pat {
1082 allow_single_line: false,
1090 cond: &'a ast::Expr,
1091 block: &'a ast::Block,
1092 label: Option<ast::SpannedIdent>,
1094 ) -> ControlFlow<'a> {
1104 allow_single_line: false,
1110 fn rewrite_single_line(
1113 context: &RewriteContext,
1115 ) -> Option<String> {
1116 assert!(self.allow_single_line);
1117 let else_block = try_opt!(self.else_block);
1118 let fixed_cost = self.keyword.len() + " { } else { }".len();
1120 if let ast::ExprKind::Block(ref else_node) = else_block.node {
1121 if !is_simple_block(self.block, context.codemap) ||
1122 !is_simple_block(else_node, context.codemap) ||
1123 pat_expr_str.contains('\n')
1128 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
1129 let expr = &self.block.stmts[0];
1130 let if_str = try_opt!(expr.rewrite(
1132 Shape::legacy(new_width, Indent::empty()),
1135 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
1136 let else_expr = &else_node.stmts[0];
1138 try_opt!(else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
1140 if if_str.contains('\n') || else_str.contains('\n') {
1144 let result = format!(
1145 "{} {} {{ {} }} else {{ {} }}",
1152 if result.len() <= width {
1153 return Some(result);
1161 impl<'a> ControlFlow<'a> {
1164 context: &RewriteContext,
1166 alt_block_sep: &str,
1167 ) -> Option<(String, usize)> {
1168 let constr_shape = if self.nested_if {
1169 // We are part of an if-elseif-else chain. Our constraints are tightened.
1170 // 7 = "} else " .len()
1171 try_opt!(shape.shrink_left(7))
1176 let label_string = rewrite_label(self.label);
1177 // 1 = space after keyword.
1178 let offset = self.keyword.len() + label_string.len() + 1;
1180 let pat_expr_string = match self.cond {
1182 let mut cond_shape = match context.config.control_style() {
1183 Style::Legacy => try_opt!(constr_shape.shrink_left(offset)),
1184 Style::Rfc => try_opt!(constr_shape.offset_left(offset)),
1186 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1188 cond_shape = try_opt!(cond_shape.sub_width(2));
1191 try_opt!(rewrite_pat_expr(
1201 None => String::new(),
1204 let force_newline_brace = context.config.control_style() == Style::Rfc &&
1205 pat_expr_string.contains('\n') &&
1206 !last_line_extendable(&pat_expr_string);
1208 // Try to format if-else on single line.
1209 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1210 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1212 if let Some(cond_str) = trial {
1213 if cond_str.len() <= context.config.single_line_if_else_max_width() {
1214 return Some((cond_str, 0));
1219 let cond_span = if let Some(cond) = self.cond {
1222 mk_sp(self.block.span.lo, self.block.span.lo)
1225 // for event in event
1226 let between_kwd_cond = mk_sp(
1227 context.codemap.span_after(self.span, self.keyword.trim()),
1230 |p| if self.matcher.is_empty() {
1233 context.codemap.span_before(self.span, self.matcher.trim())
1238 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1240 let after_cond_comment =
1241 extract_comment(mk_sp(cond_span.hi, self.block.span.lo), context, shape);
1243 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1245 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine ||
1253 let used_width = if pat_expr_string.contains('\n') {
1254 last_line_width(&pat_expr_string)
1256 // 2 = spaces after keyword and condition.
1257 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1265 between_kwd_cond_comment.as_ref().map_or(
1266 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1274 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1281 impl<'a> Rewrite for ControlFlow<'a> {
1282 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1283 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1286 String::from("\n") + &shape.indent.block_only().to_string(context.config);
1287 let (cond_str, used_width) = try_opt!(self.rewrite_cond(context, shape, &alt_block_sep));
1288 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1289 if used_width == 0 {
1290 return Some(cond_str);
1293 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1294 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1295 // we should avoid the single line case.
1296 let block_width = if self.else_block.is_some() || self.nested_if {
1301 let block_shape = Shape {
1305 let mut block_context = context.clone();
1306 block_context.is_if_else_block = self.else_block.is_some();
1307 let block_str = try_opt!(rewrite_block_with_visitor(
1314 let mut result = format!("{}{}", cond_str, block_str);
1316 if let Some(else_block) = self.else_block {
1317 let shape = Shape::indented(shape.indent, context.config);
1318 let mut last_in_chain = false;
1319 let rewrite = match else_block.node {
1320 // If the else expression is another if-else expression, prevent it
1321 // from being formatted on a single line.
1322 // Note how we're passing the original shape, as the
1323 // cost of "else" should not cascade.
1324 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1325 ControlFlow::new_if(
1329 next_else_block.as_ref().map(|e| &**e),
1332 mk_sp(else_block.span.lo, self.span.hi),
1333 ).rewrite(context, shape)
1335 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1336 ControlFlow::new_if(
1340 next_else_block.as_ref().map(|e| &**e),
1343 mk_sp(else_block.span.lo, self.span.hi),
1344 ).rewrite(context, shape)
1347 last_in_chain = true;
1348 // When rewriting a block, the width is only used for single line
1349 // blocks, passing 1 lets us avoid that.
1350 let else_shape = Shape {
1351 width: min(1, shape.width),
1354 format_expr(else_block, ExprType::Statement, context, else_shape)
1358 let between_kwd_else_block = mk_sp(
1362 .span_before(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1364 let between_kwd_else_block_comment =
1365 extract_comment(between_kwd_else_block, context, shape);
1367 let after_else = mk_sp(
1370 .span_after(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1373 let after_else_comment = extract_comment(after_else, context, shape);
1375 let between_sep = match context.config.control_brace_style() {
1376 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1379 ControlBraceStyle::AlwaysSameLine => " ",
1381 let after_sep = match context.config.control_brace_style() {
1382 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1389 between_kwd_else_block_comment
1391 .map_or(between_sep, |s| &**s),
1392 after_else_comment.as_ref().map_or(after_sep, |s| &**s)
1395 result.push_str(&try_opt!(rewrite));
1402 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
1404 Some(ident) => format!("{}: ", ident.node),
1405 None => "".to_owned(),
1409 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1410 let comment_str = context.snippet(span);
1411 if contains_comment(&comment_str) {
1412 let comment = try_opt!(rewrite_comment(
1419 "\n{indent}{}\n{indent}",
1421 indent = shape.indent.to_string(context.config)
1428 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1429 let snippet = codemap.span_to_snippet(block.span).unwrap();
1430 contains_comment(&snippet)
1433 // Checks that a block contains no statements, an expression and no comments.
1434 // FIXME: incorrectly returns false when comment is contained completely within
1436 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1437 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) &&
1438 !block_contains_comment(block, codemap))
1441 /// Checks whether a block contains at most one statement or expression, and no comments.
1442 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1443 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1446 /// Checks whether a block contains no statements, expressions, or comments.
1447 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1448 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1451 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1453 ast::StmtKind::Expr(..) => true,
1458 fn is_unsafe_block(block: &ast::Block) -> bool {
1459 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1466 // inter-match-arm-comment-rules:
1467 // - all comments following a match arm before the start of the next arm
1468 // are about the second arm
1469 fn rewrite_match_arm_comment(
1470 context: &RewriteContext,
1473 arm_indent_str: &str,
1474 ) -> Option<String> {
1475 // The leading "," is not part of the arm-comment
1476 let missed_str = match missed_str.find_uncommented(",") {
1477 Some(n) => &missed_str[n + 1..],
1478 None => &missed_str[..],
1481 let mut result = String::new();
1482 // any text not preceeded by a newline is pushed unmodified to the block
1483 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
1484 result.push_str(&missed_str[..first_brk]);
1485 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
1487 let first = missed_str
1488 .find(|c: char| !c.is_whitespace())
1489 .unwrap_or(missed_str.len());
1490 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
1491 // Excessive vertical whitespace before comment should be preserved
1492 // FIXME handle vertical whitespace better
1495 let missed_str = missed_str[first..].trim();
1496 if !missed_str.is_empty() {
1497 let comment = try_opt!(rewrite_comment(&missed_str, false, shape, context.config));
1499 result.push_str(arm_indent_str);
1500 result.push_str(&comment);
1507 context: &RewriteContext,
1512 ) -> Option<String> {
1513 if arms.is_empty() {
1518 let cond_shape = match context.config.control_style() {
1519 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
1520 Style::Rfc => try_opt!(shape.offset_left(8)),
1522 let cond_str = try_opt!(cond.rewrite(context, cond_shape));
1523 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1524 let block_sep = match context.config.control_brace_style() {
1525 ControlBraceStyle::AlwaysNextLine => alt_block_sep.as_str(),
1530 "match {}{}{{{}\n{}}}",
1533 try_opt!(rewrite_match_arms(context, arms, shape, span, cond.span.hi)),
1534 shape.indent.to_string(context.config),
1538 fn arm_comma(config: &Config, body: &ast::Expr) -> &'static str {
1539 if config.match_block_trailing_comma() {
1541 } else if let ast::ExprKind::Block(ref block) = body.node {
1542 if let ast::BlockCheckMode::Default = block.rules {
1552 fn rewrite_match_pattern(
1553 context: &RewriteContext,
1554 pats: &Vec<ptr::P<ast::Pat>>,
1555 guard: &Option<ptr::P<ast::Expr>>,
1557 ) -> Option<String> {
1560 let pat_shape = try_opt!(shape.sub_width(5));
1562 let pat_strs = try_opt!(
1564 .map(|p| p.rewrite(context, pat_shape))
1565 .collect::<Option<Vec<_>>>()
1568 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1569 let tactic = definitive_tactic(&items, ListTactic::HorizontalVertical, pat_shape.width);
1570 let fmt = ListFormatting {
1573 trailing_separator: SeparatorTactic::Never,
1575 ends_with_newline: false,
1576 config: context.config,
1578 let pats_str = try_opt!(write_list(&items, &fmt));
1581 let guard_str = try_opt!(rewrite_guard(
1585 trimmed_last_line_width(&pats_str),
1588 Some(format!("{}{}", pats_str, guard_str))
1591 fn rewrite_match_arms(
1592 context: &RewriteContext,
1596 cond_end_pos: BytePos,
1597 ) -> Option<String> {
1598 let mut result = String::new();
1600 let arm_shape = if context.config.indent_match_arms() {
1601 shape.block_indent(context.config.tab_spaces())
1603 shape.block_indent(0)
1604 }.with_max_width(context.config);
1605 let arm_indent_str = arm_shape.indent.to_string(context.config);
1607 let open_brace_pos = context
1609 .span_after(mk_sp(cond_end_pos, arms[0].span().lo), "{");
1611 let arm_num = arms.len();
1612 for (i, arm) in arms.iter().enumerate() {
1613 // Make sure we get the stuff between arms.
1614 let missed_str = if i == 0 {
1615 context.snippet(mk_sp(open_brace_pos, arm.span().lo))
1617 context.snippet(mk_sp(arms[i - 1].span().hi, arm.span().lo))
1619 let comment = try_opt!(rewrite_match_arm_comment(
1625 result.push_str(&comment);
1627 result.push_str(&arm_indent_str);
1629 let arm_str = rewrite_match_arm(context, arm, arm_shape);
1630 if let Some(ref arm_str) = arm_str {
1631 // Trim the trailing comma if necessary.
1632 if i == arm_num - 1 && context.config.trailing_comma() == SeparatorTactic::Never &&
1633 arm_str.ends_with(',')
1635 result.push_str(&arm_str[0..arm_str.len() - 1])
1637 result.push_str(arm_str)
1640 // We couldn't format the arm, just reproduce the source.
1641 let snippet = context.snippet(arm.span());
1642 result.push_str(&snippet);
1643 if context.config.trailing_comma() != SeparatorTactic::Never {
1644 result.push_str(arm_comma(context.config, &arm.body))
1648 // BytePos(1) = closing match brace.
1649 let last_span = mk_sp(arms[arms.len() - 1].span().hi, span.hi - BytePos(1));
1650 let last_comment = context.snippet(last_span);
1651 let comment = try_opt!(rewrite_match_arm_comment(
1657 result.push_str(&comment);
1662 fn rewrite_match_arm(context: &RewriteContext, arm: &ast::Arm, shape: Shape) -> Option<String> {
1663 let attr_str = if !arm.attrs.is_empty() {
1664 if contains_skip(&arm.attrs) {
1669 try_opt!(arm.attrs.rewrite(context, shape)),
1670 shape.indent.to_string(context.config)
1675 let pats_str = try_opt!(rewrite_match_pattern(context, &arm.pats, &arm.guard, shape));
1676 let pats_str = attr_str + &pats_str;
1677 rewrite_match_body(context, &arm.body, &pats_str, shape, arm.guard.is_some())
1680 fn rewrite_match_body(
1681 context: &RewriteContext,
1682 body: &ptr::P<ast::Expr>,
1686 ) -> Option<String> {
1687 let (extend, body) = match body.node {
1688 ast::ExprKind::Block(ref block)
1689 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) => {
1690 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1691 (expr.can_be_overflowed(context, 1), &**expr)
1696 _ => (body.can_be_overflowed(context, 1), &**body),
1699 let comma = arm_comma(&context.config, body);
1700 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1701 let alt_block_sep = alt_block_sep.as_str();
1702 let is_block = if let ast::ExprKind::Block(..) = body.node {
1708 let combine_orig_body = |body_str: &str| {
1709 let block_sep = match context.config.control_brace_style() {
1710 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
1711 _ if has_guard && pats_str.contains('\n') && is_block && body_str != "{}" => {
1717 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
1720 let combine_next_line_body = |body_str: &str| {
1721 let indent_str = shape
1723 .block_indent(context.config)
1724 .to_string(context.config);
1725 let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1726 let comma = if context.config.match_block_trailing_comma() {
1733 format!("\n{}}}{}", shape.indent.to_string(context.config), comma),
1736 ("", String::from(","))
1739 let block_sep = match context.config.control_brace_style() {
1740 ControlBraceStyle::AlwaysNextLine => format!("{}{}\n", alt_block_sep, body_prefix),
1741 _ if body_prefix.is_empty() => "\n".to_owned(),
1742 _ => " ".to_owned() + body_prefix + "\n",
1754 // Let's try and get the arm body on the same line as the condition.
1756 let orig_arm_shape = shape
1757 .offset_left(extra_offset(&pats_str, shape) + 4)
1758 .and_then(|shape| shape.sub_width(comma.len()));
1759 let orig_body = if let Some(arm_shape) = orig_arm_shape {
1760 let rewrite = nop_block_collapse(
1761 format_expr(body, ExprType::Statement, context, arm_shape),
1767 if ((!body_str.contains('\n')) && first_line_width(body_str) <= arm_shape.width) ||
1770 return combine_orig_body(body_str);
1777 let orig_budget = orig_arm_shape.map_or(0, |shape| shape.width);
1779 // Try putting body on the next line and see if it looks better.
1780 let next_line_body_shape =
1781 Shape::indented(shape.indent.block_indent(context.config), context.config);
1782 let next_line_body = nop_block_collapse(
1783 format_expr(body, ExprType::Statement, context, next_line_body_shape),
1784 next_line_body_shape.width,
1786 match (orig_body, next_line_body) {
1787 (Some(ref orig_str), Some(ref next_line_str))
1788 if prefer_next_line(orig_str, next_line_str) => combine_next_line_body(next_line_str),
1789 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
1790 combine_orig_body(orig_str)
1792 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
1793 combine_next_line_body(next_line_str)
1795 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
1796 (None, None) => None,
1797 (Some(ref orig_str), _) => combine_orig_body(orig_str),
1801 // The `if ...` guard on a match arm.
1803 context: &RewriteContext,
1804 guard: &Option<ptr::P<ast::Expr>>,
1806 // The amount of space used up on this line for the pattern in
1807 // the arm (excludes offset).
1808 pattern_width: usize,
1809 ) -> Option<String> {
1810 if let Some(ref guard) = *guard {
1811 // First try to fit the guard string on the same line as the pattern.
1812 // 4 = ` if `, 5 = ` => {`
1813 let cond_shape = shape
1814 .offset_left(pattern_width + 4)
1815 .and_then(|s| s.sub_width(5));
1816 if let Some(cond_shape) = cond_shape {
1817 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1818 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
1819 return Some(format!(" if {}", cond_str));
1824 // Not enough space to put the guard after the pattern, try a newline.
1825 // 3 = `if `, 5 = ` => {`
1826 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
1828 .and_then(|s| s.sub_width(5));
1829 if let Some(cond_shape) = cond_shape {
1830 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1831 return Some(format!(
1833 cond_shape.indent.to_string(context.config),
1845 fn rewrite_pat_expr(
1846 context: &RewriteContext,
1847 pat: Option<&ast::Pat>,
1850 // Connecting piece between pattern and expression,
1851 // *without* trailing space.
1855 ) -> Option<String> {
1856 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1857 if let Some(pat) = pat {
1858 let matcher = if matcher.is_empty() {
1861 format!("{} ", matcher)
1864 try_opt!(try_opt!(shape.offset_left(matcher.len())).sub_width(connector.len()));
1865 let pat_string = try_opt!(pat.rewrite(context, pat_shape));
1866 let result = format!("{}{}{}", matcher, pat_string, connector);
1867 return rewrite_assign_rhs(context, result, expr, shape);
1870 let expr_rw = expr.rewrite(context, shape);
1871 // The expression may (partially) fit on the current line.
1872 // We do not allow splitting between `if` and condition.
1873 if keyword == "if" || expr_rw.is_some() {
1877 // The expression won't fit on the current line, jump to next.
1878 let nested_shape = shape
1879 .block_indent(context.config.tab_spaces())
1880 .with_max_width(context.config);
1881 let nested_indent_str = nested_shape.indent.to_string(context.config);
1882 expr.rewrite(context, nested_shape)
1883 .map(|expr_rw| format!("\n{}{}", nested_indent_str, expr_rw))
1886 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1887 let string_lit = context.snippet(span);
1889 if !context.config.format_strings() && !context.config.force_format_strings() {
1894 .all(|line| line.ends_with('\\'))
1896 let new_indent = shape.visual_indent(1).indent;
1897 return Some(String::from(
1901 new_indent.to_string(context.config) + line.trim_left()
1903 .collect::<Vec<_>>()
1908 return Some(string_lit);
1912 if !context.config.force_format_strings() &&
1913 !string_requires_rewrite(context, span, &string_lit, shape)
1915 return Some(string_lit);
1918 let fmt = StringFormat {
1925 config: context.config,
1928 // Remove the quote characters.
1929 let str_lit = &string_lit[1..string_lit.len() - 1];
1931 rewrite_string(str_lit, &fmt)
1934 fn string_requires_rewrite(
1935 context: &RewriteContext,
1940 if context.codemap.lookup_char_pos(span.lo).col.0 != shape.indent.width() {
1944 for (i, line) in string.lines().enumerate() {
1946 if line.len() > shape.width {
1950 if line.len() > shape.width + shape.indent.width() {
1959 pub fn rewrite_call_with_binary_search<R>(
1960 context: &RewriteContext,
1962 args: &[&ast::Expr],
1969 let force_trailing_comma = if context.inside_macro {
1970 span_ends_with_comma(context, span)
1974 let closure = |callee_max_width| {
1975 // FIXME using byte lens instead of char lens (and probably all over the
1977 let callee_shape = Shape {
1978 width: callee_max_width,
1981 let callee_str = callee
1982 .rewrite(context, callee_shape)
1983 .ok_or(Ordering::Greater)?;
1991 context.config.fn_call_width(),
1992 force_trailing_comma,
1996 binary_search(1, shape.width, closure)
1999 pub fn rewrite_call(
2000 context: &RewriteContext,
2002 args: &[ptr::P<ast::Expr>],
2005 ) -> Option<String> {
2006 let force_trailing_comma = if context.inside_macro {
2007 span_ends_with_comma(context, span)
2014 &args.iter().map(|x| &**x).collect::<Vec<_>>(),
2017 context.config.fn_call_width(),
2018 force_trailing_comma,
2022 pub fn rewrite_call_inner<'a, T>(
2023 context: &RewriteContext,
2028 args_max_width: usize,
2029 force_trailing_comma: bool,
2030 ) -> Result<String, Ordering>
2032 T: Rewrite + Spanned + ToExpr + 'a,
2034 // 2 = `( `, 1 = `(`
2035 let paren_overhead = if context.config.spaces_within_parens() {
2040 let used_width = extra_offset(&callee_str, shape);
2041 let one_line_width = shape
2043 .checked_sub(used_width + 2 * paren_overhead)
2044 .ok_or(Ordering::Greater)?;
2046 let nested_shape = shape_from_fn_call_style(
2049 used_width + 2 * paren_overhead,
2050 used_width + paren_overhead,
2051 ).ok_or(Ordering::Greater)?;
2053 let span_lo = context.codemap.span_after(span, "(");
2054 let args_span = mk_sp(span_lo, span.hi);
2056 let (extendable, list_str) = rewrite_call_args(
2063 force_trailing_comma,
2064 ).or_else(|| if context.use_block_indent() {
2070 shape.block().indent.block_indent(context.config),
2075 force_trailing_comma,
2080 .ok_or(Ordering::Less)?;
2082 if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
2083 let mut new_context = context.clone();
2084 new_context.use_block = true;
2085 return rewrite_call_inner(
2092 force_trailing_comma,
2096 let args_shape = shape
2097 .sub_width(last_line_width(&callee_str))
2098 .ok_or(Ordering::Less)?;
2102 wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2106 fn need_block_indent(s: &str, shape: Shape) -> bool {
2107 s.lines().skip(1).any(|s| {
2108 s.find(|c| !char::is_whitespace(c))
2109 .map_or(false, |w| w + 1 < shape.indent.width())
2113 fn rewrite_call_args<'a, T>(
2114 context: &RewriteContext,
2118 one_line_width: usize,
2119 args_max_width: usize,
2120 force_trailing_comma: bool,
2121 ) -> Option<(bool, String)>
2123 T: Rewrite + Spanned + ToExpr + 'a,
2125 let items = itemize_list(
2129 |item| item.span().lo,
2130 |item| item.span().hi,
2131 |item| item.rewrite(context, shape),
2135 let mut item_vec: Vec<_> = items.collect();
2137 // Try letting the last argument overflow to the next line with block
2138 // indentation. If its first line fits on one line with the other arguments,
2139 // we format the function arguments horizontally.
2140 let tactic = try_overflow_last_arg(
2149 let fmt = ListFormatting {
2152 trailing_separator: if force_trailing_comma {
2153 SeparatorTactic::Always
2154 } else if context.inside_macro || !context.use_block_indent() {
2155 SeparatorTactic::Never
2157 context.config.trailing_comma()
2160 ends_with_newline: context.use_block_indent() && tactic == DefinitiveListTactic::Vertical,
2161 config: context.config,
2164 write_list(&item_vec, &fmt).map(|args_str| {
2165 (tactic != DefinitiveListTactic::Vertical, args_str)
2169 fn try_overflow_last_arg<'a, T>(
2170 context: &RewriteContext,
2171 item_vec: &mut Vec<ListItem>,
2174 one_line_width: usize,
2175 args_max_width: usize,
2176 ) -> DefinitiveListTactic
2178 T: Rewrite + Spanned + ToExpr + 'a,
2180 let overflow_last = can_be_overflowed(&context, args);
2182 // Replace the last item with its first line to see if it fits with
2184 let (orig_last, placeholder) = if overflow_last {
2185 let mut context = context.clone();
2186 if let Some(expr) = args[args.len() - 1].to_expr() {
2188 ast::ExprKind::MethodCall(..) => context.force_one_line_chain = true,
2192 last_arg_shape(&context, &item_vec, shape, args_max_width)
2193 .map_or((None, None), |arg_shape| {
2194 rewrite_last_arg_with_overflow(
2197 &mut item_vec[args.len() - 1],
2205 let tactic = definitive_tactic(
2207 ListTactic::LimitedHorizontalVertical(args_max_width),
2211 // Replace the stub with the full overflowing last argument if the rewrite
2212 // succeeded and its first line fits with the other arguments.
2213 match (overflow_last, tactic, placeholder) {
2214 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2215 item_vec[args.len() - 1].item = placeholder;
2218 item_vec[args.len() - 1].item = orig_last;
2227 context: &RewriteContext,
2228 items: &Vec<ListItem>,
2230 args_max_width: usize,
2231 ) -> Option<Shape> {
2232 let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
2233 acc + i.item.as_ref().map_or(0, |s| first_line_width(&s))
2235 let max_width = min(args_max_width, shape.width);
2236 let arg_indent = if context.use_block_indent() {
2237 shape.block().indent.block_unindent(context.config)
2239 shape.block().indent
2242 width: try_opt!(max_width.checked_sub(overhead)),
2248 // Rewriting closure which is placed at the end of the function call's arg.
2249 // Returns `None` if the reformatted closure 'looks bad'.
2250 fn rewrite_last_closure(
2251 context: &RewriteContext,
2254 ) -> Option<String> {
2255 if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
2256 let body = match body.node {
2257 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
2258 stmt_expr(&block.stmts[0]).unwrap_or(body)
2262 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
2270 // If the closure goes multi line before its body, do not overflow the closure.
2271 if prefix.contains('\n') {
2274 let body_shape = try_opt!(shape.offset_left(extra_offset));
2275 // When overflowing the closure which consists of a single control flow expression,
2276 // force to use block if its condition uses multi line.
2277 if rewrite_cond(context, body, body_shape)
2278 .map(|cond| cond.contains('\n'))
2281 return rewrite_closure_with_block(context, body_shape, &prefix, body);
2284 // Seems fine, just format the closure in usual manner.
2285 return expr.rewrite(context, shape);
2290 fn rewrite_last_arg_with_overflow<'a, T>(
2291 context: &RewriteContext,
2293 last_item: &mut ListItem,
2295 ) -> (Option<String>, Option<String>)
2297 T: Rewrite + Spanned + ToExpr + 'a,
2299 let last_arg = args[args.len() - 1];
2300 let rewrite = if let Some(expr) = last_arg.to_expr() {
2302 // When overflowing the closure which consists of a single control flow expression,
2303 // force to use block if its condition uses multi line.
2304 ast::ExprKind::Closure(..) => {
2305 // If the argument consists of multiple closures, we do not overflow
2306 // the last closure.
2307 if args.len() > 1 &&
2311 .filter_map(|arg| arg.to_expr())
2312 .any(|expr| match expr.node {
2313 ast::ExprKind::Closure(..) => true,
2318 rewrite_last_closure(context, expr, shape)
2321 _ => expr.rewrite(context, shape),
2324 last_arg.rewrite(context, shape)
2326 let orig_last = last_item.item.clone();
2328 if let Some(rewrite) = rewrite {
2329 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2330 last_item.item = rewrite_first_line;
2331 (orig_last, Some(rewrite))
2337 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2339 T: Rewrite + Spanned + ToExpr + 'a,
2342 .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2345 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2347 ast::ExprKind::Match(..) => {
2348 (context.use_block_indent() && args_len == 1) ||
2349 (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
2351 ast::ExprKind::If(..) |
2352 ast::ExprKind::IfLet(..) |
2353 ast::ExprKind::ForLoop(..) |
2354 ast::ExprKind::Loop(..) |
2355 ast::ExprKind::While(..) |
2356 ast::ExprKind::WhileLet(..) => {
2357 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2359 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
2360 context.use_block_indent() ||
2361 context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
2363 ast::ExprKind::Array(..) |
2364 ast::ExprKind::Call(..) |
2365 ast::ExprKind::Mac(..) |
2366 ast::ExprKind::MethodCall(..) |
2367 ast::ExprKind::Struct(..) |
2368 ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2369 ast::ExprKind::AddrOf(_, ref expr) |
2370 ast::ExprKind::Box(ref expr) |
2371 ast::ExprKind::Try(ref expr) |
2372 ast::ExprKind::Unary(_, ref expr) |
2373 ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2378 pub fn wrap_args_with_parens(
2379 context: &RewriteContext,
2381 is_extendable: bool,
2383 nested_shape: Shape,
2385 if !context.use_block_indent() ||
2386 (context.inside_macro && !args_str.contains('\n') &&
2387 args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2389 if context.config.spaces_within_parens() && args_str.len() > 0 {
2390 format!("( {} )", args_str)
2392 format!("({})", args_str)
2397 nested_shape.indent.to_string(context.config),
2399 shape.block().indent.to_string(context.config)
2404 fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2405 let snippet = context.snippet(span);
2407 .trim_right_matches(|c: char| c == ')' || c.is_whitespace())
2411 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2412 debug!("rewrite_paren, shape: {:?}", shape);
2413 let paren_overhead = paren_overhead(context);
2414 let sub_shape = try_opt!(shape.sub_width(paren_overhead / 2)).visual_indent(paren_overhead / 2);
2416 let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && s.len() > 0 {
2417 format!("( {} )", s)
2422 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2423 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2425 if subexpr_str.contains('\n') {
2426 Some(paren_wrapper(&subexpr_str))
2428 if subexpr_str.len() + paren_overhead <= shape.width {
2429 Some(paren_wrapper(&subexpr_str))
2431 let sub_shape = try_opt!(shape.offset_left(2));
2432 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2433 Some(paren_wrapper(&subexpr_str))
2441 context: &RewriteContext,
2443 ) -> Option<String> {
2444 let expr_str = try_opt!(expr.rewrite(context, shape));
2446 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
2452 let offset = last_line_width(&expr_str) + lbr.len();
2453 let rhs_overhead = shape.rhs_overhead(context.config);
2454 let index_shape = if expr_str.contains('\n') {
2455 Shape::legacy(context.config.max_width(), shape.indent)
2456 .offset_left(offset)
2457 .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
2459 shape.visual_indent(offset).sub_width(offset + rbr.len())
2461 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
2463 // Return if index fits in a single line.
2464 match orig_index_rw {
2465 Some(ref index_str) if !index_str.contains('\n') => {
2466 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2471 // Try putting index on the next line and see if it fits in a single line.
2472 let indent = shape.indent.block_indent(context.config);
2473 let index_shape = try_opt!(Shape::indented(indent, context.config).offset_left(lbr.len()));
2474 let index_shape = try_opt!(index_shape.sub_width(rbr.len() + rhs_overhead));
2475 let new_index_rw = index.rewrite(context, index_shape);
2476 match (orig_index_rw, new_index_rw) {
2477 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
2480 indent.to_string(&context.config),
2485 (None, Some(ref new_index_str)) => Some(format!(
2488 indent.to_string(&context.config),
2493 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2498 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2503 fields.iter().all(|field| !field.is_shorthand)
2506 fn rewrite_struct_lit<'a>(
2507 context: &RewriteContext,
2509 fields: &'a [ast::Field],
2510 base: Option<&'a ast::Expr>,
2513 ) -> Option<String> {
2514 debug!("rewrite_struct_lit: shape {:?}", shape);
2516 enum StructLitField<'a> {
2517 Regular(&'a ast::Field),
2518 Base(&'a ast::Expr),
2522 let path_shape = try_opt!(shape.sub_width(2));
2523 let path_str = try_opt!(rewrite_path(
2531 if fields.len() == 0 && base.is_none() {
2532 return Some(format!("{} {{}}", path_str));
2535 // Foo { a: Foo } - indent is +3, width is -5.
2536 let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
2538 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2539 let body_lo = context.codemap.span_after(span, "{");
2540 let fields_str = if struct_lit_can_be_aligned(fields, &base) &&
2541 context.config.struct_field_align_threshold() > 0
2543 try_opt!(rewrite_with_alignment(
2547 mk_sp(body_lo, span.hi),
2551 let field_iter = fields
2553 .map(StructLitField::Regular)
2554 .chain(base.into_iter().map(StructLitField::Base));
2556 let span_lo = |item: &StructLitField| match *item {
2557 StructLitField::Regular(field) => field.span().lo,
2558 StructLitField::Base(expr) => {
2559 let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
2560 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
2561 let pos = snippet.find_uncommented("..").unwrap();
2562 last_field_hi + BytePos(pos as u32)
2565 let span_hi = |item: &StructLitField| match *item {
2566 StructLitField::Regular(field) => field.span().hi,
2567 StructLitField::Base(expr) => expr.span.hi,
2569 let rewrite = |item: &StructLitField| match *item {
2570 StructLitField::Regular(field) => {
2571 // The 1 taken from the v_budget is for the comma.
2572 rewrite_field(context, field, try_opt!(v_shape.sub_width(1)), 0)
2574 StructLitField::Base(expr) => {
2576 expr.rewrite(context, try_opt!(v_shape.shrink_left(2)))
2577 .map(|s| format!("..{}", s))
2581 let items = itemize_list(
2591 let item_vec = items.collect::<Vec<_>>();
2593 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2594 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2595 let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2597 try_opt!(write_list(&item_vec, &fmt))
2600 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2601 Some(format!("{} {{{}}}", path_str, fields_str))
2603 // FIXME if context.config.struct_lit_style() == Visual, but we run out
2604 // of space, we should fall back to BlockIndent.
2607 pub fn wrap_struct_field(
2608 context: &RewriteContext,
2611 nested_shape: Shape,
2612 one_line_width: usize,
2614 if context.config.struct_lit_style() == IndentStyle::Block &&
2615 (fields_str.contains('\n') ||
2616 context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti ||
2617 fields_str.len() > one_line_width)
2621 nested_shape.indent.to_string(context.config),
2623 shape.indent.to_string(context.config)
2626 // One liner or visual indent.
2627 format!(" {} ", fields_str)
2631 pub fn struct_lit_field_separator(config: &Config) -> &str {
2633 config.space_before_struct_lit_field_colon(),
2634 config.space_after_struct_lit_field_colon(),
2638 pub fn rewrite_field(
2639 context: &RewriteContext,
2642 prefix_max_width: usize,
2643 ) -> Option<String> {
2644 if contains_skip(&field.attrs) {
2646 context.snippet(field.span()),
2647 context.config.max_width(),
2651 let name = &field.ident.node.to_string();
2652 if field.is_shorthand {
2653 Some(name.to_string())
2655 let mut separator = String::from(struct_lit_field_separator(context.config));
2656 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2657 separator.push(' ');
2659 let overhead = name.len() + separator.len();
2660 let expr_shape = try_opt!(shape.offset_left(overhead));
2661 let expr = field.expr.rewrite(context, expr_shape);
2663 let mut attrs_str = try_opt!(field.attrs.rewrite(context, shape));
2664 if !attrs_str.is_empty() {
2665 attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2669 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2671 let expr_offset = shape.indent.block_indent(context.config);
2674 .rewrite(context, Shape::indented(expr_offset, context.config));
2680 expr_offset.to_string(&context.config),
2689 fn shape_from_fn_call_style(
2690 context: &RewriteContext,
2694 ) -> Option<Shape> {
2695 if context.use_block_indent() {
2699 .block_indent(context.config.tab_spaces())
2700 .with_max_width(context.config)
2703 shape.visual_indent(offset).sub_width(overhead)
2707 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2708 context: &RewriteContext,
2714 T: Rewrite + Spanned + ToExpr + 'a,
2716 let mut items = items.iter();
2717 // In case of length 1, need a trailing comma
2718 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2719 if items.len() == 1 {
2721 let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
2722 return items.next().unwrap().rewrite(context, nested_shape).map(
2723 |s| if context.config.spaces_within_parens() {
2724 format!("( {}, )", s)
2731 let list_lo = context.codemap.span_after(span, "(");
2732 let nested_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
2733 let items = itemize_list(
2737 |item| item.span().lo,
2738 |item| item.span().hi,
2739 |item| item.rewrite(context, nested_shape),
2741 span.hi - BytePos(1),
2743 let item_vec: Vec<_> = items.collect();
2744 let tactic = definitive_tactic(
2746 ListTactic::HorizontalVertical,
2749 let fmt = ListFormatting {
2752 trailing_separator: SeparatorTactic::Never,
2754 ends_with_newline: false,
2755 config: context.config,
2757 let list_str = try_opt!(write_list(&item_vec, &fmt));
2759 if context.config.spaces_within_parens() && list_str.len() > 0 {
2760 Some(format!("( {} )", list_str))
2762 Some(format!("({})", list_str))
2766 pub fn rewrite_tuple<'a, T>(
2767 context: &RewriteContext,
2773 T: Rewrite + Spanned + ToExpr + 'a,
2775 debug!("rewrite_tuple {:?}", shape);
2776 if context.use_block_indent() {
2777 // We use the same rule as funcation call for rewriting tuple.
2778 let force_trailing_comma = if context.inside_macro {
2779 span_ends_with_comma(context, span)
2789 context.config.fn_call_width(),
2790 force_trailing_comma,
2793 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2797 pub fn rewrite_unary_prefix<R: Rewrite>(
2798 context: &RewriteContext,
2802 ) -> Option<String> {
2804 .rewrite(context, try_opt!(shape.offset_left(prefix.len())))
2805 .map(|r| format!("{}{}", prefix, r))
2808 // FIXME: this is probably not correct for multi-line Rewrites. we should
2809 // subtract suffix.len() from the last line budget, not the first!
2810 pub fn rewrite_unary_suffix<R: Rewrite>(
2811 context: &RewriteContext,
2815 ) -> Option<String> {
2817 .rewrite(context, try_opt!(shape.sub_width(suffix.len())))
2824 fn rewrite_unary_op(
2825 context: &RewriteContext,
2829 ) -> Option<String> {
2830 // For some reason, an UnOp is not spanned like BinOp!
2831 let operator_str = match *op {
2832 ast::UnOp::Deref => "*",
2833 ast::UnOp::Not => "!",
2834 ast::UnOp::Neg => "-",
2836 rewrite_unary_prefix(context, operator_str, expr, shape)
2839 fn rewrite_assignment(
2840 context: &RewriteContext,
2843 op: Option<&ast::BinOp>,
2845 ) -> Option<String> {
2846 let operator_str = match op {
2847 Some(op) => context.snippet(op.span),
2848 None => "=".to_owned(),
2851 // 1 = space between lhs and operator.
2852 let lhs_shape = try_opt!(shape.sub_width(operator_str.len() + 1));
2853 let lhs_str = format!(
2855 try_opt!(lhs.rewrite(context, lhs_shape)),
2859 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2862 // The left hand side must contain everything up to, and including, the
2863 // assignment operator.
2864 pub fn rewrite_assign_rhs<S: Into<String>>(
2865 context: &RewriteContext,
2869 ) -> Option<String> {
2870 let lhs = lhs.into();
2871 let last_line_width = last_line_width(&lhs) -
2872 if lhs.contains('\n') {
2873 shape.indent.width()
2877 // 1 = space between operator and rhs.
2878 let orig_shape = try_opt!(shape.offset_left(last_line_width + 1));
2879 let rhs = try_opt!(choose_rhs(
2883 ex.rewrite(context, orig_shape)
2889 context: &RewriteContext,
2892 orig_rhs: Option<String>,
2893 ) -> Option<String> {
2895 Some(ref new_str) if !new_str.contains('\n') => Some(format!(" {}", new_str)),
2897 // Expression did not fit on the same line as the identifier.
2898 // Try splitting the line and see if that works better.
2899 let new_shape = try_opt!(
2901 shape.block().indent.block_indent(context.config),
2903 ).sub_width(shape.rhs_overhead(context.config))
2905 let new_rhs = expr.rewrite(context, new_shape);
2906 let new_indent_str = &new_shape.indent.to_string(context.config);
2908 match (orig_rhs, new_rhs) {
2909 (Some(ref orig_rhs), Some(ref new_rhs)) if prefer_next_line(orig_rhs, new_rhs) => {
2910 Some(format!("\n{}{}", new_indent_str, new_rhs))
2912 (None, Some(ref new_rhs)) => Some(format!("\n{}{}", new_indent_str, new_rhs)),
2913 (None, None) => None,
2914 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2920 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {
2922 fn count_line_breaks(src: &str) -> usize {
2923 src.chars().filter(|&x| x == '\n').count()
2926 !next_line_rhs.contains('\n') ||
2927 count_line_breaks(orig_rhs) > count_line_breaks(next_line_rhs) + 1
2930 fn rewrite_expr_addrof(
2931 context: &RewriteContext,
2932 mutability: ast::Mutability,
2935 ) -> Option<String> {
2936 let operator_str = match mutability {
2937 ast::Mutability::Immutable => "&",
2938 ast::Mutability::Mutable => "&mut ",
2940 rewrite_unary_prefix(context, operator_str, expr, shape)
2944 fn to_expr(&self) -> Option<&ast::Expr>;
2945 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2948 impl ToExpr for ast::Expr {
2949 fn to_expr(&self) -> Option<&ast::Expr> {
2953 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2954 can_be_overflowed_expr(context, self, len)
2958 impl ToExpr for ast::Ty {
2959 fn to_expr(&self) -> Option<&ast::Expr> {
2963 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2964 can_be_overflowed_type(context, self, len)
2968 impl<'a> ToExpr for TuplePatField<'a> {
2969 fn to_expr(&self) -> Option<&ast::Expr> {
2973 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2974 can_be_overflowed_pat(context, self, len)
2978 impl<'a> ToExpr for ast::StructField {
2979 fn to_expr(&self) -> Option<&ast::Expr> {
2983 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {