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.
13 use std::iter::{repeat, ExactSizeIterator};
15 use syntax::{ast, ptr};
16 use syntax::codemap::{BytePos, CodeMap, Span};
17 use syntax::parse::classify;
20 use chains::rewrite_chain;
21 use codemap::{LineRangeUtils, SpanUtils};
22 use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
23 rewrite_comment, rewrite_missing_comment, FindUncommented};
24 use config::{Config, ControlBraceStyle, IndentStyle, MultilineStyle, Style};
25 use items::{span_hi_for_arg, span_lo_for_arg};
26 use lists::{definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting,
27 struct_lit_shape, struct_lit_tactic, write_list, DefinitiveListTactic, ListFormatting,
28 ListItem, ListTactic, Separator, SeparatorPlace, SeparatorTactic};
29 use macros::{rewrite_macro, MacroArg, MacroPosition};
30 use patterns::{can_be_overflowed_pat, TuplePatField};
31 use rewrite::{Rewrite, RewriteContext};
32 use shape::{Indent, Shape};
33 use string::{rewrite_string, StringFormat};
34 use types::{can_be_overflowed_type, rewrite_path, PathContext};
35 use utils::{colon_spaces, contains_skip, extra_offset, first_line_width, inner_attributes,
36 last_line_extendable, last_line_width, left_most_sub_expr, mk_sp, outer_attributes,
37 paren_overhead, ptr_vec_to_ref_vec, semicolon_for_stmt, stmt_expr,
38 trimmed_last_line_width};
39 use vertical::rewrite_with_alignment;
40 use visitor::FmtVisitor;
42 impl Rewrite for ast::Expr {
43 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
44 format_expr(self, ExprType::SubExpression, context, shape)
48 #[derive(Copy, Clone, PartialEq)]
57 context: &RewriteContext,
60 skip_out_of_file_lines_range!(context, expr.span);
62 if contains_skip(&*expr.attrs) {
63 return Some(context.snippet(expr.span()));
66 let expr_rw = match expr.node {
67 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
68 expr_vec.iter().map(|e| &**e),
69 mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi()),
74 ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
75 ast::ExprKind::Call(ref callee, ref args) => {
76 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
77 let callee_str = callee.rewrite(context, shape)?;
78 rewrite_call(context, &callee_str, &args, inner_span, shape)
80 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
81 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
82 // FIXME: format comments between operands and operator
87 &format!(" {} ", context.snippet(op.span)),
91 context.config.binop_separator(),
94 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
95 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
99 base.as_ref().map(|e| &**e),
103 ast::ExprKind::Tup(ref items) => {
104 rewrite_tuple(context, &ptr_vec_to_ref_vec(&items), expr.span, shape)
106 ast::ExprKind::If(..) |
107 ast::ExprKind::IfLet(..) |
108 ast::ExprKind::ForLoop(..) |
109 ast::ExprKind::Loop(..) |
110 ast::ExprKind::While(..) |
111 ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
112 .and_then(|control_flow| control_flow.rewrite(context, shape)),
113 ast::ExprKind::Block(ref block) => {
115 ExprType::Statement => {
116 if is_unsafe_block(block) {
117 block.rewrite(context, shape)
118 } else if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
119 // Rewrite block without trying to put it in a single line.
122 let prefix = block_prefix(context, block, shape)?;
123 rewrite_block_with_visitor(context, &prefix, block, shape)
126 ExprType::SubExpression => block.rewrite(context, shape),
129 ast::ExprKind::Match(ref cond, ref arms) => {
130 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
132 ast::ExprKind::Path(ref qself, ref path) => {
133 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
135 ast::ExprKind::Assign(ref lhs, ref rhs) => {
136 rewrite_assignment(context, lhs, rhs, None, shape)
138 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
139 rewrite_assignment(context, lhs, rhs, Some(op), shape)
141 ast::ExprKind::Continue(ref opt_ident) => {
142 let id_str = match *opt_ident {
143 Some(ident) => format!(" {}", ident.node),
144 None => String::new(),
146 Some(format!("continue{}", id_str))
148 ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
149 let id_str = match *opt_ident {
150 Some(ident) => format!(" {}", ident.node),
151 None => String::new(),
154 if let Some(ref expr) = *opt_expr {
155 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
157 Some(format!("break{}", id_str))
160 ast::ExprKind::Yield(ref opt_expr) => if let Some(ref expr) = *opt_expr {
161 rewrite_unary_prefix(context, "yield ", &**expr, shape)
163 Some("yield".to_string())
165 ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
166 rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
168 ast::ExprKind::Try(..) |
169 ast::ExprKind::Field(..) |
170 ast::ExprKind::TupField(..) |
171 ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
172 ast::ExprKind::Mac(ref mac) => {
173 // Failure to rewrite a marco should not imply failure to
174 // rewrite the expression.
175 rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
176 .or_else(|| Some(context.snippet(expr.span)))
178 ast::ExprKind::Ret(None) => Some("return".to_owned()),
179 ast::ExprKind::Ret(Some(ref expr)) => {
180 rewrite_unary_prefix(context, "return ", &**expr, shape)
182 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
183 ast::ExprKind::AddrOf(mutability, ref expr) => {
184 rewrite_expr_addrof(context, mutability, expr, shape)
186 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
194 SeparatorPlace::Front,
196 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
204 SeparatorPlace::Back,
206 ast::ExprKind::Index(ref expr, ref index) => {
207 rewrite_index(&**expr, &**index, context, shape)
209 ast::ExprKind::Repeat(ref expr, ref repeats) => {
210 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
223 SeparatorPlace::Back,
226 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
227 let delim = match limits {
228 ast::RangeLimits::HalfOpen => "..",
229 ast::RangeLimits::Closed => "..=",
232 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
234 ast::ExprKind::Lit(ref lit) => match lit.node {
235 ast::LitKind::FloatUnsuffixed(..) => {
236 context.snippet(lit.span).ends_with('.')
244 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
245 (Some(lhs), Some(rhs)) => {
246 let sp_delim = if context.config.spaces_around_ranges() {
247 format!(" {} ", delim)
248 } else if needs_space_before_range(context, lhs) {
249 format!(" {}", delim)
261 SeparatorPlace::Front,
264 (None, Some(rhs)) => {
265 let sp_delim = if context.config.spaces_around_ranges() {
266 format!("{} ", delim)
270 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
272 (Some(lhs), None) => {
273 let sp_delim = if context.config.spaces_around_ranges() {
274 format!(" {}", delim)
278 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
280 (None, None) => Some(delim.into()),
283 // We do not format these expressions yet, but they should still
284 // satisfy our width restrictions.
285 ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => {
286 Some(context.snippet(expr.span))
288 ast::ExprKind::Catch(ref block) => {
289 if let rw @ Some(_) = rewrite_single_line_block(context, "do catch ", block, shape) {
293 let budget = shape.width.checked_sub(9).unwrap_or(0);
297 block.rewrite(context, Shape::legacy(budget, shape.indent))?
304 .and_then(|expr_str| {
305 recover_comment_removed(expr_str, expr.span, context)
307 .and_then(|expr_str| {
308 let attrs = outer_attributes(&expr.attrs);
309 let attrs_str = attrs.rewrite(context, shape)?;
311 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
314 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
318 pub fn rewrite_pair<LHS, RHS>(
324 context: &RewriteContext,
326 separator_place: SeparatorPlace,
332 let lhs_overhead = match separator_place {
333 SeparatorPlace::Back => shape.used_width() + prefix.len() + infix.trim_right().len(),
334 SeparatorPlace::Front => shape.used_width(),
336 let lhs_shape = Shape {
337 width: context.budget(lhs_overhead),
340 let lhs_result = lhs.rewrite(context, lhs_shape)
341 .map(|lhs_str| format!("{}{}", prefix, lhs_str))?;
343 // Try to the both lhs and rhs on the same line.
344 let rhs_orig_result = shape
345 .offset_left(last_line_width(&lhs_result) + infix.len())
346 .and_then(|s| s.sub_width(suffix.len()))
347 .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
348 if let Some(ref rhs_result) = rhs_orig_result {
349 // If the rhs looks like block expression, we allow it to stay on the same line
350 // with the lhs even if it is multi-lined.
351 let allow_same_line = rhs_result
354 .map(|first_line| first_line.ends_with('{'))
356 if !rhs_result.contains('\n') || allow_same_line {
357 let one_line_width = last_line_width(&lhs_result) + infix.len()
358 + first_line_width(&rhs_result) + suffix.len();
359 if one_line_width <= shape.width {
360 return Some(format!("{}{}{}{}", lhs_result, infix, rhs_result, suffix));
365 // We have to use multiple lines.
366 // Re-evaluate the rhs because we have more space now:
367 let mut rhs_shape = match context.config.control_style() {
368 Style::Legacy => shape
369 .sub_width(suffix.len() + prefix.len())?
370 .visual_indent(prefix.len()),
372 // Try to calculate the initial constraint on the right hand side.
373 let rhs_overhead = shape.rhs_overhead(context.config);
374 Shape::indented(shape.indent.block_indent(context.config), context.config)
375 .sub_width(rhs_overhead)?
378 let infix = match separator_place {
379 SeparatorPlace::Back => infix.trim_right(),
380 SeparatorPlace::Front => infix.trim_left(),
382 if separator_place == SeparatorPlace::Front {
383 rhs_shape = rhs_shape.offset_left(infix.len())?;
385 let rhs_result = rhs.rewrite(context, rhs_shape)?;
386 match separator_place {
387 SeparatorPlace::Back => Some(format!(
391 rhs_shape.indent.to_string(context.config),
395 SeparatorPlace::Front => Some(format!(
398 rhs_shape.indent.to_string(context.config),
406 pub fn rewrite_array<'a, I>(
409 context: &RewriteContext,
411 trailing_comma: bool,
414 I: Iterator<Item = &'a ast::Expr>,
416 let bracket_size = if context.config.spaces_within_square_brackets() {
422 let nested_shape = match context.config.array_layout() {
423 IndentStyle::Block => shape
425 .block_indent(context.config.tab_spaces())
426 .with_max_width(context.config)
428 IndentStyle::Visual => shape
429 .visual_indent(bracket_size)
430 .sub_width(bracket_size * 2)?,
433 let items = itemize_list(
437 |item| item.span.lo(),
438 |item| item.span.hi(),
439 |item| item.rewrite(context, nested_shape),
443 ).collect::<Vec<_>>();
445 if items.is_empty() {
446 if context.config.spaces_within_square_brackets() {
447 return Some("[ ]".to_string());
449 return Some("[]".to_string());
453 let has_long_item = items
455 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
457 let mut tactic = match context.config.array_layout() {
458 IndentStyle::Block => {
459 // FIXME wrong shape in one-line case
460 match shape.width.checked_sub(2 * bracket_size) {
463 ListTactic::LimitedHorizontalVertical(context.config.array_width());
464 definitive_tactic(&items, tactic, Separator::Comma, width)
466 None => DefinitiveListTactic::Vertical,
469 IndentStyle::Visual => if has_long_item || items.iter().any(ListItem::is_multiline) {
472 ListTactic::LimitedHorizontalVertical(context.config.array_width()),
477 DefinitiveListTactic::Mixed
480 let ends_with_newline = tactic.ends_with_newline(context.config.array_layout());
481 if context.config.array_horizontal_layout_threshold() > 0
482 && items.len() > context.config.array_horizontal_layout_threshold()
484 tactic = DefinitiveListTactic::Mixed;
487 let fmt = ListFormatting {
490 trailing_separator: if trailing_comma {
491 SeparatorTactic::Always
492 } else if context.inside_macro || context.config.array_layout() == IndentStyle::Visual {
493 SeparatorTactic::Never
495 SeparatorTactic::Vertical
497 separator_place: SeparatorPlace::Back,
499 ends_with_newline: ends_with_newline,
500 preserve_newline: false,
501 config: context.config,
503 let list_str = write_list(&items, &fmt)?;
505 let result = if context.config.array_layout() == IndentStyle::Visual
506 || tactic == DefinitiveListTactic::Horizontal
508 if context.config.spaces_within_square_brackets() && !list_str.is_empty() {
509 format!("[ {} ]", list_str)
511 format!("[{}]", list_str)
516 nested_shape.indent.to_string(context.config),
518 shape.block().indent.to_string(context.config)
525 // Return type is (prefix, extra_offset)
526 fn rewrite_closure_fn_decl(
527 capture: ast::CaptureBy,
528 fn_decl: &ast::FnDecl,
531 context: &RewriteContext,
533 ) -> Option<(String, usize)> {
534 let mover = if capture == ast::CaptureBy::Value {
539 // 4 = "|| {".len(), which is overconservative when the closure consists of
540 // a single expression.
541 let nested_shape = shape.shrink_left(mover.len())?.sub_width(4)?;
544 let argument_offset = nested_shape.indent + 1;
545 let arg_shape = nested_shape.offset_left(1)?.visual_indent(0);
546 let ret_str = fn_decl.output.rewrite(context, arg_shape)?;
548 let arg_items = itemize_list(
550 fn_decl.inputs.iter(),
552 |arg| span_lo_for_arg(arg),
553 |arg| span_hi_for_arg(context, arg),
554 |arg| arg.rewrite(context, arg_shape),
555 context.codemap.span_after(span, "|"),
559 let item_vec = arg_items.collect::<Vec<_>>();
560 // 1 = space between arguments and return type.
561 let horizontal_budget = nested_shape
563 .checked_sub(ret_str.len() + 1)
565 let tactic = definitive_tactic(
567 ListTactic::HorizontalVertical,
571 let arg_shape = match tactic {
572 DefinitiveListTactic::Horizontal => arg_shape.sub_width(ret_str.len() + 1)?,
576 let fmt = ListFormatting {
579 trailing_separator: SeparatorTactic::Never,
580 separator_place: SeparatorPlace::Back,
582 ends_with_newline: false,
583 preserve_newline: true,
584 config: context.config,
586 let list_str = write_list(&item_vec, &fmt)?;
587 let mut prefix = format!("{}|{}|", mover, list_str);
589 if !ret_str.is_empty() {
590 if prefix.contains('\n') {
592 prefix.push_str(&argument_offset.to_string(context.config));
596 prefix.push_str(&ret_str);
598 // 1 = space between `|...|` and body.
599 let extra_offset = last_line_width(&prefix) + 1;
601 Some((prefix, extra_offset))
604 // This functions is pretty messy because of the rules around closures and blocks:
605 // FIXME - the below is probably no longer true in full.
606 // * if there is a return type, then there must be braces,
607 // * given a closure with braces, whether that is parsed to give an inner block
608 // or not depends on if there is a return type and if there are statements
610 // * if the first expression in the body ends with a block (i.e., is a
611 // statement without needing a semi-colon), then adding or removing braces
612 // can change whether it is treated as an expression or statement.
614 capture: ast::CaptureBy,
615 fn_decl: &ast::FnDecl,
618 context: &RewriteContext,
620 ) -> Option<String> {
621 let (prefix, extra_offset) =
622 rewrite_closure_fn_decl(capture, fn_decl, body, span, context, shape)?;
623 // 1 = space between `|...|` and body.
624 let body_shape = shape.offset_left(extra_offset)?;
626 if let ast::ExprKind::Block(ref block) = body.node {
627 // The body of the closure is an empty block.
628 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
629 return Some(format!("{} {{}}", prefix));
632 // Figure out if the block is necessary.
633 let needs_block = block.rules != ast::BlockCheckMode::Default || block.stmts.len() > 1
634 || context.inside_macro
635 || block_contains_comment(block, context.codemap)
636 || prefix.contains('\n');
638 let no_return_type = if let ast::FunctionRetTy::Default(_) = fn_decl.output {
643 if no_return_type && !needs_block {
644 // block.stmts.len() == 1
645 if let Some(expr) = stmt_expr(&block.stmts[0]) {
646 if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
652 // Either we require a block, or tried without and failed.
653 rewrite_closure_block(block, &prefix, context, body_shape)
655 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
656 // The closure originally had a non-block expression, but we can't fit on
657 // one line, so we'll insert a block.
658 rewrite_closure_with_block(context, body_shape, &prefix, body)
663 // Rewrite closure with a single expression wrapping its body with block.
664 fn rewrite_closure_with_block(
665 context: &RewriteContext,
669 ) -> Option<String> {
670 let block = ast::Block {
673 id: ast::NodeId::new(0),
674 node: ast::StmtKind::Expr(ptr::P(body.clone())),
678 id: ast::NodeId::new(0),
679 rules: ast::BlockCheckMode::Default,
682 rewrite_closure_block(&block, prefix, context, shape)
685 // Rewrite closure with a single expression without wrapping its body with block.
686 fn rewrite_closure_expr(
689 context: &RewriteContext,
691 ) -> Option<String> {
692 let mut rewrite = expr.rewrite(context, shape);
693 if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
694 rewrite = and_one_line(rewrite);
696 rewrite = rewrite.and_then(|rw| {
697 if context.config.multiline_closure_forces_block() && rw.contains('\n') {
703 rewrite.map(|rw| format!("{} {}", prefix, rw))
706 // Rewrite closure whose body is block.
707 fn rewrite_closure_block(
710 context: &RewriteContext,
712 ) -> Option<String> {
713 // Start with visual indent, then fall back to block indent if the
715 let block_threshold = context.config.closure_block_indent_threshold();
716 if block_threshold >= 0 {
717 if let Some(block_str) = block.rewrite(context, shape) {
718 if block_str.matches('\n').count() <= block_threshold as usize
719 && !need_block_indent(&block_str, shape)
721 return Some(format!("{} {}", prefix, block_str));
726 // The body of the closure is big enough to be block indented, that
727 // means we must re-format.
728 let block_shape = shape.block();
729 let block_str = block.rewrite(context, block_shape)?;
730 Some(format!("{} {}", prefix, block_str))
733 fn and_one_line(x: Option<String>) -> Option<String> {
734 x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
737 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
738 debug!("nop_block_collapse {:?} {}", block_str, budget);
739 block_str.map(|block_str| {
740 if block_str.starts_with('{') && budget >= 2
741 && (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
750 fn rewrite_empty_block(
751 context: &RewriteContext,
754 ) -> Option<String> {
755 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
757 return Some("{}".to_owned());
760 // If a block contains only a single-line comment, then leave it on one line.
761 let user_str = context.snippet(block.span);
762 let user_str = user_str.trim();
763 if user_str.starts_with('{') && user_str.ends_with('}') {
764 let comment_str = user_str[1..user_str.len() - 1].trim();
765 if block.stmts.is_empty() && !comment_str.contains('\n') && !comment_str.starts_with("//")
766 && comment_str.len() + 4 <= shape.width
768 return Some(format!("{{ {} }}", comment_str));
775 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
776 Some(match block.rules {
777 ast::BlockCheckMode::Unsafe(..) => {
778 let snippet = context.snippet(block.span);
779 let open_pos = snippet.find_uncommented("{")?;
780 // Extract comment between unsafe and block start.
781 let trimmed = &snippet[6..open_pos].trim();
783 if !trimmed.is_empty() {
784 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
785 let budget = shape.width.checked_sub(9)?;
791 Shape::legacy(budget, shape.indent + 7),
799 ast::BlockCheckMode::Default => String::new(),
803 fn rewrite_single_line_block(
804 context: &RewriteContext,
808 ) -> Option<String> {
809 if is_simple_block(block, context.codemap) {
810 let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
811 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
812 let result = format!("{}{{ {} }}", prefix, expr_str);
813 if result.len() <= shape.width && !result.contains('\n') {
820 fn rewrite_block_with_visitor(
821 context: &RewriteContext,
825 ) -> Option<String> {
826 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
830 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
831 visitor.block_indent = shape.indent;
832 visitor.is_if_else_block = context.is_if_else_block;
834 ast::BlockCheckMode::Unsafe(..) => {
835 let snippet = context.snippet(block.span);
836 let open_pos = snippet.find_uncommented("{")?;
837 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
839 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo(),
842 visitor.visit_block(block, None);
843 Some(format!("{}{}", prefix, visitor.buffer))
846 impl Rewrite for ast::Block {
847 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
848 // shape.width is used only for the single line case: either the empty block `{}`,
849 // or an unsafe expression `unsafe { e }`.
850 if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
854 let prefix = block_prefix(context, self, shape)?;
856 let result = rewrite_block_with_visitor(context, &prefix, self, shape);
857 if let Some(ref result_str) = result {
858 if result_str.lines().count() <= 3 {
859 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
869 impl Rewrite for ast::Stmt {
870 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
871 skip_out_of_file_lines_range!(context, self.span());
873 let result = match self.node {
874 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
875 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
876 let suffix = if semicolon_for_stmt(context, self) {
882 let shape = shape.sub_width(suffix.len())?;
883 format_expr(ex, ExprType::Statement, context, shape).map(|s| s + suffix)
885 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
887 result.and_then(|res| recover_comment_removed(res, self.span(), context))
891 // Rewrite condition if the given expression has one.
892 fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
894 ast::ExprKind::Match(ref cond, _) => {
896 let cond_shape = match context.config.control_style() {
897 Style::Legacy => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
898 Style::Rfc => shape.offset_left(8)?,
900 cond.rewrite(context, cond_shape)
902 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
903 stmt_expr(&block.stmts[0]).and_then(|e| rewrite_cond(context, e, shape))
905 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
907 String::from("\n") + &shape.indent.block_only().to_string(context.config);
909 .rewrite_cond(context, shape, &alt_block_sep)
910 .and_then(|rw| Some(rw.0))
915 // Abstraction over control flow expressions
917 struct ControlFlow<'a> {
918 cond: Option<&'a ast::Expr>,
919 block: &'a ast::Block,
920 else_block: Option<&'a ast::Expr>,
921 label: Option<ast::SpannedIdent>,
922 pat: Option<&'a ast::Pat>,
926 allow_single_line: bool,
927 // True if this is an `if` expression in an `else if` :-( hacky
932 fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'a>> {
934 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
938 else_block.as_ref().map(|e| &**e),
939 expr_type == ExprType::SubExpression,
943 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
944 Some(ControlFlow::new_if(
948 else_block.as_ref().map(|e| &**e),
949 expr_type == ExprType::SubExpression,
954 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
955 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
957 ast::ExprKind::Loop(ref block, label) => {
958 Some(ControlFlow::new_loop(block, label, expr.span))
960 ast::ExprKind::While(ref cond, ref block, label) => {
961 Some(ControlFlow::new_while(None, cond, block, label, expr.span))
963 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
964 ControlFlow::new_while(Some(pat), cond, block, label, expr.span),
970 impl<'a> ControlFlow<'a> {
973 pat: Option<&'a ast::Pat>,
974 block: &'a ast::Block,
975 else_block: Option<&'a ast::Expr>,
976 allow_single_line: bool,
979 ) -> ControlFlow<'a> {
983 else_block: else_block,
992 allow_single_line: allow_single_line,
993 nested_if: nested_if,
999 block: &'a ast::Block,
1000 label: Option<ast::SpannedIdent>,
1002 ) -> ControlFlow<'a> {
1012 allow_single_line: false,
1019 pat: Option<&'a ast::Pat>,
1020 cond: &'a ast::Expr,
1021 block: &'a ast::Block,
1022 label: Option<ast::SpannedIdent>,
1024 ) -> ControlFlow<'a> {
1032 matcher: match pat {
1037 allow_single_line: false,
1045 cond: &'a ast::Expr,
1046 block: &'a ast::Block,
1047 label: Option<ast::SpannedIdent>,
1049 ) -> ControlFlow<'a> {
1059 allow_single_line: false,
1065 fn rewrite_single_line(
1068 context: &RewriteContext,
1070 ) -> Option<String> {
1071 assert!(self.allow_single_line);
1072 let else_block = self.else_block?;
1073 let fixed_cost = self.keyword.len() + " { } else { }".len();
1075 if let ast::ExprKind::Block(ref else_node) = else_block.node {
1076 if !is_simple_block(self.block, context.codemap)
1077 || !is_simple_block(else_node, context.codemap)
1078 || pat_expr_str.contains('\n')
1083 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
1084 let expr = &self.block.stmts[0];
1085 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
1087 let new_width = new_width.checked_sub(if_str.len())?;
1088 let else_expr = &else_node.stmts[0];
1089 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
1091 if if_str.contains('\n') || else_str.contains('\n') {
1095 let result = format!(
1096 "{} {} {{ {} }} else {{ {} }}",
1103 if result.len() <= width {
1104 return Some(result);
1112 impl<'a> ControlFlow<'a> {
1115 context: &RewriteContext,
1117 alt_block_sep: &str,
1118 ) -> Option<(String, usize)> {
1119 // Do not take the rhs overhead from the upper expressions into account
1120 // when rewriting pattern.
1121 let new_width = context
1124 .checked_sub(shape.used_width())
1126 let fresh_shape = Shape {
1130 let constr_shape = if self.nested_if {
1131 // We are part of an if-elseif-else chain. Our constraints are tightened.
1132 // 7 = "} else " .len()
1133 fresh_shape.offset_left(7)?
1138 let label_string = rewrite_label(self.label);
1139 // 1 = space after keyword.
1140 let offset = self.keyword.len() + label_string.len() + 1;
1142 let pat_expr_string = match self.cond {
1144 let cond_shape = match context.config.control_style() {
1145 Style::Legacy => constr_shape.shrink_left(offset)?,
1146 Style::Rfc => constr_shape.offset_left(offset)?,
1158 None => String::new(),
1161 let brace_overhead =
1162 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1168 let one_line_budget = context
1171 .checked_sub(constr_shape.used_width() + offset + brace_overhead)
1173 let force_newline_brace = context.config.control_style() == Style::Rfc
1174 && (pat_expr_string.contains('\n') || pat_expr_string.len() > one_line_budget)
1175 && !last_line_extendable(&pat_expr_string);
1177 // Try to format if-else on single line.
1178 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1179 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1181 if let Some(cond_str) = trial {
1182 if cond_str.len() <= context.config.single_line_if_else_max_width() {
1183 return Some((cond_str, 0));
1188 let cond_span = if let Some(cond) = self.cond {
1191 mk_sp(self.block.span.lo(), self.block.span.lo())
1194 // `for event in event`
1195 // Do not include label in the span.
1196 let lo = self.label.map_or(self.span.lo(), |label| label.span.hi());
1197 let between_kwd_cond = mk_sp(
1200 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
1202 .map_or(cond_span.lo(), |p| if self.matcher.is_empty() {
1205 context.codemap.span_before(self.span, self.matcher.trim())
1209 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1211 let after_cond_comment =
1212 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
1214 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1216 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
1217 || force_newline_brace
1224 let used_width = if pat_expr_string.contains('\n') {
1225 last_line_width(&pat_expr_string)
1227 // 2 = spaces after keyword and condition.
1228 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1236 between_kwd_cond_comment.as_ref().map_or(
1237 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1245 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1252 impl<'a> Rewrite for ControlFlow<'a> {
1253 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1254 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1257 String::from("\n") + &shape.indent.block_only().to_string(context.config);
1258 let (cond_str, used_width) = self.rewrite_cond(context, shape, &alt_block_sep)?;
1259 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1260 if used_width == 0 {
1261 return Some(cond_str);
1264 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1265 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1266 // we should avoid the single line case.
1267 let block_width = if self.else_block.is_some() || self.nested_if {
1272 let block_shape = Shape {
1276 let mut block_context = context.clone();
1277 block_context.is_if_else_block = self.else_block.is_some();
1278 let block_str = rewrite_block_with_visitor(&block_context, "", self.block, block_shape)?;
1280 let mut result = format!("{}{}", cond_str, block_str);
1282 if let Some(else_block) = self.else_block {
1283 let shape = Shape::indented(shape.indent, context.config);
1284 let mut last_in_chain = false;
1285 let rewrite = match else_block.node {
1286 // If the else expression is another if-else expression, prevent it
1287 // from being formatted on a single line.
1288 // Note how we're passing the original shape, as the
1289 // cost of "else" should not cascade.
1290 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1291 ControlFlow::new_if(
1295 next_else_block.as_ref().map(|e| &**e),
1298 mk_sp(else_block.span.lo(), self.span.hi()),
1299 ).rewrite(context, shape)
1301 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1302 ControlFlow::new_if(
1306 next_else_block.as_ref().map(|e| &**e),
1309 mk_sp(else_block.span.lo(), self.span.hi()),
1310 ).rewrite(context, shape)
1313 last_in_chain = true;
1314 // When rewriting a block, the width is only used for single line
1315 // blocks, passing 1 lets us avoid that.
1316 let else_shape = Shape {
1317 width: min(1, shape.width),
1320 format_expr(else_block, ExprType::Statement, context, else_shape)
1324 let between_kwd_else_block = mk_sp(
1325 self.block.span.hi(),
1328 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1330 let between_kwd_else_block_comment =
1331 extract_comment(between_kwd_else_block, context, shape);
1333 let after_else = mk_sp(
1336 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1337 else_block.span.lo(),
1339 let after_else_comment = extract_comment(after_else, context, shape);
1341 let between_sep = match context.config.control_brace_style() {
1342 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1345 ControlBraceStyle::AlwaysSameLine => " ",
1347 let after_sep = match context.config.control_brace_style() {
1348 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1352 result.push_str(&format!(
1354 between_kwd_else_block_comment
1356 .map_or(between_sep, |s| &**s),
1357 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1359 result.push_str(&rewrite?);
1366 fn rewrite_label(label: Option<ast::SpannedIdent>) -> Cow<'static, str> {
1368 Some(ident) => Cow::from(format!("{}: ", ident.node)),
1369 None => Cow::from(""),
1373 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1374 match rewrite_missing_comment(span, shape, context) {
1375 Some(ref comment) if !comment.is_empty() => Some(format!(
1376 "\n{indent}{}\n{indent}",
1378 indent = shape.indent.to_string(context.config)
1384 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1385 let snippet = codemap.span_to_snippet(block.span).unwrap();
1386 contains_comment(&snippet)
1389 // Checks that a block contains no statements, an expression and no comments.
1390 // FIXME: incorrectly returns false when comment is contained completely within
1392 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1393 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0])
1394 && !block_contains_comment(block, codemap))
1397 /// Checks whether a block contains at most one statement or expression, and no comments.
1398 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1399 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1402 /// Checks whether a block contains no statements, expressions, or comments.
1403 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1404 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1407 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1409 ast::StmtKind::Expr(..) => true,
1414 fn is_unsafe_block(block: &ast::Block) -> bool {
1415 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1422 // A simple wrapper type against ast::Arm. Used inside write_list().
1423 struct ArmWrapper<'a> {
1424 pub arm: &'a ast::Arm,
1425 // True if the arm is the last one in match expression. Used to decide on whether we should add
1426 // trailing comma to the match arm when `config.trailing_comma() == Never`.
1430 impl<'a> ArmWrapper<'a> {
1431 pub fn new(arm: &'a ast::Arm, is_last: bool) -> ArmWrapper<'a> {
1432 ArmWrapper { arm, is_last }
1436 impl<'a> Rewrite for ArmWrapper<'a> {
1437 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1438 rewrite_match_arm(context, self.arm, shape, self.is_last)
1443 context: &RewriteContext,
1448 attrs: &[ast::Attribute],
1449 ) -> Option<String> {
1450 if arms.is_empty() {
1454 // Do not take the rhs overhead from the upper expressions into account
1455 // when rewriting match condition.
1456 let new_width = context.config.max_width().checked_sub(shape.used_width())?;
1457 let cond_shape = Shape {
1462 let cond_shape = match context.config.control_style() {
1463 Style::Legacy => cond_shape.shrink_left(6)?,
1464 Style::Rfc => cond_shape.offset_left(6)?,
1466 let cond_str = cond.rewrite(context, cond_shape)?;
1467 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1468 let block_sep = match context.config.control_brace_style() {
1469 ControlBraceStyle::AlwaysNextLine => &alt_block_sep,
1470 _ if last_line_extendable(&cond_str) => " ",
1472 _ if cond_str.contains('\n') || cond_str.len() + 2 > cond_shape.width => &alt_block_sep,
1476 let nested_indent_str = shape
1478 .block_indent(context.config)
1479 .to_string(context.config);
1480 // Inner attributes.
1481 let inner_attrs = &inner_attributes(attrs);
1482 let inner_attrs_str = if inner_attrs.is_empty() {
1486 .rewrite(context, shape)
1487 .map(|s| format!("{}{}\n", nested_indent_str, s))?
1490 let open_brace_pos = if inner_attrs.is_empty() {
1493 .span_after(mk_sp(cond.span.hi(), arms[0].span().lo()), "{")
1495 inner_attrs[inner_attrs.len() - 1].span().hi()
1498 let arm_indent_str = if context.config.indent_match_arms() {
1501 shape.indent.to_string(context.config)
1505 "match {}{}{{\n{}{}{}\n{}}}",
1510 rewrite_match_arms(context, arms, shape, span, open_brace_pos,)?,
1511 shape.indent.to_string(context.config),
1515 fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
1516 if is_last && config.trailing_comma() == SeparatorTactic::Never {
1518 } else if config.match_block_trailing_comma() {
1520 } else if let ast::ExprKind::Block(ref block) = body.node {
1521 if let ast::BlockCheckMode::Default = block.rules {
1531 fn rewrite_match_arms(
1532 context: &RewriteContext,
1536 open_brace_pos: BytePos,
1537 ) -> Option<String> {
1538 let arm_shape = if context.config.indent_match_arms() {
1539 shape.block_indent(context.config.tab_spaces())
1541 shape.block_indent(0)
1542 }.with_max_width(context.config);
1544 let arm_len = arms.len();
1545 let is_last_iter = repeat(false)
1546 .take(arm_len.checked_sub(1).unwrap_or(0))
1547 .chain(repeat(true));
1548 let items = itemize_list(
1552 .map(|(arm, is_last)| ArmWrapper::new(arm, is_last)),
1554 |arm| arm.arm.span().lo(),
1555 |arm| arm.arm.span().hi(),
1556 |arm| arm.rewrite(context, arm_shape),
1561 let arms_vec: Vec<_> = items.collect();
1562 let fmt = ListFormatting {
1563 tactic: DefinitiveListTactic::Vertical,
1564 // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
1566 trailing_separator: SeparatorTactic::Never,
1567 separator_place: SeparatorPlace::Back,
1569 ends_with_newline: true,
1570 preserve_newline: true,
1571 config: context.config,
1574 write_list(&arms_vec, &fmt)
1577 fn rewrite_match_arm(
1578 context: &RewriteContext,
1582 ) -> Option<String> {
1583 let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
1584 if contains_skip(&arm.attrs) {
1585 let (_, body) = flatten_arm_body(context, &arm.body);
1586 // `arm.span()` does not include trailing comma, add it manually.
1587 return Some(format!(
1589 context.snippet(arm.span()),
1590 arm_comma(context.config, body, is_last),
1595 arm.attrs[arm.attrs.len() - 1].span.hi(),
1596 arm.pats[0].span.lo(),
1598 arm.attrs.rewrite(context, shape)?,
1601 (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
1604 rewrite_match_pattern(context, &arm.pats, &arm.guard, shape).and_then(|pats_str| {
1605 combine_strs_with_missing_comments(
1619 arm.guard.is_some(),
1624 fn rewrite_match_pattern(
1625 context: &RewriteContext,
1626 pats: &[ptr::P<ast::Pat>],
1627 guard: &Option<ptr::P<ast::Expr>>,
1629 ) -> Option<String> {
1632 let pat_shape = shape.sub_width(5)?;
1634 let pat_strs = pats.iter()
1635 .map(|p| p.rewrite(context, pat_shape))
1636 .collect::<Option<Vec<_>>>()?;
1638 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1639 let tactic = definitive_tactic(
1641 ListTactic::HorizontalVertical,
1642 Separator::VerticalBar,
1645 let fmt = ListFormatting {
1648 trailing_separator: SeparatorTactic::Never,
1649 separator_place: context.config.match_pattern_separator_break_point(),
1651 ends_with_newline: false,
1652 preserve_newline: false,
1653 config: context.config,
1655 let pats_str = write_list(&items, &fmt)?;
1658 let guard_str = rewrite_guard(context, guard, shape, trimmed_last_line_width(&pats_str))?;
1660 Some(format!("{}{}", pats_str, guard_str))
1664 // @extend: true if the arm body can be put next to `=>`
1665 // @body: flattened body, if the body is block with a single expression
1666 fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bool, &'a ast::Expr) {
1668 ast::ExprKind::Block(ref block)
1669 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) =>
1671 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1673 !context.config.multiline_match_arm_forces_block()
1674 && expr.can_be_overflowed(context, 1),
1682 !context.config.multiline_match_arm_forces_block()
1683 && body.can_be_overflowed(context, 1),
1689 fn rewrite_match_body(
1690 context: &RewriteContext,
1691 body: &ptr::P<ast::Expr>,
1696 ) -> Option<String> {
1697 let (extend, body) = flatten_arm_body(context, body);
1699 let comma = arm_comma(context.config, body, is_last);
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, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
1703 (true, is_empty_block(block, context.codemap))
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,
1714 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
1717 let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
1718 let next_line_indent = if is_block {
1721 shape.indent.block_indent(context.config)
1723 let combine_next_line_body = |body_str: &str| {
1725 return Some(format!(
1728 next_line_indent.to_string(context.config),
1733 let indent_str = shape.indent.to_string(context.config);
1734 let nested_indent_str = next_line_indent.to_string(context.config);
1735 let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1736 let comma = if context.config.match_block_trailing_comma() {
1741 ("{", format!("\n{}}}{}", indent_str, comma))
1743 ("", String::from(","))
1746 let block_sep = match context.config.control_brace_style() {
1747 ControlBraceStyle::AlwaysNextLine => format!("{}{}\n", alt_block_sep, body_prefix),
1748 _ if body_prefix.is_empty() => "\n".to_owned(),
1749 _ if forbid_same_line => format!("{}{}\n", alt_block_sep, body_prefix),
1750 _ => format!(" {}\n", body_prefix),
1751 } + &nested_indent_str;
1762 // Let's try and get the arm body on the same line as the condition.
1764 let orig_body_shape = shape
1765 .offset_left(extra_offset(pats_str, shape) + 4)
1766 .and_then(|shape| shape.sub_width(comma.len()));
1767 let orig_body = if let Some(body_shape) = orig_body_shape {
1768 let rewrite = nop_block_collapse(
1769 format_expr(body, ExprType::Statement, context, body_shape),
1775 if !forbid_same_line
1777 || (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
1779 return combine_orig_body(body_str);
1786 let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
1788 // Try putting body on the next line and see if it looks better.
1789 let next_line_body_shape = Shape::indented(next_line_indent, context.config);
1790 let next_line_body = nop_block_collapse(
1791 format_expr(body, ExprType::Statement, context, next_line_body_shape),
1792 next_line_body_shape.width,
1794 match (orig_body, next_line_body) {
1795 (Some(ref orig_str), Some(ref next_line_str))
1796 if forbid_same_line || prefer_next_line(orig_str, next_line_str) =>
1798 combine_next_line_body(next_line_str)
1800 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
1801 combine_orig_body(orig_str)
1803 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
1804 combine_next_line_body(next_line_str)
1806 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
1807 (None, None) => None,
1808 (Some(ref orig_str), _) => combine_orig_body(orig_str),
1812 // The `if ...` guard on a match arm.
1814 context: &RewriteContext,
1815 guard: &Option<ptr::P<ast::Expr>>,
1817 // The amount of space used up on this line for the pattern in
1818 // the arm (excludes offset).
1819 pattern_width: usize,
1820 ) -> Option<String> {
1821 if let Some(ref guard) = *guard {
1822 // First try to fit the guard string on the same line as the pattern.
1823 // 4 = ` if `, 5 = ` => {`
1824 let cond_shape = shape
1825 .offset_left(pattern_width + 4)
1826 .and_then(|s| s.sub_width(5));
1827 if let Some(cond_shape) = cond_shape {
1828 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1829 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
1830 return Some(format!(" if {}", cond_str));
1835 // Not enough space to put the guard after the pattern, try a newline.
1836 // 3 = `if `, 5 = ` => {`
1837 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
1839 .and_then(|s| s.sub_width(5));
1840 if let Some(cond_shape) = cond_shape {
1841 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1842 return Some(format!(
1844 cond_shape.indent.to_string(context.config),
1856 fn rewrite_pat_expr(
1857 context: &RewriteContext,
1858 pat: Option<&ast::Pat>,
1861 // Connecting piece between pattern and expression,
1862 // *without* trailing space.
1866 ) -> Option<String> {
1867 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1868 if let Some(pat) = pat {
1869 let matcher = if matcher.is_empty() {
1872 format!("{} ", matcher)
1874 let pat_shape = shape.offset_left(matcher.len())?.sub_width(connector.len())?;
1875 let pat_string = pat.rewrite(context, pat_shape)?;
1876 let result = format!("{}{}{}", matcher, pat_string, connector);
1877 return rewrite_assign_rhs(context, result, expr, shape);
1880 let expr_rw = expr.rewrite(context, shape);
1881 // The expression may (partially) fit on the current line.
1882 // We do not allow splitting between `if` and condition.
1883 if keyword == "if" || expr_rw.is_some() {
1887 // The expression won't fit on the current line, jump to next.
1888 let nested_shape = shape
1889 .block_indent(context.config.tab_spaces())
1890 .with_max_width(context.config);
1891 let nested_indent_str = nested_shape.indent.to_string(context.config);
1892 expr.rewrite(context, nested_shape)
1893 .map(|expr_rw| format!("\n{}{}", nested_indent_str, expr_rw))
1896 pub fn rewrite_literal(context: &RewriteContext, l: &ast::Lit, shape: Shape) -> Option<String> {
1898 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1899 _ => Some(context.snippet(l.span)),
1903 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1904 let string_lit = context.snippet(span);
1906 if !context.config.format_strings() && !context.config.force_format_strings() {
1911 .all(|line| line.ends_with('\\'))
1913 let new_indent = shape.visual_indent(1).indent;
1914 return Some(String::from(
1920 new_indent.to_string(context.config),
1924 .collect::<Vec<_>>()
1929 return Some(string_lit);
1933 if !context.config.force_format_strings()
1934 && !string_requires_rewrite(context, span, &string_lit, shape)
1936 return Some(string_lit);
1939 // Remove the quote characters.
1940 let str_lit = &string_lit[1..string_lit.len() - 1];
1942 rewrite_string(str_lit, &StringFormat::new(shape, context.config))
1945 fn string_requires_rewrite(
1946 context: &RewriteContext,
1951 if context.codemap.lookup_char_pos(span.lo()).col.0 != shape.indent.width() {
1955 for (i, line) in string.lines().enumerate() {
1957 if line.len() > shape.width {
1960 } else if line.len() > shape.width + shape.indent.width() {
1968 pub fn rewrite_call(
1969 context: &RewriteContext,
1971 args: &[ptr::P<ast::Expr>],
1974 ) -> Option<String> {
1975 let force_trailing_comma = if context.inside_macro {
1976 span_ends_with_comma(context, span)
1983 &ptr_vec_to_ref_vec(&args),
1986 context.config.fn_call_width(),
1987 force_trailing_comma,
1991 pub fn rewrite_call_inner<'a, T>(
1992 context: &RewriteContext,
1997 args_max_width: usize,
1998 force_trailing_comma: bool,
2001 T: Rewrite + Spanned + ToExpr + 'a,
2003 // 2 = `( `, 1 = `(`
2004 let paren_overhead = if context.config.spaces_within_parens() {
2009 let used_width = extra_offset(callee_str, shape);
2010 let one_line_width = shape.width.checked_sub(used_width + 2 * paren_overhead)?;
2012 let nested_shape = shape_from_fn_call_style(
2015 used_width + 2 * paren_overhead,
2016 used_width + paren_overhead,
2019 let span_lo = context.codemap.span_after(span, "(");
2020 let args_span = mk_sp(span_lo, span.hi());
2022 let (extendable, list_str) = rewrite_call_args(
2029 force_trailing_comma,
2032 if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
2033 let mut new_context = context.clone();
2034 new_context.use_block = true;
2035 return rewrite_call_inner(
2042 force_trailing_comma,
2046 let args_shape = shape.sub_width(last_line_width(callee_str))?;
2050 wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2054 fn need_block_indent(s: &str, shape: Shape) -> bool {
2055 s.lines().skip(1).any(|s| {
2056 s.find(|c| !char::is_whitespace(c))
2057 .map_or(false, |w| w + 1 < shape.indent.width())
2061 fn rewrite_call_args<'a, T>(
2062 context: &RewriteContext,
2066 one_line_width: usize,
2067 args_max_width: usize,
2068 force_trailing_comma: bool,
2069 ) -> Option<(bool, String)>
2071 T: Rewrite + Spanned + ToExpr + 'a,
2073 let items = itemize_list(
2077 |item| item.span().lo(),
2078 |item| item.span().hi(),
2079 |item| item.rewrite(context, shape),
2084 let mut item_vec: Vec<_> = items.collect();
2086 // Try letting the last argument overflow to the next line with block
2087 // indentation. If its first line fits on one line with the other arguments,
2088 // we format the function arguments horizontally.
2089 let tactic = try_overflow_last_arg(
2098 let fmt = ListFormatting {
2101 trailing_separator: if force_trailing_comma {
2102 SeparatorTactic::Always
2103 } else if context.inside_macro || !context.use_block_indent() {
2104 SeparatorTactic::Never
2106 context.config.trailing_comma()
2108 separator_place: SeparatorPlace::Back,
2110 ends_with_newline: context.use_block_indent() && tactic == DefinitiveListTactic::Vertical,
2111 preserve_newline: false,
2112 config: context.config,
2115 write_list(&item_vec, &fmt).map(|args_str| {
2116 (tactic != DefinitiveListTactic::Vertical, args_str)
2120 fn try_overflow_last_arg<'a, T>(
2121 context: &RewriteContext,
2122 item_vec: &mut Vec<ListItem>,
2125 one_line_width: usize,
2126 args_max_width: usize,
2127 ) -> DefinitiveListTactic
2129 T: Rewrite + Spanned + ToExpr + 'a,
2131 let overflow_last = can_be_overflowed(context, args);
2133 // Replace the last item with its first line to see if it fits with
2135 let placeholder = if overflow_last {
2136 let mut context = context.clone();
2137 if let Some(expr) = args[args.len() - 1].to_expr() {
2138 if let ast::ExprKind::MethodCall(..) = expr.node {
2139 context.force_one_line_chain = true;
2142 last_arg_shape(&context, item_vec, shape, args_max_width).and_then(|arg_shape| {
2143 rewrite_last_arg_with_overflow(&context, args, &mut item_vec[args.len() - 1], arg_shape)
2149 let mut tactic = definitive_tactic(
2151 ListTactic::LimitedHorizontalVertical(args_max_width),
2156 // Replace the stub with the full overflowing last argument if the rewrite
2157 // succeeded and its first line fits with the other arguments.
2158 match (overflow_last, tactic, placeholder) {
2159 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2160 item_vec[args.len() - 1].item = placeholder;
2162 _ if args.len() >= 1 => {
2163 item_vec[args.len() - 1].item = args.last()
2164 .and_then(|last_arg| last_arg.rewrite(context, shape));
2165 // Use horizontal layout for a function with a single argument as long as
2166 // everything fits in a single line.
2168 && args_max_width != 0 // Vertical layout is forced.
2169 && !item_vec[0].has_comment()
2170 && !item_vec[0].inner_as_ref().contains('\n')
2171 && ::lists::total_item_width(&item_vec[0]) <= one_line_width
2173 tactic = DefinitiveListTactic::Horizontal;
2175 tactic = definitive_tactic(
2177 ListTactic::LimitedHorizontalVertical(args_max_width),
2190 context: &RewriteContext,
2193 args_max_width: usize,
2194 ) -> Option<Shape> {
2195 let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
2196 acc + i.item.as_ref().map_or(0, |s| first_line_width(s))
2198 let max_width = min(args_max_width, shape.width);
2199 let arg_indent = if context.use_block_indent() {
2200 shape.block().indent.block_unindent(context.config)
2202 shape.block().indent
2205 width: max_width.checked_sub(overhead)?,
2211 // Rewriting closure which is placed at the end of the function call's arg.
2212 // Returns `None` if the reformatted closure 'looks bad'.
2213 fn rewrite_last_closure(
2214 context: &RewriteContext,
2217 ) -> Option<String> {
2218 if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
2219 let body = match body.node {
2220 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
2221 stmt_expr(&block.stmts[0]).unwrap_or(body)
2225 let (prefix, extra_offset) =
2226 rewrite_closure_fn_decl(capture, fn_decl, body, expr.span, context, shape)?;
2227 // If the closure goes multi line before its body, do not overflow the closure.
2228 if prefix.contains('\n') {
2231 let body_shape = shape.offset_left(extra_offset)?;
2232 // When overflowing the closure which consists of a single control flow expression,
2233 // force to use block if its condition uses multi line.
2234 let is_multi_lined_cond = rewrite_cond(context, body, body_shape)
2235 .map(|cond| cond.contains('\n') || cond.len() > body_shape.width)
2237 if is_multi_lined_cond {
2238 return rewrite_closure_with_block(context, body_shape, &prefix, body);
2241 // Seems fine, just format the closure in usual manner.
2242 return expr.rewrite(context, shape);
2247 fn rewrite_last_arg_with_overflow<'a, T>(
2248 context: &RewriteContext,
2250 last_item: &mut ListItem,
2254 T: Rewrite + Spanned + ToExpr + 'a,
2256 let last_arg = args[args.len() - 1];
2257 let rewrite = if let Some(expr) = last_arg.to_expr() {
2259 // When overflowing the closure which consists of a single control flow expression,
2260 // force to use block if its condition uses multi line.
2261 ast::ExprKind::Closure(..) => {
2262 // If the argument consists of multiple closures, we do not overflow
2263 // the last closure.
2268 .filter_map(|arg| arg.to_expr())
2269 .any(|expr| match expr.node {
2270 ast::ExprKind::Closure(..) => true,
2275 rewrite_last_closure(context, expr, shape)
2278 _ => expr.rewrite(context, shape),
2281 last_arg.rewrite(context, shape)
2284 if let Some(rewrite) = rewrite {
2285 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2286 last_item.item = rewrite_first_line;
2293 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2295 T: Rewrite + Spanned + ToExpr + 'a,
2298 .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2301 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2303 ast::ExprKind::Match(..) => {
2304 (context.use_block_indent() && args_len == 1)
2305 || (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
2307 ast::ExprKind::If(..) |
2308 ast::ExprKind::IfLet(..) |
2309 ast::ExprKind::ForLoop(..) |
2310 ast::ExprKind::Loop(..) |
2311 ast::ExprKind::While(..) |
2312 ast::ExprKind::WhileLet(..) => {
2313 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2315 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
2316 context.use_block_indent()
2317 || context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
2319 ast::ExprKind::Array(..) |
2320 ast::ExprKind::Call(..) |
2321 ast::ExprKind::Mac(..) |
2322 ast::ExprKind::MethodCall(..) |
2323 ast::ExprKind::Struct(..) |
2324 ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2325 ast::ExprKind::AddrOf(_, ref expr) |
2326 ast::ExprKind::Box(ref expr) |
2327 ast::ExprKind::Try(ref expr) |
2328 ast::ExprKind::Unary(_, ref expr) |
2329 ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2334 pub fn wrap_args_with_parens(
2335 context: &RewriteContext,
2337 is_extendable: bool,
2339 nested_shape: Shape,
2341 if !context.use_block_indent()
2342 || (context.inside_macro && !args_str.contains('\n')
2343 && args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2345 if context.config.spaces_within_parens() && !args_str.is_empty() {
2346 format!("( {} )", args_str)
2348 format!("({})", args_str)
2353 nested_shape.indent.to_string(context.config),
2355 shape.block().indent.to_string(context.config)
2360 fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2361 let snippet = context.snippet(span);
2363 .trim_right_matches(|c: char| c == ')' || c.is_whitespace())
2367 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2368 debug!("rewrite_paren, shape: {:?}", shape);
2369 let total_paren_overhead = paren_overhead(context);
2370 let paren_overhead = total_paren_overhead / 2;
2371 let sub_shape = shape
2372 .offset_left(paren_overhead)
2373 .and_then(|s| s.sub_width(paren_overhead))?;
2375 let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && !s.is_empty() {
2376 format!("( {} )", s)
2381 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
2382 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2384 if subexpr_str.contains('\n')
2385 || first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
2387 Some(paren_wrapper(&subexpr_str))
2396 context: &RewriteContext,
2398 ) -> Option<String> {
2399 let expr_str = expr.rewrite(context, shape)?;
2401 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
2407 let offset = last_line_width(&expr_str) + lbr.len();
2408 let rhs_overhead = shape.rhs_overhead(context.config);
2409 let index_shape = if expr_str.contains('\n') {
2410 Shape::legacy(context.config.max_width(), shape.indent)
2411 .offset_left(offset)
2412 .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
2414 shape.visual_indent(offset).sub_width(offset + rbr.len())
2416 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
2418 // Return if index fits in a single line.
2419 match orig_index_rw {
2420 Some(ref index_str) if !index_str.contains('\n') => {
2421 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2426 // Try putting index on the next line and see if it fits in a single line.
2427 let indent = shape.indent.block_indent(context.config);
2428 let index_shape = Shape::indented(indent, context.config).offset_left(lbr.len())?;
2429 let index_shape = index_shape.sub_width(rbr.len() + rhs_overhead)?;
2430 let new_index_rw = index.rewrite(context, index_shape);
2431 match (orig_index_rw, new_index_rw) {
2432 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
2435 indent.to_string(context.config),
2440 (None, Some(ref new_index_str)) => Some(format!(
2443 indent.to_string(context.config),
2448 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2453 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2458 fields.iter().all(|field| !field.is_shorthand)
2461 fn rewrite_struct_lit<'a>(
2462 context: &RewriteContext,
2464 fields: &'a [ast::Field],
2465 base: Option<&'a ast::Expr>,
2468 ) -> Option<String> {
2469 debug!("rewrite_struct_lit: shape {:?}", shape);
2471 enum StructLitField<'a> {
2472 Regular(&'a ast::Field),
2473 Base(&'a ast::Expr),
2477 let path_shape = shape.sub_width(2)?;
2478 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
2480 if fields.is_empty() && base.is_none() {
2481 return Some(format!("{} {{}}", path_str));
2484 // Foo { a: Foo } - indent is +3, width is -5.
2485 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
2487 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2488 let body_lo = context.codemap.span_after(span, "{");
2489 let fields_str = if struct_lit_can_be_aligned(fields, &base)
2490 && context.config.struct_field_align_threshold() > 0
2492 rewrite_with_alignment(
2496 mk_sp(body_lo, span.hi()),
2500 let field_iter = fields
2502 .map(StructLitField::Regular)
2503 .chain(base.into_iter().map(StructLitField::Base));
2505 let span_lo = |item: &StructLitField| match *item {
2506 StructLitField::Regular(field) => field.span().lo(),
2507 StructLitField::Base(expr) => {
2508 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
2509 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
2510 let pos = snippet.find_uncommented("..").unwrap();
2511 last_field_hi + BytePos(pos as u32)
2514 let span_hi = |item: &StructLitField| match *item {
2515 StructLitField::Regular(field) => field.span().hi(),
2516 StructLitField::Base(expr) => expr.span.hi(),
2518 let rewrite = |item: &StructLitField| match *item {
2519 StructLitField::Regular(field) => {
2520 // The 1 taken from the v_budget is for the comma.
2521 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
2523 StructLitField::Base(expr) => {
2525 expr.rewrite(context, v_shape.offset_left(2)?)
2526 .map(|s| format!("..{}", s))
2530 let items = itemize_list(
2541 let item_vec = items.collect::<Vec<_>>();
2543 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2544 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2545 let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2547 write_list(&item_vec, &fmt)?
2550 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2551 Some(format!("{} {{{}}}", path_str, fields_str))
2553 // FIXME if context.config.struct_lit_style() == Visual, but we run out
2554 // of space, we should fall back to BlockIndent.
2557 pub fn wrap_struct_field(
2558 context: &RewriteContext,
2561 nested_shape: Shape,
2562 one_line_width: usize,
2564 if context.config.struct_lit_style() == IndentStyle::Block
2565 && (fields_str.contains('\n')
2566 || context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti
2567 || fields_str.len() > one_line_width)
2571 nested_shape.indent.to_string(context.config),
2573 shape.indent.to_string(context.config)
2576 // One liner or visual indent.
2577 format!(" {} ", fields_str)
2581 pub fn struct_lit_field_separator(config: &Config) -> &str {
2583 config.space_before_struct_lit_field_colon(),
2584 config.space_after_struct_lit_field_colon(),
2588 pub fn rewrite_field(
2589 context: &RewriteContext,
2592 prefix_max_width: usize,
2593 ) -> Option<String> {
2594 if contains_skip(&field.attrs) {
2595 return Some(context.snippet(field.span()));
2597 let name = &field.ident.node.to_string();
2598 if field.is_shorthand {
2599 Some(name.to_string())
2601 let mut separator = String::from(struct_lit_field_separator(context.config));
2602 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2603 separator.push(' ');
2605 let overhead = name.len() + separator.len();
2606 let expr_shape = shape.offset_left(overhead)?;
2607 let expr = field.expr.rewrite(context, expr_shape);
2609 let mut attrs_str = field.attrs.rewrite(context, shape)?;
2610 if !attrs_str.is_empty() {
2611 attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2615 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2617 let expr_offset = shape.indent.block_indent(context.config);
2620 .rewrite(context, Shape::indented(expr_offset, context.config));
2626 expr_offset.to_string(context.config),
2635 fn shape_from_fn_call_style(
2636 context: &RewriteContext,
2640 ) -> Option<Shape> {
2641 if context.use_block_indent() {
2645 .block_indent(context.config.tab_spaces())
2646 .with_max_width(context.config)
2649 shape.visual_indent(offset).sub_width(overhead)
2653 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2654 context: &RewriteContext,
2660 T: Rewrite + Spanned + ToExpr + 'a,
2662 let mut items = items.iter();
2663 // In case of length 1, need a trailing comma
2664 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2665 if items.len() == 1 {
2667 let nested_shape = shape.sub_width(3)?.visual_indent(1);
2668 return items.next().unwrap().rewrite(context, nested_shape).map(
2669 |s| if context.config.spaces_within_parens() {
2670 format!("( {}, )", s)
2677 let list_lo = context.codemap.span_after(span, "(");
2678 let nested_shape = shape.sub_width(2)?.visual_indent(1);
2679 let items = itemize_list(
2683 |item| item.span().lo(),
2684 |item| item.span().hi(),
2685 |item| item.rewrite(context, nested_shape),
2687 span.hi() - BytePos(1),
2690 let item_vec: Vec<_> = items.collect();
2691 let tactic = definitive_tactic(
2693 ListTactic::HorizontalVertical,
2697 let fmt = ListFormatting {
2700 trailing_separator: SeparatorTactic::Never,
2701 separator_place: SeparatorPlace::Back,
2703 ends_with_newline: false,
2704 preserve_newline: false,
2705 config: context.config,
2707 let list_str = write_list(&item_vec, &fmt)?;
2709 if context.config.spaces_within_parens() && !list_str.is_empty() {
2710 Some(format!("( {} )", list_str))
2712 Some(format!("({})", list_str))
2716 pub fn rewrite_tuple<'a, T>(
2717 context: &RewriteContext,
2723 T: Rewrite + Spanned + ToExpr + 'a,
2725 debug!("rewrite_tuple {:?}", shape);
2726 if context.use_block_indent() {
2727 // We use the same rule as function calls for rewriting tuples.
2728 let force_trailing_comma = if context.inside_macro {
2729 span_ends_with_comma(context, span)
2739 context.config.fn_call_width(),
2740 force_trailing_comma,
2743 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2747 pub fn rewrite_unary_prefix<R: Rewrite>(
2748 context: &RewriteContext,
2752 ) -> Option<String> {
2754 .rewrite(context, shape.offset_left(prefix.len())?)
2755 .map(|r| format!("{}{}", prefix, r))
2758 // FIXME: this is probably not correct for multi-line Rewrites. we should
2759 // subtract suffix.len() from the last line budget, not the first!
2760 pub fn rewrite_unary_suffix<R: Rewrite>(
2761 context: &RewriteContext,
2765 ) -> Option<String> {
2767 .rewrite(context, shape.sub_width(suffix.len())?)
2774 fn rewrite_unary_op(
2775 context: &RewriteContext,
2779 ) -> Option<String> {
2780 // For some reason, an UnOp is not spanned like BinOp!
2781 let operator_str = match *op {
2782 ast::UnOp::Deref => "*",
2783 ast::UnOp::Not => "!",
2784 ast::UnOp::Neg => "-",
2786 rewrite_unary_prefix(context, operator_str, expr, shape)
2789 fn rewrite_assignment(
2790 context: &RewriteContext,
2793 op: Option<&ast::BinOp>,
2795 ) -> Option<String> {
2796 let operator_str = match op {
2797 Some(op) => context.snippet(op.span),
2798 None => "=".to_owned(),
2801 // 1 = space between lhs and operator.
2802 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
2803 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
2805 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2808 // The left hand side must contain everything up to, and including, the
2809 // assignment operator.
2810 pub fn rewrite_assign_rhs<S: Into<String>>(
2811 context: &RewriteContext,
2815 ) -> Option<String> {
2816 let lhs = lhs.into();
2817 let last_line_width = last_line_width(&lhs) - if lhs.contains('\n') {
2818 shape.indent.width()
2822 // 1 = space between operator and rhs.
2823 let orig_shape = shape.offset_left(last_line_width + 1)?;
2824 let rhs = choose_rhs(context, ex, orig_shape, ex.rewrite(context, orig_shape))?;
2829 context: &RewriteContext,
2832 orig_rhs: Option<String>,
2833 ) -> Option<String> {
2835 Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
2836 Some(format!(" {}", new_str))
2839 // Expression did not fit on the same line as the identifier.
2840 // Try splitting the line and see if that works better.
2841 let new_shape = Shape::indented(
2842 shape.block().indent.block_indent(context.config),
2844 ).sub_width(shape.rhs_overhead(context.config))?;
2845 let new_rhs = expr.rewrite(context, new_shape);
2846 let new_indent_str = &new_shape.indent.to_string(context.config);
2848 match (orig_rhs, new_rhs) {
2849 (Some(ref orig_rhs), Some(ref new_rhs)) if prefer_next_line(orig_rhs, new_rhs) => {
2850 Some(format!("\n{}{}", new_indent_str, new_rhs))
2852 (None, Some(ref new_rhs)) => Some(format!("\n{}{}", new_indent_str, new_rhs)),
2853 (None, None) => None,
2854 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2860 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {
2861 fn count_line_breaks(src: &str) -> usize {
2862 src.chars().filter(|&x| x == '\n').count()
2865 !next_line_rhs.contains('\n')
2866 || count_line_breaks(orig_rhs) > count_line_breaks(next_line_rhs) + 1
2869 fn rewrite_expr_addrof(
2870 context: &RewriteContext,
2871 mutability: ast::Mutability,
2874 ) -> Option<String> {
2875 let operator_str = match mutability {
2876 ast::Mutability::Immutable => "&",
2877 ast::Mutability::Mutable => "&mut ",
2879 rewrite_unary_prefix(context, operator_str, expr, shape)
2883 fn to_expr(&self) -> Option<&ast::Expr>;
2884 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2887 impl ToExpr for ast::Expr {
2888 fn to_expr(&self) -> Option<&ast::Expr> {
2892 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2893 can_be_overflowed_expr(context, self, len)
2897 impl ToExpr for ast::Ty {
2898 fn to_expr(&self) -> Option<&ast::Expr> {
2902 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2903 can_be_overflowed_type(context, self, len)
2907 impl<'a> ToExpr for TuplePatField<'a> {
2908 fn to_expr(&self) -> Option<&ast::Expr> {
2912 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2913 can_be_overflowed_pat(context, self, len)
2917 impl<'a> ToExpr for ast::StructField {
2918 fn to_expr(&self) -> Option<&ast::Expr> {
2922 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
2927 impl<'a> ToExpr for MacroArg {
2928 fn to_expr(&self) -> Option<&ast::Expr> {
2930 MacroArg::Expr(ref expr) => Some(expr),
2935 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2937 MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
2938 MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
2939 MacroArg::Pat(..) => false,