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) => 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 if context.config.array_horizontal_layout_threshold() > 0 &&
505 items.len() > context.config.array_horizontal_layout_threshold()
507 tactic = DefinitiveListTactic::Mixed;
508 if context.config.array_layout() == IndentStyle::Block {
509 nested_shape = try_opt!(
511 .visual_indent(bracket_size)
512 .sub_width(bracket_size * 2)
517 let fmt = ListFormatting {
520 trailing_separator: if trailing_comma {
521 SeparatorTactic::Always
522 } else if context.inside_macro || context.config.array_layout() == IndentStyle::Visual {
523 SeparatorTactic::Never
525 SeparatorTactic::Vertical
528 ends_with_newline: false,
529 config: context.config,
531 let list_str = try_opt!(write_list(&items, &fmt));
533 let result = if context.config.array_layout() == IndentStyle::Visual ||
534 tactic != DefinitiveListTactic::Vertical
536 if context.config.spaces_within_square_brackets() && list_str.len() > 0 {
537 format!("[ {} ]", list_str)
539 format!("[{}]", list_str)
544 nested_shape.indent.to_string(context.config),
546 shape.block().indent.to_string(context.config)
553 // Return type is (prefix, extra_offset)
554 fn rewrite_closure_fn_decl(
555 capture: ast::CaptureBy,
556 fn_decl: &ast::FnDecl,
559 context: &RewriteContext,
561 ) -> Option<(String, usize)> {
562 let mover = if capture == ast::CaptureBy::Value {
567 // 4 = "|| {".len(), which is overconservative when the closure consists of
568 // a single expression.
569 let nested_shape = try_opt!(try_opt!(shape.shrink_left(mover.len())).sub_width(4));
572 let argument_offset = nested_shape.indent + 1;
573 let arg_shape = try_opt!(nested_shape.shrink_left(1)).visual_indent(0);
574 let ret_str = try_opt!(fn_decl.output.rewrite(context, arg_shape));
576 let arg_items = itemize_list(
578 fn_decl.inputs.iter(),
580 |arg| span_lo_for_arg(arg),
581 |arg| span_hi_for_arg(context, arg),
582 |arg| arg.rewrite(context, arg_shape),
583 context.codemap.span_after(span, "|"),
586 let item_vec = arg_items.collect::<Vec<_>>();
587 // 1 = space between arguments and return type.
588 let horizontal_budget = nested_shape
590 .checked_sub(ret_str.len() + 1)
592 let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
593 let arg_shape = match tactic {
594 DefinitiveListTactic::Horizontal => try_opt!(arg_shape.sub_width(ret_str.len() + 1)),
598 let fmt = ListFormatting {
601 trailing_separator: SeparatorTactic::Never,
603 ends_with_newline: false,
604 config: context.config,
606 let list_str = try_opt!(write_list(&item_vec, &fmt));
607 let mut prefix = format!("{}|{}|", mover, list_str);
608 // 1 = space between `|...|` and body.
609 let extra_offset = extra_offset(&prefix, shape) + 1;
611 if !ret_str.is_empty() {
612 if prefix.contains('\n') {
614 prefix.push_str(&argument_offset.to_string(context.config));
618 prefix.push_str(&ret_str);
621 Some((prefix, extra_offset))
624 // This functions is pretty messy because of the rules around closures and blocks:
625 // FIXME - the below is probably no longer true in full.
626 // * if there is a return type, then there must be braces,
627 // * given a closure with braces, whether that is parsed to give an inner block
628 // or not depends on if there is a return type and if there are statements
630 // * if the first expression in the body ends with a block (i.e., is a
631 // statement without needing a semi-colon), then adding or removing braces
632 // can change whether it is treated as an expression or statement.
634 capture: ast::CaptureBy,
635 fn_decl: &ast::FnDecl,
638 context: &RewriteContext,
640 ) -> Option<String> {
641 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
649 // 1 = space between `|...|` and body.
650 let body_shape = try_opt!(shape.offset_left(extra_offset));
652 if let ast::ExprKind::Block(ref block) = body.node {
653 // The body of the closure is an empty block.
654 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
655 return Some(format!("{} {{}}", prefix));
658 // Figure out if the block is necessary.
659 let needs_block = block.rules != ast::BlockCheckMode::Default ||
660 block.stmts.len() > 1 || context.inside_macro ||
661 block_contains_comment(block, context.codemap) ||
662 prefix.contains('\n');
664 let no_return_type = if let ast::FunctionRetTy::Default(_) = fn_decl.output {
669 if no_return_type && !needs_block {
670 // lock.stmts.len() == 1
671 if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
672 if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
679 // We need braces, but we might still prefer a one-liner.
680 let stmt = &block.stmts[0];
681 // 4 = braces and spaces.
682 if let Some(body_shape) = body_shape.sub_width(4) {
683 // Checks if rewrite succeeded and fits on a single line.
684 if let Some(rewrite) = and_one_line(stmt.rewrite(context, body_shape)) {
685 return Some(format!("{} {{ {} }}", prefix, rewrite));
690 // Either we require a block, or tried without and failed.
691 rewrite_closure_block(&block, &prefix, context, body_shape)
693 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
694 // The closure originally had a non-block expression, but we can't fit on
695 // one line, so we'll insert a block.
696 rewrite_closure_with_block(context, body_shape, &prefix, body)
701 // Rewrite closure with a single expression wrapping its body with block.
702 fn rewrite_closure_with_block(
703 context: &RewriteContext,
707 ) -> Option<String> {
708 let block = ast::Block {
711 id: ast::NodeId::new(0),
712 node: ast::StmtKind::Expr(ptr::P(body.clone())),
716 id: ast::NodeId::new(0),
717 rules: ast::BlockCheckMode::Default,
720 rewrite_closure_block(&block, prefix, context, shape)
723 // Rewrite closure with a single expression without wrapping its body with block.
724 fn rewrite_closure_expr(
727 context: &RewriteContext,
729 ) -> Option<String> {
730 let mut rewrite = expr.rewrite(context, shape);
731 if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
732 rewrite = and_one_line(rewrite);
734 rewrite.map(|rw| format!("{} {}", prefix, rw))
737 // Rewrite closure whose body is block.
738 fn rewrite_closure_block(
741 context: &RewriteContext,
743 ) -> Option<String> {
744 // Start with visual indent, then fall back to block indent if the
746 let block_threshold = context.config.closure_block_indent_threshold();
747 if block_threshold >= 0 {
748 if let Some(block_str) = block.rewrite(&context, shape) {
749 if block_str.matches('\n').count() <= block_threshold as usize &&
750 !need_block_indent(&block_str, shape)
752 if let Some(block_str) = block_str.rewrite(context, shape) {
753 return Some(format!("{} {}", prefix, block_str));
759 // The body of the closure is big enough to be block indented, that
760 // means we must re-format.
761 let block_shape = shape.block();
762 let block_str = try_opt!(block.rewrite(&context, block_shape));
763 Some(format!("{} {}", prefix, block_str))
766 fn and_one_line(x: Option<String>) -> Option<String> {
767 x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
770 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
771 debug!("nop_block_collapse {:?} {}", block_str, budget);
772 block_str.map(|block_str| {
773 if block_str.starts_with('{') && budget >= 2 &&
774 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
783 fn rewrite_empty_block(
784 context: &RewriteContext,
787 ) -> Option<String> {
788 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) &&
791 return Some("{}".to_owned());
794 // If a block contains only a single-line comment, then leave it on one line.
795 let user_str = context.snippet(block.span);
796 let user_str = user_str.trim();
797 if user_str.starts_with('{') && user_str.ends_with('}') {
798 let comment_str = user_str[1..user_str.len() - 1].trim();
799 if block.stmts.is_empty() && !comment_str.contains('\n') &&
800 !comment_str.starts_with("//") && comment_str.len() + 4 <= shape.width
802 return Some(format!("{{ {} }}", comment_str));
809 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
810 Some(match block.rules {
811 ast::BlockCheckMode::Unsafe(..) => {
812 let snippet = context.snippet(block.span);
813 let open_pos = try_opt!(snippet.find_uncommented("{"));
814 // Extract comment between unsafe and block start.
815 let trimmed = &snippet[6..open_pos].trim();
817 if !trimmed.is_empty() {
818 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
819 let budget = try_opt!(shape.width.checked_sub(9));
822 try_opt!(rewrite_comment(
825 Shape::legacy(budget, shape.indent + 7),
833 ast::BlockCheckMode::Default => String::new(),
837 fn rewrite_single_line_block(
838 context: &RewriteContext,
842 ) -> Option<String> {
843 if is_simple_block(block, context.codemap) {
844 let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
845 let expr_str = try_opt!(block.stmts[0].rewrite(context, expr_shape));
846 let result = format!("{}{{ {} }}", prefix, expr_str);
847 if result.len() <= shape.width && !result.contains('\n') {
854 fn rewrite_block_with_visitor(
855 context: &RewriteContext,
859 ) -> Option<String> {
860 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
864 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
865 visitor.block_indent = shape.indent;
866 visitor.is_if_else_block = context.is_if_else_block;
868 ast::BlockCheckMode::Unsafe(..) => {
869 let snippet = context.snippet(block.span);
870 let open_pos = try_opt!(snippet.find_uncommented("{"));
871 visitor.last_pos = block.span.lo + BytePos(open_pos as u32)
873 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo,
876 visitor.visit_block(block);
877 if visitor.failed && shape.indent.alignment != 0 {
880 Shape::indented(shape.indent.block_only(), context.config),
883 Some(format!("{}{}", prefix, visitor.buffer))
887 impl Rewrite for ast::Block {
888 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
889 // shape.width is used only for the single line case: either the empty block `{}`,
890 // or an unsafe expression `unsafe { e }`.
891 if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
895 let prefix = try_opt!(block_prefix(context, self, shape));
896 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
900 rewrite_block_with_visitor(context, &prefix, self, shape)
904 impl Rewrite for ast::Stmt {
905 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
906 let result = match self.node {
907 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
908 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
909 let suffix = if semicolon_for_stmt(self) { ";" } else { "" };
914 ast::StmtKind::Expr(_) => ExprType::SubExpression,
915 ast::StmtKind::Semi(_) => ExprType::Statement,
919 try_opt!(shape.sub_width(suffix.len())),
920 ).map(|s| s + suffix)
922 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
924 result.and_then(|res| {
925 recover_comment_removed(res, self.span, context, shape)
930 // Rewrite condition if the given expression has one.
931 fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
933 ast::ExprKind::Match(ref cond, _) => {
935 let cond_shape = match context.config.control_style() {
936 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
937 Style::Rfc => try_opt!(shape.offset_left(8)),
939 cond.rewrite(context, cond_shape)
941 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
942 stmt_expr(&block.stmts[0]).and_then(|e| rewrite_cond(context, e, shape))
944 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
946 String::from("\n") + &shape.indent.block_only().to_string(context.config);
948 .rewrite_cond(context, shape, &alt_block_sep)
949 .and_then(|rw| Some(rw.0))
954 // Abstraction over control flow expressions
956 struct ControlFlow<'a> {
957 cond: Option<&'a ast::Expr>,
958 block: &'a ast::Block,
959 else_block: Option<&'a ast::Expr>,
960 label: Option<ast::SpannedIdent>,
961 pat: Option<&'a ast::Pat>,
965 allow_single_line: bool,
966 // True if this is an `if` expression in an `else if` :-( hacky
971 fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'a>> {
973 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
977 else_block.as_ref().map(|e| &**e),
978 expr_type == ExprType::SubExpression,
982 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
983 Some(ControlFlow::new_if(
987 else_block.as_ref().map(|e| &**e),
988 expr_type == ExprType::SubExpression,
993 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
994 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
996 ast::ExprKind::Loop(ref block, label) => {
997 Some(ControlFlow::new_loop(block, label, expr.span))
999 ast::ExprKind::While(ref cond, ref block, label) => {
1000 Some(ControlFlow::new_while(None, cond, block, label, expr.span))
1002 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
1003 ControlFlow::new_while(Some(pat), cond, block, label, expr.span),
1009 impl<'a> ControlFlow<'a> {
1011 cond: &'a ast::Expr,
1012 pat: Option<&'a ast::Pat>,
1013 block: &'a ast::Block,
1014 else_block: Option<&'a ast::Expr>,
1015 allow_single_line: bool,
1018 ) -> ControlFlow<'a> {
1022 else_block: else_block,
1026 matcher: match pat {
1031 allow_single_line: allow_single_line,
1032 nested_if: nested_if,
1038 block: &'a ast::Block,
1039 label: Option<ast::SpannedIdent>,
1041 ) -> ControlFlow<'a> {
1051 allow_single_line: false,
1058 pat: Option<&'a ast::Pat>,
1059 cond: &'a ast::Expr,
1060 block: &'a ast::Block,
1061 label: Option<ast::SpannedIdent>,
1063 ) -> ControlFlow<'a> {
1071 matcher: match pat {
1076 allow_single_line: false,
1084 cond: &'a ast::Expr,
1085 block: &'a ast::Block,
1086 label: Option<ast::SpannedIdent>,
1088 ) -> ControlFlow<'a> {
1098 allow_single_line: false,
1104 fn rewrite_single_line(
1107 context: &RewriteContext,
1109 ) -> Option<String> {
1110 assert!(self.allow_single_line);
1111 let else_block = try_opt!(self.else_block);
1112 let fixed_cost = self.keyword.len() + " { } else { }".len();
1114 if let ast::ExprKind::Block(ref else_node) = else_block.node {
1115 if !is_simple_block(self.block, context.codemap) ||
1116 !is_simple_block(else_node, context.codemap) ||
1117 pat_expr_str.contains('\n')
1122 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
1123 let expr = &self.block.stmts[0];
1124 let if_str = try_opt!(expr.rewrite(
1126 Shape::legacy(new_width, Indent::empty()),
1129 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
1130 let else_expr = &else_node.stmts[0];
1132 try_opt!(else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
1134 if if_str.contains('\n') || else_str.contains('\n') {
1138 let result = format!(
1139 "{} {} {{ {} }} else {{ {} }}",
1146 if result.len() <= width {
1147 return Some(result);
1155 impl<'a> ControlFlow<'a> {
1158 context: &RewriteContext,
1160 alt_block_sep: &str,
1161 ) -> Option<(String, usize)> {
1162 let constr_shape = if self.nested_if {
1163 // We are part of an if-elseif-else chain. Our constraints are tightened.
1164 // 7 = "} else " .len()
1165 try_opt!(shape.shrink_left(7))
1170 let label_string = rewrite_label(self.label);
1171 // 1 = space after keyword.
1172 let offset = self.keyword.len() + label_string.len() + 1;
1174 let pat_expr_string = match self.cond {
1176 let mut cond_shape = match context.config.control_style() {
1177 Style::Legacy => try_opt!(constr_shape.shrink_left(offset)),
1178 Style::Rfc => try_opt!(constr_shape.offset_left(offset)),
1180 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1182 cond_shape = try_opt!(cond_shape.sub_width(2));
1185 try_opt!(rewrite_pat_expr(
1195 None => String::new(),
1198 let force_newline_brace = context.config.control_style() == Style::Rfc &&
1199 pat_expr_string.contains('\n') &&
1200 !last_line_extendable(&pat_expr_string);
1202 // Try to format if-else on single line.
1203 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1204 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1206 if let Some(cond_str) = trial {
1207 if cond_str.len() <= context.config.single_line_if_else_max_width() {
1208 return Some((cond_str, 0));
1213 let cond_span = if let Some(cond) = self.cond {
1216 mk_sp(self.block.span.lo, self.block.span.lo)
1219 // for event in event
1220 let between_kwd_cond = mk_sp(
1221 context.codemap.span_after(self.span, self.keyword.trim()),
1224 |p| if self.matcher.is_empty() {
1227 context.codemap.span_before(self.span, self.matcher.trim())
1232 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1234 let after_cond_comment =
1235 extract_comment(mk_sp(cond_span.hi, self.block.span.lo), context, shape);
1237 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1239 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine ||
1247 let used_width = if pat_expr_string.contains('\n') {
1248 last_line_width(&pat_expr_string)
1250 // 2 = spaces after keyword and condition.
1251 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1259 between_kwd_cond_comment.as_ref().map_or(
1260 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1268 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1275 impl<'a> Rewrite for ControlFlow<'a> {
1276 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1277 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1280 String::from("\n") + &shape.indent.block_only().to_string(context.config);
1281 let (cond_str, used_width) = try_opt!(self.rewrite_cond(context, shape, &alt_block_sep));
1282 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1283 if used_width == 0 {
1284 return Some(cond_str);
1287 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1288 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1289 // we should avoid the single line case.
1290 let block_width = if self.else_block.is_some() || self.nested_if {
1295 let block_shape = Shape {
1299 let mut block_context = context.clone();
1300 block_context.is_if_else_block = self.else_block.is_some();
1301 let block_str = try_opt!(rewrite_block_with_visitor(
1308 let mut result = format!("{}{}", cond_str, block_str);
1310 if let Some(else_block) = self.else_block {
1311 let shape = Shape::indented(shape.indent, context.config);
1312 let mut last_in_chain = false;
1313 let rewrite = match else_block.node {
1314 // If the else expression is another if-else expression, prevent it
1315 // from being formatted on a single line.
1316 // Note how we're passing the original shape, as the
1317 // cost of "else" should not cascade.
1318 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1319 ControlFlow::new_if(
1323 next_else_block.as_ref().map(|e| &**e),
1326 mk_sp(else_block.span.lo, self.span.hi),
1327 ).rewrite(context, shape)
1329 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1330 ControlFlow::new_if(
1334 next_else_block.as_ref().map(|e| &**e),
1337 mk_sp(else_block.span.lo, self.span.hi),
1338 ).rewrite(context, shape)
1341 last_in_chain = true;
1342 // When rewriting a block, the width is only used for single line
1343 // blocks, passing 1 lets us avoid that.
1344 let else_shape = Shape {
1345 width: min(1, shape.width),
1348 format_expr(else_block, ExprType::Statement, context, else_shape)
1352 let between_kwd_else_block = mk_sp(
1356 .span_before(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1358 let between_kwd_else_block_comment =
1359 extract_comment(between_kwd_else_block, context, shape);
1361 let after_else = mk_sp(
1364 .span_after(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1367 let after_else_comment = extract_comment(after_else, context, shape);
1369 let between_sep = match context.config.control_brace_style() {
1370 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1373 ControlBraceStyle::AlwaysSameLine => " ",
1375 let after_sep = match context.config.control_brace_style() {
1376 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1383 between_kwd_else_block_comment
1385 .map_or(between_sep, |s| &**s),
1386 after_else_comment.as_ref().map_or(after_sep, |s| &**s)
1389 result.push_str(&try_opt!(rewrite));
1396 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
1398 Some(ident) => format!("{}: ", ident.node),
1399 None => "".to_owned(),
1403 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1404 let comment_str = context.snippet(span);
1405 if contains_comment(&comment_str) {
1406 let comment = try_opt!(rewrite_comment(
1413 "\n{indent}{}\n{indent}",
1415 indent = shape.indent.to_string(context.config)
1422 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1423 let snippet = codemap.span_to_snippet(block.span).unwrap();
1424 contains_comment(&snippet)
1427 // Checks that a block contains no statements, an expression and no comments.
1428 // FIXME: incorrectly returns false when comment is contained completely within
1430 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1431 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) &&
1432 !block_contains_comment(block, codemap))
1435 /// Checks whether a block contains at most one statement or expression, and no comments.
1436 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1437 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1440 /// Checks whether a block contains no statements, expressions, or comments.
1441 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1442 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1445 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1447 ast::StmtKind::Expr(..) => true,
1452 fn is_unsafe_block(block: &ast::Block) -> bool {
1453 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1460 // inter-match-arm-comment-rules:
1461 // - all comments following a match arm before the start of the next arm
1462 // are about the second arm
1463 fn rewrite_match_arm_comment(
1464 context: &RewriteContext,
1467 arm_indent_str: &str,
1468 ) -> Option<String> {
1469 // The leading "," is not part of the arm-comment
1470 let missed_str = match missed_str.find_uncommented(",") {
1471 Some(n) => &missed_str[n + 1..],
1472 None => &missed_str[..],
1475 let mut result = String::new();
1476 // any text not preceeded by a newline is pushed unmodified to the block
1477 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
1478 result.push_str(&missed_str[..first_brk]);
1479 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
1481 let first = missed_str
1482 .find(|c: char| !c.is_whitespace())
1483 .unwrap_or(missed_str.len());
1484 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
1485 // Excessive vertical whitespace before comment should be preserved
1486 // FIXME handle vertical whitespace better
1489 let missed_str = missed_str[first..].trim();
1490 if !missed_str.is_empty() {
1491 let comment = try_opt!(rewrite_comment(&missed_str, false, shape, context.config));
1493 result.push_str(arm_indent_str);
1494 result.push_str(&comment);
1501 context: &RewriteContext,
1506 ) -> Option<String> {
1507 if arms.is_empty() {
1512 let cond_shape = match context.config.control_style() {
1513 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
1514 Style::Rfc => try_opt!(shape.offset_left(8)),
1516 let cond_str = try_opt!(cond.rewrite(context, cond_shape));
1517 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1518 let block_sep = match context.config.control_brace_style() {
1519 ControlBraceStyle::AlwaysNextLine => alt_block_sep.as_str(),
1524 "match {}{}{{{}\n{}}}",
1527 try_opt!(rewrite_match_arms(context, arms, shape, span, cond.span.hi)),
1528 shape.indent.to_string(context.config),
1532 fn arm_comma(config: &Config, body: &ast::Expr) -> &'static str {
1533 if config.match_block_trailing_comma() {
1535 } else if let ast::ExprKind::Block(ref block) = body.node {
1536 if let ast::BlockCheckMode::Default = block.rules {
1546 fn rewrite_match_pattern(
1547 context: &RewriteContext,
1548 pats: &Vec<ptr::P<ast::Pat>>,
1549 guard: &Option<ptr::P<ast::Expr>>,
1551 ) -> Option<String> {
1554 let pat_shape = try_opt!(shape.sub_width(5));
1556 let pat_strs = try_opt!(
1558 .map(|p| p.rewrite(context, pat_shape))
1559 .collect::<Option<Vec<_>>>()
1562 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1563 let tactic = definitive_tactic(&items, ListTactic::HorizontalVertical, pat_shape.width);
1564 let fmt = ListFormatting {
1567 trailing_separator: SeparatorTactic::Never,
1569 ends_with_newline: false,
1570 config: context.config,
1572 let pats_str = try_opt!(write_list(&items, &fmt));
1575 let guard_str = try_opt!(rewrite_guard(
1579 trimmed_last_line_width(&pats_str),
1582 Some(format!("{}{}", pats_str, guard_str))
1585 fn rewrite_match_arms(
1586 context: &RewriteContext,
1590 cond_end_pos: BytePos,
1591 ) -> Option<String> {
1592 let mut result = String::new();
1594 let arm_shape = if context.config.indent_match_arms() {
1595 shape.block_indent(context.config.tab_spaces())
1597 shape.block_indent(0)
1598 }.with_max_width(context.config);
1599 let arm_indent_str = arm_shape.indent.to_string(context.config);
1601 let open_brace_pos = context
1603 .span_after(mk_sp(cond_end_pos, arms[0].span().lo), "{");
1605 let arm_num = arms.len();
1606 for (i, arm) in arms.iter().enumerate() {
1607 // Make sure we get the stuff between arms.
1608 let missed_str = if i == 0 {
1609 context.snippet(mk_sp(open_brace_pos, arm.span().lo))
1611 context.snippet(mk_sp(arms[i - 1].span().hi, arm.span().lo))
1613 let comment = try_opt!(rewrite_match_arm_comment(
1619 result.push_str(&comment);
1621 result.push_str(&arm_indent_str);
1623 let arm_str = rewrite_match_arm(context, arm, arm_shape);
1624 if let Some(ref arm_str) = arm_str {
1625 // Trim the trailing comma if necessary.
1626 if i == arm_num - 1 && context.config.trailing_comma() == SeparatorTactic::Never &&
1627 arm_str.ends_with(',')
1629 result.push_str(&arm_str[0..arm_str.len() - 1])
1631 result.push_str(arm_str)
1634 // We couldn't format the arm, just reproduce the source.
1635 let snippet = context.snippet(arm.span());
1636 result.push_str(&snippet);
1637 if context.config.trailing_comma() != SeparatorTactic::Never {
1638 result.push_str(arm_comma(context.config, &arm.body))
1642 // BytePos(1) = closing match brace.
1643 let last_span = mk_sp(arms[arms.len() - 1].span().hi, span.hi - BytePos(1));
1644 let last_comment = context.snippet(last_span);
1645 let comment = try_opt!(rewrite_match_arm_comment(
1651 result.push_str(&comment);
1656 fn rewrite_match_arm(context: &RewriteContext, arm: &ast::Arm, shape: Shape) -> Option<String> {
1657 let attr_str = if !arm.attrs.is_empty() {
1658 if contains_skip(&arm.attrs) {
1663 try_opt!(arm.attrs.rewrite(context, shape)),
1664 shape.indent.to_string(context.config)
1669 let pats_str = try_opt!(rewrite_match_pattern(context, &arm.pats, &arm.guard, shape));
1670 let pats_str = attr_str + &pats_str;
1671 rewrite_match_body(context, &arm.body, &pats_str, shape, arm.guard.is_some())
1674 fn rewrite_match_body(
1675 context: &RewriteContext,
1676 body: &ptr::P<ast::Expr>,
1680 ) -> Option<String> {
1681 let (extend, body) = match body.node {
1682 ast::ExprKind::Block(ref block)
1683 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) => {
1684 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1685 (expr.can_be_overflowed(context, 1), &**expr)
1690 _ => (body.can_be_overflowed(context, 1), &**body),
1693 let comma = arm_comma(&context.config, body);
1694 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1695 let alt_block_sep = alt_block_sep.as_str();
1696 let is_block = if let ast::ExprKind::Block(..) = body.node {
1702 let combine_orig_body = |body_str: &str| {
1703 let block_sep = match context.config.control_brace_style() {
1704 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
1705 _ if has_guard && pats_str.contains('\n') && is_block && body_str != "{}" => {
1711 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
1714 let combine_next_line_body = |body_str: &str| {
1715 let indent_str = shape
1717 .block_indent(context.config)
1718 .to_string(context.config);
1719 let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1720 let comma = if context.config.match_block_trailing_comma() {
1727 format!("\n{}}}{}", shape.indent.to_string(context.config), comma),
1730 ("", String::from(","))
1733 let block_sep = match context.config.control_brace_style() {
1734 ControlBraceStyle::AlwaysNextLine => format!("{}{}\n", alt_block_sep, body_prefix),
1735 _ if body_prefix.is_empty() => "\n".to_owned(),
1736 _ => " ".to_owned() + body_prefix + "\n",
1748 // Let's try and get the arm body on the same line as the condition.
1750 let orig_arm_shape = shape
1751 .offset_left(extra_offset(&pats_str, shape) + 4)
1752 .and_then(|shape| shape.sub_width(comma.len()));
1753 let orig_body = if let Some(arm_shape) = orig_arm_shape {
1754 let rewrite = nop_block_collapse(
1755 format_expr(body, ExprType::Statement, context, arm_shape),
1761 if ((!body_str.contains('\n')) && first_line_width(body_str) <= arm_shape.width) ||
1764 return combine_orig_body(body_str);
1771 let orig_budget = orig_arm_shape.map_or(0, |shape| shape.width);
1773 // Try putting body on the next line and see if it looks better.
1774 let next_line_body_shape =
1775 Shape::indented(shape.indent.block_indent(context.config), context.config);
1776 let next_line_body = nop_block_collapse(
1777 format_expr(body, ExprType::Statement, context, next_line_body_shape),
1778 next_line_body_shape.width,
1780 match (orig_body, next_line_body) {
1781 (Some(ref orig_str), Some(ref next_line_str))
1782 if prefer_next_line(orig_str, next_line_str) => combine_next_line_body(next_line_str),
1783 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
1784 combine_orig_body(orig_str)
1786 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
1787 combine_next_line_body(next_line_str)
1789 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
1790 (None, None) => None,
1791 (Some(ref orig_str), _) => combine_orig_body(orig_str),
1795 // The `if ...` guard on a match arm.
1797 context: &RewriteContext,
1798 guard: &Option<ptr::P<ast::Expr>>,
1800 // The amount of space used up on this line for the pattern in
1801 // the arm (excludes offset).
1802 pattern_width: usize,
1803 ) -> Option<String> {
1804 if let Some(ref guard) = *guard {
1805 // First try to fit the guard string on the same line as the pattern.
1806 // 4 = ` if `, 5 = ` => {`
1807 let cond_shape = shape
1808 .offset_left(pattern_width + 4)
1809 .and_then(|s| s.sub_width(5));
1810 if let Some(cond_shape) = cond_shape {
1811 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1812 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
1813 return Some(format!(" if {}", cond_str));
1818 // Not enough space to put the guard after the pattern, try a newline.
1819 // 3 = `if `, 5 = ` => {`
1820 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
1822 .and_then(|s| s.sub_width(5));
1823 if let Some(cond_shape) = cond_shape {
1824 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1825 return Some(format!(
1827 cond_shape.indent.to_string(context.config),
1839 fn rewrite_pat_expr(
1840 context: &RewriteContext,
1841 pat: Option<&ast::Pat>,
1844 // Connecting piece between pattern and expression,
1845 // *without* trailing space.
1849 ) -> Option<String> {
1850 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1851 if let Some(pat) = pat {
1852 let matcher = if matcher.is_empty() {
1855 format!("{} ", matcher)
1858 try_opt!(try_opt!(shape.offset_left(matcher.len())).sub_width(connector.len()));
1859 let pat_string = try_opt!(pat.rewrite(context, pat_shape));
1860 let result = format!("{}{}{}", matcher, pat_string, connector);
1861 return rewrite_assign_rhs(context, result, expr, shape);
1864 let expr_rw = expr.rewrite(context, shape);
1865 // The expression may (partially) fit on the current line.
1866 // We do not allow splitting between `if` and condition.
1867 if keyword == "if" || expr_rw.is_some() {
1871 // The expression won't fit on the current line, jump to next.
1872 let nested_shape = shape
1873 .block_indent(context.config.tab_spaces())
1874 .with_max_width(context.config);
1875 let nested_indent_str = nested_shape.indent.to_string(context.config);
1876 expr.rewrite(context, nested_shape)
1877 .map(|expr_rw| format!("\n{}{}", nested_indent_str, expr_rw))
1880 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1881 let string_lit = context.snippet(span);
1883 if !context.config.format_strings() && !context.config.force_format_strings() {
1888 .all(|line| line.ends_with('\\'))
1890 let new_indent = shape.visual_indent(1).indent;
1891 return Some(String::from(
1895 new_indent.to_string(context.config) + line.trim_left()
1897 .collect::<Vec<_>>()
1902 return Some(string_lit);
1906 if !context.config.force_format_strings() &&
1907 !string_requires_rewrite(context, span, &string_lit, shape)
1909 return Some(string_lit);
1912 let fmt = StringFormat {
1919 config: context.config,
1922 // Remove the quote characters.
1923 let str_lit = &string_lit[1..string_lit.len() - 1];
1925 rewrite_string(str_lit, &fmt)
1928 fn string_requires_rewrite(
1929 context: &RewriteContext,
1934 if context.codemap.lookup_char_pos(span.lo).col.0 != shape.indent.width() {
1938 for (i, line) in string.lines().enumerate() {
1940 if line.len() > shape.width {
1944 if line.len() > shape.width + shape.indent.width() {
1953 pub fn rewrite_call_with_binary_search<R>(
1954 context: &RewriteContext,
1956 args: &[&ast::Expr],
1963 let force_trailing_comma = if context.inside_macro {
1964 span_ends_with_comma(context, span)
1968 let closure = |callee_max_width| {
1969 // FIXME using byte lens instead of char lens (and probably all over the
1971 let callee_shape = Shape {
1972 width: callee_max_width,
1975 let callee_str = callee
1976 .rewrite(context, callee_shape)
1977 .ok_or(Ordering::Greater)?;
1985 context.config.fn_call_width(),
1986 force_trailing_comma,
1990 binary_search(1, shape.width, closure)
1993 pub fn rewrite_call(
1994 context: &RewriteContext,
1996 args: &[ptr::P<ast::Expr>],
1999 ) -> Option<String> {
2000 let force_trailing_comma = if context.inside_macro {
2001 span_ends_with_comma(context, span)
2008 &args.iter().map(|x| &**x).collect::<Vec<_>>(),
2011 context.config.fn_call_width(),
2012 force_trailing_comma,
2016 pub fn rewrite_call_inner<'a, T>(
2017 context: &RewriteContext,
2022 args_max_width: usize,
2023 force_trailing_comma: bool,
2024 ) -> Result<String, Ordering>
2026 T: Rewrite + Spanned + ToExpr + 'a,
2028 // 2 = `( `, 1 = `(`
2029 let paren_overhead = if context.config.spaces_within_parens() {
2034 let used_width = extra_offset(&callee_str, shape);
2035 let one_line_width = shape
2037 .checked_sub(used_width + 2 * paren_overhead)
2038 .ok_or(Ordering::Greater)?;
2040 let nested_shape = shape_from_fn_call_style(
2043 used_width + 2 * paren_overhead,
2044 used_width + paren_overhead,
2045 ).ok_or(Ordering::Greater)?;
2047 let span_lo = context.codemap.span_after(span, "(");
2048 let args_span = mk_sp(span_lo, span.hi);
2050 let (extendable, list_str) = rewrite_call_args(
2057 force_trailing_comma,
2058 ).or_else(|| if context.use_block_indent() {
2064 shape.block().indent.block_indent(context.config),
2069 force_trailing_comma,
2074 .ok_or(Ordering::Less)?;
2076 if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
2077 let mut new_context = context.clone();
2078 new_context.use_block = true;
2079 return rewrite_call_inner(
2086 force_trailing_comma,
2090 let args_shape = shape
2091 .sub_width(last_line_width(&callee_str))
2092 .ok_or(Ordering::Less)?;
2096 wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2100 fn need_block_indent(s: &str, shape: Shape) -> bool {
2101 s.lines().skip(1).any(|s| {
2102 s.find(|c| !char::is_whitespace(c))
2103 .map_or(false, |w| w + 1 < shape.indent.width())
2107 fn rewrite_call_args<'a, T>(
2108 context: &RewriteContext,
2112 one_line_width: usize,
2113 args_max_width: usize,
2114 force_trailing_comma: bool,
2115 ) -> Option<(bool, String)>
2117 T: Rewrite + Spanned + ToExpr + 'a,
2119 let items = itemize_list(
2123 |item| item.span().lo,
2124 |item| item.span().hi,
2125 |item| item.rewrite(context, shape),
2129 let mut item_vec: Vec<_> = items.collect();
2131 // Try letting the last argument overflow to the next line with block
2132 // indentation. If its first line fits on one line with the other arguments,
2133 // we format the function arguments horizontally.
2134 let tactic = try_overflow_last_arg(
2143 let fmt = ListFormatting {
2146 trailing_separator: if force_trailing_comma {
2147 SeparatorTactic::Always
2148 } else if context.inside_macro || !context.use_block_indent() {
2149 SeparatorTactic::Never
2151 context.config.trailing_comma()
2154 ends_with_newline: context.use_block_indent() && tactic == DefinitiveListTactic::Vertical,
2155 config: context.config,
2158 write_list(&item_vec, &fmt).map(|args_str| {
2159 (tactic != DefinitiveListTactic::Vertical, args_str)
2163 fn try_overflow_last_arg<'a, T>(
2164 context: &RewriteContext,
2165 item_vec: &mut Vec<ListItem>,
2168 one_line_width: usize,
2169 args_max_width: usize,
2170 ) -> DefinitiveListTactic
2172 T: Rewrite + Spanned + ToExpr + 'a,
2174 let overflow_last = can_be_overflowed(&context, args);
2176 // Replace the last item with its first line to see if it fits with
2178 let (orig_last, placeholder) = if overflow_last {
2179 let mut context = context.clone();
2180 if let Some(expr) = args[args.len() - 1].to_expr() {
2182 ast::ExprKind::MethodCall(..) => context.force_one_line_chain = true,
2186 last_arg_shape(&context, &item_vec, shape, args_max_width)
2187 .map_or((None, None), |arg_shape| {
2188 rewrite_last_arg_with_overflow(
2191 &mut item_vec[args.len() - 1],
2199 let tactic = definitive_tactic(
2201 ListTactic::LimitedHorizontalVertical(args_max_width),
2205 // Replace the stub with the full overflowing last argument if the rewrite
2206 // succeeded and its first line fits with the other arguments.
2207 match (overflow_last, tactic, placeholder) {
2208 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2209 item_vec[args.len() - 1].item = placeholder;
2212 item_vec[args.len() - 1].item = orig_last;
2221 context: &RewriteContext,
2222 items: &Vec<ListItem>,
2224 args_max_width: usize,
2225 ) -> Option<Shape> {
2226 let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
2227 acc + i.item.as_ref().map_or(0, |s| first_line_width(&s))
2229 let max_width = min(args_max_width, shape.width);
2230 let arg_indent = if context.use_block_indent() {
2231 shape.block().indent.block_unindent(context.config)
2233 shape.block().indent
2236 width: try_opt!(max_width.checked_sub(overhead)),
2242 // Rewriting closure which is placed at the end of the function call's arg.
2243 // Returns `None` if the reformatted closure 'looks bad'.
2244 fn rewrite_last_closure(
2245 context: &RewriteContext,
2248 ) -> Option<String> {
2249 if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
2250 let body = match body.node {
2251 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
2252 stmt_expr(&block.stmts[0]).unwrap_or(body)
2256 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
2264 // If the closure goes multi line before its body, do not overflow the closure.
2265 if prefix.contains('\n') {
2268 let body_shape = try_opt!(shape.offset_left(extra_offset));
2269 // When overflowing the closure which consists of a single control flow expression,
2270 // force to use block if its condition uses multi line.
2271 if rewrite_cond(context, body, body_shape)
2272 .map(|cond| cond.contains('\n'))
2275 return rewrite_closure_with_block(context, body_shape, &prefix, body);
2278 // Seems fine, just format the closure in usual manner.
2279 return expr.rewrite(context, shape);
2284 fn rewrite_last_arg_with_overflow<'a, T>(
2285 context: &RewriteContext,
2287 last_item: &mut ListItem,
2289 ) -> (Option<String>, Option<String>)
2291 T: Rewrite + Spanned + ToExpr + 'a,
2293 let last_arg = args[args.len() - 1];
2294 let rewrite = if let Some(expr) = last_arg.to_expr() {
2296 // When overflowing the closure which consists of a single control flow expression,
2297 // force to use block if its condition uses multi line.
2298 ast::ExprKind::Closure(..) => {
2299 // If the argument consists of multiple closures, we do not overflow
2300 // the last closure.
2301 if args.len() > 1 &&
2305 .filter_map(|arg| arg.to_expr())
2306 .any(|expr| match expr.node {
2307 ast::ExprKind::Closure(..) => true,
2312 rewrite_last_closure(context, expr, shape)
2315 _ => expr.rewrite(context, shape),
2318 last_arg.rewrite(context, shape)
2320 let orig_last = last_item.item.clone();
2322 if let Some(rewrite) = rewrite {
2323 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2324 last_item.item = rewrite_first_line;
2325 (orig_last, Some(rewrite))
2331 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2333 T: Rewrite + Spanned + ToExpr + 'a,
2336 .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2339 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2341 ast::ExprKind::Match(..) => {
2342 (context.use_block_indent() && args_len == 1) ||
2343 (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
2345 ast::ExprKind::If(..) |
2346 ast::ExprKind::IfLet(..) |
2347 ast::ExprKind::ForLoop(..) |
2348 ast::ExprKind::Loop(..) |
2349 ast::ExprKind::While(..) |
2350 ast::ExprKind::WhileLet(..) => {
2351 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2353 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
2354 context.use_block_indent() ||
2355 context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
2357 ast::ExprKind::Array(..) |
2358 ast::ExprKind::Call(..) |
2359 ast::ExprKind::Mac(..) |
2360 ast::ExprKind::MethodCall(..) |
2361 ast::ExprKind::Struct(..) |
2362 ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2363 ast::ExprKind::AddrOf(_, ref expr) |
2364 ast::ExprKind::Box(ref expr) |
2365 ast::ExprKind::Try(ref expr) |
2366 ast::ExprKind::Unary(_, ref expr) |
2367 ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2372 pub fn wrap_args_with_parens(
2373 context: &RewriteContext,
2375 is_extendable: bool,
2377 nested_shape: Shape,
2379 if !context.use_block_indent() ||
2380 (context.inside_macro && !args_str.contains('\n') &&
2381 args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2383 if context.config.spaces_within_parens() && args_str.len() > 0 {
2384 format!("( {} )", args_str)
2386 format!("({})", args_str)
2391 nested_shape.indent.to_string(context.config),
2393 shape.block().indent.to_string(context.config)
2398 fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2399 let snippet = context.snippet(span);
2401 .trim_right_matches(|c: char| c == ')' || c.is_whitespace())
2405 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2406 debug!("rewrite_paren, shape: {:?}", shape);
2407 let paren_overhead = paren_overhead(context);
2408 let sub_shape = try_opt!(shape.sub_width(paren_overhead / 2)).visual_indent(paren_overhead / 2);
2410 let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && s.len() > 0 {
2411 format!("( {} )", s)
2416 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2417 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2419 if subexpr_str.contains('\n') {
2420 Some(paren_wrapper(&subexpr_str))
2422 if subexpr_str.len() + paren_overhead <= shape.width {
2423 Some(paren_wrapper(&subexpr_str))
2425 let sub_shape = try_opt!(shape.offset_left(2));
2426 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2427 Some(paren_wrapper(&subexpr_str))
2435 context: &RewriteContext,
2437 ) -> Option<String> {
2438 let expr_str = try_opt!(expr.rewrite(context, shape));
2440 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
2446 let offset = last_line_width(&expr_str) + lbr.len();
2447 let rhs_overhead = shape.rhs_overhead(context.config);
2448 let index_shape = if expr_str.contains('\n') {
2449 Shape::legacy(context.config.max_width(), shape.indent)
2450 .offset_left(offset)
2451 .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
2453 shape.visual_indent(offset).sub_width(offset + rbr.len())
2455 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
2457 // Return if index fits in a single line.
2458 match orig_index_rw {
2459 Some(ref index_str) if !index_str.contains('\n') => {
2460 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2465 // Try putting index on the next line and see if it fits in a single line.
2466 let indent = shape.indent.block_indent(context.config);
2467 let index_shape = try_opt!(Shape::indented(indent, context.config).offset_left(lbr.len()));
2468 let index_shape = try_opt!(index_shape.sub_width(rbr.len() + rhs_overhead));
2469 let new_index_rw = index.rewrite(context, index_shape);
2470 match (orig_index_rw, new_index_rw) {
2471 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
2474 indent.to_string(&context.config),
2479 (None, Some(ref new_index_str)) => Some(format!(
2482 indent.to_string(&context.config),
2487 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2492 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2497 fields.iter().all(|field| !field.is_shorthand)
2500 fn rewrite_struct_lit<'a>(
2501 context: &RewriteContext,
2503 fields: &'a [ast::Field],
2504 base: Option<&'a ast::Expr>,
2507 ) -> Option<String> {
2508 debug!("rewrite_struct_lit: shape {:?}", shape);
2510 enum StructLitField<'a> {
2511 Regular(&'a ast::Field),
2512 Base(&'a ast::Expr),
2516 let path_shape = try_opt!(shape.sub_width(2));
2517 let path_str = try_opt!(rewrite_path(
2525 if fields.len() == 0 && base.is_none() {
2526 return Some(format!("{} {{}}", path_str));
2529 // Foo { a: Foo } - indent is +3, width is -5.
2530 let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
2532 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2533 let body_lo = context.codemap.span_after(span, "{");
2534 let fields_str = if struct_lit_can_be_aligned(fields, &base) &&
2535 context.config.struct_field_align_threshold() > 0
2537 try_opt!(rewrite_with_alignment(
2541 mk_sp(body_lo, span.hi),
2545 let field_iter = fields
2547 .map(StructLitField::Regular)
2548 .chain(base.into_iter().map(StructLitField::Base));
2550 let span_lo = |item: &StructLitField| match *item {
2551 StructLitField::Regular(field) => field.span().lo,
2552 StructLitField::Base(expr) => {
2553 let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
2554 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
2555 let pos = snippet.find_uncommented("..").unwrap();
2556 last_field_hi + BytePos(pos as u32)
2559 let span_hi = |item: &StructLitField| match *item {
2560 StructLitField::Regular(field) => field.span().hi,
2561 StructLitField::Base(expr) => expr.span.hi,
2563 let rewrite = |item: &StructLitField| match *item {
2564 StructLitField::Regular(field) => {
2565 // The 1 taken from the v_budget is for the comma.
2566 rewrite_field(context, field, try_opt!(v_shape.sub_width(1)), 0)
2568 StructLitField::Base(expr) => {
2570 expr.rewrite(context, try_opt!(v_shape.shrink_left(2)))
2571 .map(|s| format!("..{}", s))
2575 let items = itemize_list(
2585 let item_vec = items.collect::<Vec<_>>();
2587 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2588 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2589 let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2591 try_opt!(write_list(&item_vec, &fmt))
2594 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2595 Some(format!("{} {{{}}}", path_str, fields_str))
2597 // FIXME if context.config.struct_lit_style() == Visual, but we run out
2598 // of space, we should fall back to BlockIndent.
2601 pub fn wrap_struct_field(
2602 context: &RewriteContext,
2605 nested_shape: Shape,
2606 one_line_width: usize,
2608 if context.config.struct_lit_style() == IndentStyle::Block &&
2609 (fields_str.contains('\n') ||
2610 context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti ||
2611 fields_str.len() > one_line_width)
2615 nested_shape.indent.to_string(context.config),
2617 shape.indent.to_string(context.config)
2620 // One liner or visual indent.
2621 format!(" {} ", fields_str)
2625 pub fn struct_lit_field_separator(config: &Config) -> &str {
2627 config.space_before_struct_lit_field_colon(),
2628 config.space_after_struct_lit_field_colon(),
2632 pub fn rewrite_field(
2633 context: &RewriteContext,
2636 prefix_max_width: usize,
2637 ) -> Option<String> {
2638 if contains_skip(&field.attrs) {
2640 context.snippet(field.span()),
2641 context.config.max_width(),
2645 let name = &field.ident.node.to_string();
2646 if field.is_shorthand {
2647 Some(name.to_string())
2649 let mut separator = String::from(struct_lit_field_separator(context.config));
2650 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2651 separator.push(' ');
2653 let overhead = name.len() + separator.len();
2654 let expr_shape = try_opt!(shape.offset_left(overhead));
2655 let expr = field.expr.rewrite(context, expr_shape);
2657 let mut attrs_str = try_opt!(field.attrs.rewrite(context, shape));
2658 if !attrs_str.is_empty() {
2659 attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2663 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2665 let expr_offset = shape.indent.block_indent(context.config);
2668 .rewrite(context, Shape::indented(expr_offset, context.config));
2674 expr_offset.to_string(&context.config),
2683 fn shape_from_fn_call_style(
2684 context: &RewriteContext,
2688 ) -> Option<Shape> {
2689 if context.use_block_indent() {
2693 .block_indent(context.config.tab_spaces())
2694 .with_max_width(context.config)
2697 shape.visual_indent(offset).sub_width(overhead)
2701 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2702 context: &RewriteContext,
2708 T: Rewrite + Spanned + ToExpr + 'a,
2710 let mut items = items.iter();
2711 // In case of length 1, need a trailing comma
2712 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2713 if items.len() == 1 {
2715 let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
2716 return items.next().unwrap().rewrite(context, nested_shape).map(
2717 |s| if context.config.spaces_within_parens() {
2718 format!("( {}, )", s)
2725 let list_lo = context.codemap.span_after(span, "(");
2726 let nested_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
2727 let items = itemize_list(
2731 |item| item.span().lo,
2732 |item| item.span().hi,
2733 |item| item.rewrite(context, nested_shape),
2735 span.hi - BytePos(1),
2737 let item_vec: Vec<_> = items.collect();
2738 let tactic = definitive_tactic(
2740 ListTactic::HorizontalVertical,
2743 let fmt = ListFormatting {
2746 trailing_separator: SeparatorTactic::Never,
2748 ends_with_newline: false,
2749 config: context.config,
2751 let list_str = try_opt!(write_list(&item_vec, &fmt));
2753 if context.config.spaces_within_parens() && list_str.len() > 0 {
2754 Some(format!("( {} )", list_str))
2756 Some(format!("({})", list_str))
2760 pub fn rewrite_tuple<'a, T>(
2761 context: &RewriteContext,
2767 T: Rewrite + Spanned + ToExpr + 'a,
2769 debug!("rewrite_tuple {:?}", shape);
2770 if context.use_block_indent() {
2771 // We use the same rule as funcation call for rewriting tuple.
2772 let force_trailing_comma = if context.inside_macro {
2773 span_ends_with_comma(context, span)
2783 context.config.fn_call_width(),
2784 force_trailing_comma,
2787 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2791 pub fn rewrite_unary_prefix<R: Rewrite>(
2792 context: &RewriteContext,
2796 ) -> Option<String> {
2798 .rewrite(context, try_opt!(shape.offset_left(prefix.len())))
2799 .map(|r| format!("{}{}", prefix, r))
2802 // FIXME: this is probably not correct for multi-line Rewrites. we should
2803 // subtract suffix.len() from the last line budget, not the first!
2804 pub fn rewrite_unary_suffix<R: Rewrite>(
2805 context: &RewriteContext,
2809 ) -> Option<String> {
2811 .rewrite(context, try_opt!(shape.sub_width(suffix.len())))
2818 fn rewrite_unary_op(
2819 context: &RewriteContext,
2823 ) -> Option<String> {
2824 // For some reason, an UnOp is not spanned like BinOp!
2825 let operator_str = match *op {
2826 ast::UnOp::Deref => "*",
2827 ast::UnOp::Not => "!",
2828 ast::UnOp::Neg => "-",
2830 rewrite_unary_prefix(context, operator_str, expr, shape)
2833 fn rewrite_assignment(
2834 context: &RewriteContext,
2837 op: Option<&ast::BinOp>,
2839 ) -> Option<String> {
2840 let operator_str = match op {
2841 Some(op) => context.snippet(op.span),
2842 None => "=".to_owned(),
2845 // 1 = space between lhs and operator.
2846 let lhs_shape = try_opt!(shape.sub_width(operator_str.len() + 1));
2847 let lhs_str = format!(
2849 try_opt!(lhs.rewrite(context, lhs_shape)),
2853 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2856 // The left hand side must contain everything up to, and including, the
2857 // assignment operator.
2858 pub fn rewrite_assign_rhs<S: Into<String>>(
2859 context: &RewriteContext,
2863 ) -> Option<String> {
2864 let lhs = lhs.into();
2865 let last_line_width = last_line_width(&lhs) -
2866 if lhs.contains('\n') {
2867 shape.indent.width()
2871 // 1 = space between operator and rhs.
2872 let orig_shape = try_opt!(shape.offset_left(last_line_width + 1));
2873 let rhs = try_opt!(choose_rhs(
2877 ex.rewrite(context, orig_shape)
2883 context: &RewriteContext,
2886 orig_rhs: Option<String>,
2887 ) -> Option<String> {
2889 Some(ref new_str) if !new_str.contains('\n') => Some(format!(" {}", new_str)),
2891 // Expression did not fit on the same line as the identifier.
2892 // Try splitting the line and see if that works better.
2893 let new_shape = try_opt!(
2895 shape.block().indent.block_indent(context.config),
2897 ).sub_width(shape.rhs_overhead(context.config))
2899 let new_rhs = expr.rewrite(context, new_shape);
2900 let new_indent_str = &new_shape.indent.to_string(context.config);
2902 match (orig_rhs, new_rhs) {
2903 (Some(ref orig_rhs), Some(ref new_rhs)) if prefer_next_line(orig_rhs, new_rhs) => {
2904 Some(format!("\n{}{}", new_indent_str, new_rhs))
2906 (None, Some(ref new_rhs)) => Some(format!("\n{}{}", new_indent_str, new_rhs)),
2907 (None, None) => None,
2908 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2914 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {
2916 fn count_line_breaks(src: &str) -> usize {
2917 src.chars().filter(|&x| x == '\n').count()
2920 !next_line_rhs.contains('\n') ||
2921 count_line_breaks(orig_rhs) > count_line_breaks(next_line_rhs) + 1
2924 fn rewrite_expr_addrof(
2925 context: &RewriteContext,
2926 mutability: ast::Mutability,
2929 ) -> Option<String> {
2930 let operator_str = match mutability {
2931 ast::Mutability::Immutable => "&",
2932 ast::Mutability::Mutable => "&mut ",
2934 rewrite_unary_prefix(context, operator_str, expr, shape)
2938 fn to_expr(&self) -> Option<&ast::Expr>;
2939 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2942 impl ToExpr for ast::Expr {
2943 fn to_expr(&self) -> Option<&ast::Expr> {
2947 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2948 can_be_overflowed_expr(context, self, len)
2952 impl ToExpr for ast::Ty {
2953 fn to_expr(&self) -> Option<&ast::Expr> {
2957 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2958 can_be_overflowed_type(context, self, len)
2962 impl<'a> ToExpr for TuplePatField<'a> {
2963 fn to_expr(&self) -> Option<&ast::Expr> {
2967 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2968 can_be_overflowed_pat(context, self, len)
2972 impl<'a> ToExpr for ast::StructField {
2973 fn to_expr(&self) -> Option<&ast::Expr> {
2977 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {