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.
14 use std::iter::{repeat, ExactSizeIterator};
16 use syntax::{ast, ptr};
17 use syntax::codemap::{BytePos, CodeMap, Span};
18 use syntax::parse::classify;
21 use chains::rewrite_chain;
22 use codemap::{LineRangeUtils, SpanUtils};
23 use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
24 rewrite_comment, rewrite_missing_comment, FindUncommented};
25 use config::{Config, ControlBraceStyle, IndentStyle, MultilineStyle, Style};
26 use items::{span_hi_for_arg, span_lo_for_arg};
27 use lists::{definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting,
28 struct_lit_shape, struct_lit_tactic, write_list, DefinitiveListTactic, ListFormatting,
29 ListItem, ListTactic, Separator, SeparatorPlace, SeparatorTactic};
30 use macros::{rewrite_macro, MacroArg, MacroPosition};
31 use patterns::{can_be_overflowed_pat, TuplePatField};
32 use rewrite::{Rewrite, RewriteContext};
33 use shape::{Indent, Shape};
34 use string::{rewrite_string, StringFormat};
35 use types::{can_be_overflowed_type, rewrite_path, PathContext};
36 use utils::{colon_spaces, contains_skip, extra_offset, first_line_width, inner_attributes,
37 last_line_extendable, last_line_width, left_most_sub_expr, mk_sp, outer_attributes,
38 paren_overhead, ptr_vec_to_ref_vec, semicolon_for_stmt, stmt_expr,
39 trimmed_last_line_width};
40 use vertical::rewrite_with_alignment;
41 use visitor::FmtVisitor;
43 impl Rewrite for ast::Expr {
44 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
45 format_expr(self, ExprType::SubExpression, context, shape)
49 #[derive(Copy, Clone, PartialEq)]
58 context: &RewriteContext,
61 skip_out_of_file_lines_range!(context, expr.span);
63 if contains_skip(&*expr.attrs) {
64 return Some(context.snippet(expr.span()));
67 let expr_rw = match expr.node {
68 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
69 expr_vec.iter().map(|e| &**e),
70 mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi()),
75 ast::ExprKind::Lit(ref l) => match l.node {
76 ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
77 rewrite_string_lit(context, l.span, shape)
79 _ => Some(context.snippet(expr.span)),
81 ast::ExprKind::Call(ref callee, ref args) => {
82 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
83 let callee_str = try_opt!(callee.rewrite(context, shape));
84 rewrite_call(context, &callee_str, &args, inner_span, shape)
86 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
87 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
88 // FIXME: format comments between operands and operator
93 &format!(" {} ", context.snippet(op.span)),
97 context.config.binop_separator(),
100 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
101 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
105 base.as_ref().map(|e| &**e),
109 ast::ExprKind::Tup(ref items) => {
110 rewrite_tuple(context, &ptr_vec_to_ref_vec(&items), expr.span, shape)
112 ast::ExprKind::If(..) |
113 ast::ExprKind::IfLet(..) |
114 ast::ExprKind::ForLoop(..) |
115 ast::ExprKind::Loop(..) |
116 ast::ExprKind::While(..) |
117 ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
118 .and_then(|control_flow| control_flow.rewrite(context, shape)),
119 ast::ExprKind::Block(ref block) => {
121 ExprType::Statement => {
122 if is_unsafe_block(block) {
123 block.rewrite(context, shape)
124 } else if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
125 // Rewrite block without trying to put it in a single line.
128 let prefix = try_opt!(block_prefix(context, block, shape));
129 rewrite_block_with_visitor(context, &prefix, block, shape)
132 ExprType::SubExpression => block.rewrite(context, shape),
135 ast::ExprKind::Match(ref cond, ref arms) => {
136 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
138 ast::ExprKind::Path(ref qself, ref path) => {
139 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
141 ast::ExprKind::Assign(ref lhs, ref rhs) => {
142 rewrite_assignment(context, lhs, rhs, None, shape)
144 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
145 rewrite_assignment(context, lhs, rhs, Some(op), shape)
147 ast::ExprKind::Continue(ref opt_ident) => {
148 let id_str = match *opt_ident {
149 Some(ident) => format!(" {}", ident.node),
150 None => String::new(),
152 Some(format!("continue{}", id_str))
154 ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
155 let id_str = match *opt_ident {
156 Some(ident) => format!(" {}", ident.node),
157 None => String::new(),
160 if let Some(ref expr) = *opt_expr {
161 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
163 Some(format!("break{}", id_str))
166 ast::ExprKind::Yield(ref opt_expr) => if let Some(ref expr) = *opt_expr {
167 rewrite_unary_prefix(context, "yield ", &**expr, shape)
169 Some("yield".to_string())
171 ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
172 rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
174 ast::ExprKind::Try(..) |
175 ast::ExprKind::Field(..) |
176 ast::ExprKind::TupField(..) |
177 ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
178 ast::ExprKind::Mac(ref mac) => {
179 // Failure to rewrite a marco should not imply failure to
180 // rewrite the expression.
181 rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
182 .or_else(|| Some(context.snippet(expr.span)))
184 ast::ExprKind::Ret(None) => Some("return".to_owned()),
185 ast::ExprKind::Ret(Some(ref expr)) => {
186 rewrite_unary_prefix(context, "return ", &**expr, shape)
188 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
189 ast::ExprKind::AddrOf(mutability, ref expr) => {
190 rewrite_expr_addrof(context, mutability, expr, shape)
192 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
200 SeparatorPlace::Front,
202 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
210 SeparatorPlace::Back,
212 ast::ExprKind::Index(ref expr, ref index) => {
213 rewrite_index(&**expr, &**index, context, shape)
215 ast::ExprKind::Repeat(ref expr, ref repeats) => {
216 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
229 SeparatorPlace::Back,
232 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
233 let delim = match limits {
234 ast::RangeLimits::HalfOpen => "..",
235 ast::RangeLimits::Closed => "..=",
238 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
240 ast::ExprKind::Lit(ref lit) => match lit.node {
241 ast::LitKind::FloatUnsuffixed(..) => {
242 context.snippet(lit.span).ends_with('.')
250 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
251 (Some(lhs), Some(rhs)) => {
252 let sp_delim = if context.config.spaces_around_ranges() {
253 format!(" {} ", delim)
254 } else if needs_space_before_range(context, lhs) {
255 format!(" {}", delim)
267 SeparatorPlace::Front,
270 (None, Some(rhs)) => {
271 let sp_delim = if context.config.spaces_around_ranges() {
272 format!("{} ", delim)
276 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
278 (Some(lhs), None) => {
279 let sp_delim = if context.config.spaces_around_ranges() {
280 format!(" {}", delim)
284 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
286 (None, None) => Some(delim.into()),
289 // We do not format these expressions yet, but they should still
290 // satisfy our width restrictions.
291 ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => {
292 Some(context.snippet(expr.span))
294 ast::ExprKind::Catch(ref block) => {
295 if let rw @ Some(_) = rewrite_single_line_block(context, "do catch ", block, shape) {
299 let budget = shape.width.checked_sub(9).unwrap_or(0);
303 try_opt!(block.rewrite(context, Shape::legacy(budget, shape.indent)))
310 .and_then(|expr_str| {
311 recover_comment_removed(expr_str, expr.span, context)
313 .and_then(|expr_str| {
314 let attrs = outer_attributes(&expr.attrs);
315 let attrs_str = try_opt!(attrs.rewrite(context, shape));
317 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
320 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
324 pub fn rewrite_pair<LHS, RHS>(
330 context: &RewriteContext,
332 separator_place: SeparatorPlace,
338 let lhs_overhead = match separator_place {
339 SeparatorPlace::Back => shape.used_width() + prefix.len() + infix.trim_right().len(),
340 SeparatorPlace::Front => shape.used_width(),
342 let lhs_shape = Shape {
343 width: context.budget(lhs_overhead),
346 let lhs_result = try_opt!(
347 lhs.rewrite(context, lhs_shape)
348 .map(|lhs_str| format!("{}{}", prefix, lhs_str))
351 // Try to the both lhs and rhs on the same line.
352 let rhs_orig_result = shape
353 .offset_left(last_line_width(&lhs_result) + infix.len())
354 .and_then(|s| s.sub_width(suffix.len()))
355 .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
356 if let Some(ref rhs_result) = rhs_orig_result {
357 // If the rhs looks like block expression, we allow it to stay on the same line
358 // with the lhs even if it is multi-lined.
359 let allow_same_line = rhs_result
362 .map(|first_line| first_line.ends_with('{'))
364 if !rhs_result.contains('\n') || allow_same_line {
365 let one_line_width = last_line_width(&lhs_result) + infix.len()
366 + first_line_width(&rhs_result) + suffix.len();
367 if one_line_width <= shape.width {
368 return Some(format!("{}{}{}{}", lhs_result, infix, rhs_result, suffix));
373 // We have to use multiple lines.
374 // Re-evaluate the rhs because we have more space now:
375 let mut rhs_shape = try_opt!(match context.config.control_style() {
376 Style::Legacy => shape
377 .sub_width(suffix.len() + prefix.len())
378 .map(|s| s.visual_indent(prefix.len())),
380 // Try to calculate the initial constraint on the right hand side.
381 let rhs_overhead = shape.rhs_overhead(context.config);
382 Shape::indented(shape.indent.block_indent(context.config), context.config)
383 .sub_width(rhs_overhead)
386 let infix = match separator_place {
387 SeparatorPlace::Back => infix.trim_right(),
388 SeparatorPlace::Front => infix.trim_left(),
390 if separator_place == SeparatorPlace::Front {
391 rhs_shape = try_opt!(rhs_shape.offset_left(infix.len()));
393 let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape));
394 match separator_place {
395 SeparatorPlace::Back => Some(format!(
399 rhs_shape.indent.to_string(context.config),
403 SeparatorPlace::Front => Some(format!(
406 rhs_shape.indent.to_string(context.config),
414 pub fn rewrite_array<'a, I>(
417 context: &RewriteContext,
419 trailing_comma: bool,
422 I: Iterator<Item = &'a ast::Expr>,
424 let bracket_size = if context.config.spaces_within_square_brackets() {
430 let nested_shape = match context.config.array_layout() {
431 IndentStyle::Block => try_opt!(
434 .block_indent(context.config.tab_spaces())
435 .with_max_width(context.config)
438 IndentStyle::Visual => try_opt!(
440 .visual_indent(bracket_size)
441 .sub_width(bracket_size * 2)
445 let items = itemize_list(
449 |item| item.span.lo(),
450 |item| item.span.hi(),
451 |item| item.rewrite(context, nested_shape),
455 ).collect::<Vec<_>>();
457 if items.is_empty() {
458 if context.config.spaces_within_square_brackets() {
459 return Some("[ ]".to_string());
461 return Some("[]".to_string());
465 let has_long_item = items
467 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
469 let mut tactic = match context.config.array_layout() {
470 IndentStyle::Block => {
471 // FIXME wrong shape in one-line case
472 match shape.width.checked_sub(2 * bracket_size) {
475 ListTactic::LimitedHorizontalVertical(context.config.array_width());
476 definitive_tactic(&items, tactic, Separator::Comma, width)
478 None => DefinitiveListTactic::Vertical,
481 IndentStyle::Visual => if has_long_item || items.iter().any(ListItem::is_multiline) {
484 ListTactic::LimitedHorizontalVertical(context.config.array_width()),
489 DefinitiveListTactic::Mixed
492 let ends_with_newline = tactic.ends_with_newline(context.config.array_layout());
493 if context.config.array_horizontal_layout_threshold() > 0
494 && items.len() > context.config.array_horizontal_layout_threshold()
496 tactic = DefinitiveListTactic::Mixed;
499 let fmt = ListFormatting {
502 trailing_separator: if trailing_comma {
503 SeparatorTactic::Always
504 } else if context.inside_macro || context.config.array_layout() == IndentStyle::Visual {
505 SeparatorTactic::Never
507 SeparatorTactic::Vertical
509 separator_place: SeparatorPlace::Back,
511 ends_with_newline: ends_with_newline,
512 preserve_newline: false,
513 config: context.config,
515 let list_str = try_opt!(write_list(&items, &fmt));
517 let result = if context.config.array_layout() == IndentStyle::Visual
518 || tactic == DefinitiveListTactic::Horizontal
520 if context.config.spaces_within_square_brackets() && !list_str.is_empty() {
521 format!("[ {} ]", list_str)
523 format!("[{}]", list_str)
528 nested_shape.indent.to_string(context.config),
530 shape.block().indent.to_string(context.config)
537 // Return type is (prefix, extra_offset)
538 fn rewrite_closure_fn_decl(
539 capture: ast::CaptureBy,
540 fn_decl: &ast::FnDecl,
543 context: &RewriteContext,
545 ) -> Option<(String, usize)> {
546 let mover = if capture == ast::CaptureBy::Value {
551 // 4 = "|| {".len(), which is overconservative when the closure consists of
552 // a single expression.
553 let nested_shape = try_opt!(try_opt!(shape.shrink_left(mover.len())).sub_width(4));
556 let argument_offset = nested_shape.indent + 1;
557 let arg_shape = try_opt!(nested_shape.offset_left(1)).visual_indent(0);
558 let ret_str = try_opt!(fn_decl.output.rewrite(context, arg_shape));
560 let arg_items = itemize_list(
562 fn_decl.inputs.iter(),
564 |arg| span_lo_for_arg(arg),
565 |arg| span_hi_for_arg(context, arg),
566 |arg| arg.rewrite(context, arg_shape),
567 context.codemap.span_after(span, "|"),
571 let item_vec = arg_items.collect::<Vec<_>>();
572 // 1 = space between arguments and return type.
573 let horizontal_budget = nested_shape
575 .checked_sub(ret_str.len() + 1)
577 let tactic = definitive_tactic(
579 ListTactic::HorizontalVertical,
583 let arg_shape = match tactic {
584 DefinitiveListTactic::Horizontal => try_opt!(arg_shape.sub_width(ret_str.len() + 1)),
588 let fmt = ListFormatting {
591 trailing_separator: SeparatorTactic::Never,
592 separator_place: SeparatorPlace::Back,
594 ends_with_newline: false,
595 preserve_newline: true,
596 config: context.config,
598 let list_str = try_opt!(write_list(&item_vec, &fmt));
599 let mut prefix = format!("{}|{}|", mover, list_str);
600 // 1 = space between `|...|` and body.
601 let extra_offset = extra_offset(&prefix, shape) + 1;
603 if !ret_str.is_empty() {
604 if prefix.contains('\n') {
606 prefix.push_str(&argument_offset.to_string(context.config));
610 prefix.push_str(&ret_str);
613 Some((prefix, extra_offset))
616 // This functions is pretty messy because of the rules around closures and blocks:
617 // FIXME - the below is probably no longer true in full.
618 // * if there is a return type, then there must be braces,
619 // * given a closure with braces, whether that is parsed to give an inner block
620 // or not depends on if there is a return type and if there are statements
622 // * if the first expression in the body ends with a block (i.e., is a
623 // statement without needing a semi-colon), then adding or removing braces
624 // can change whether it is treated as an expression or statement.
626 capture: ast::CaptureBy,
627 fn_decl: &ast::FnDecl,
630 context: &RewriteContext,
632 ) -> Option<String> {
633 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
641 // 1 = space between `|...|` and body.
642 let body_shape = try_opt!(shape.offset_left(extra_offset));
644 if let ast::ExprKind::Block(ref block) = body.node {
645 // The body of the closure is an empty block.
646 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
647 return Some(format!("{} {{}}", prefix));
650 // Figure out if the block is necessary.
651 let needs_block = block.rules != ast::BlockCheckMode::Default || block.stmts.len() > 1
652 || context.inside_macro
653 || block_contains_comment(block, context.codemap)
654 || prefix.contains('\n');
656 let no_return_type = if let ast::FunctionRetTy::Default(_) = fn_decl.output {
661 if no_return_type && !needs_block {
662 // block.stmts.len() == 1
663 if let Some(expr) = stmt_expr(&block.stmts[0]) {
664 if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
670 // Either we require a block, or tried without and failed.
671 rewrite_closure_block(block, &prefix, context, body_shape)
673 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
674 // The closure originally had a non-block expression, but we can't fit on
675 // one line, so we'll insert a block.
676 rewrite_closure_with_block(context, body_shape, &prefix, body)
681 // Rewrite closure with a single expression wrapping its body with block.
682 fn rewrite_closure_with_block(
683 context: &RewriteContext,
687 ) -> Option<String> {
688 let block = ast::Block {
691 id: ast::NodeId::new(0),
692 node: ast::StmtKind::Expr(ptr::P(body.clone())),
696 id: ast::NodeId::new(0),
697 rules: ast::BlockCheckMode::Default,
700 rewrite_closure_block(&block, prefix, context, shape)
703 // Rewrite closure with a single expression without wrapping its body with block.
704 fn rewrite_closure_expr(
707 context: &RewriteContext,
709 ) -> Option<String> {
710 let mut rewrite = expr.rewrite(context, shape);
711 if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
712 rewrite = and_one_line(rewrite);
714 rewrite = rewrite.and_then(|rw| {
715 if context.config.multiline_closure_forces_block() && rw.contains('\n') {
721 rewrite.map(|rw| format!("{} {}", prefix, rw))
724 // Rewrite closure whose body is block.
725 fn rewrite_closure_block(
728 context: &RewriteContext,
730 ) -> Option<String> {
731 // Start with visual indent, then fall back to block indent if the
733 let block_threshold = context.config.closure_block_indent_threshold();
734 if block_threshold >= 0 {
735 if let Some(block_str) = block.rewrite(context, shape) {
736 if block_str.matches('\n').count() <= block_threshold as usize
737 && !need_block_indent(&block_str, shape)
739 if let Some(block_str) = block_str.rewrite(context, shape) {
740 return Some(format!("{} {}", prefix, block_str));
746 // The body of the closure is big enough to be block indented, that
747 // means we must re-format.
748 let block_shape = shape.block();
749 let block_str = try_opt!(block.rewrite(context, block_shape));
750 Some(format!("{} {}", prefix, block_str))
753 fn and_one_line(x: Option<String>) -> Option<String> {
754 x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
757 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
758 debug!("nop_block_collapse {:?} {}", block_str, budget);
759 block_str.map(|block_str| {
760 if block_str.starts_with('{') && budget >= 2
761 && (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
770 fn rewrite_empty_block(
771 context: &RewriteContext,
774 ) -> Option<String> {
775 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
777 return Some("{}".to_owned());
780 // If a block contains only a single-line comment, then leave it on one line.
781 let user_str = context.snippet(block.span);
782 let user_str = user_str.trim();
783 if user_str.starts_with('{') && user_str.ends_with('}') {
784 let comment_str = user_str[1..user_str.len() - 1].trim();
785 if block.stmts.is_empty() && !comment_str.contains('\n') && !comment_str.starts_with("//")
786 && comment_str.len() + 4 <= shape.width
788 return Some(format!("{{ {} }}", comment_str));
795 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
796 Some(match block.rules {
797 ast::BlockCheckMode::Unsafe(..) => {
798 let snippet = context.snippet(block.span);
799 let open_pos = try_opt!(snippet.find_uncommented("{"));
800 // Extract comment between unsafe and block start.
801 let trimmed = &snippet[6..open_pos].trim();
803 if !trimmed.is_empty() {
804 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
805 let budget = try_opt!(shape.width.checked_sub(9));
808 try_opt!(rewrite_comment(
811 Shape::legacy(budget, shape.indent + 7),
819 ast::BlockCheckMode::Default => String::new(),
823 fn rewrite_single_line_block(
824 context: &RewriteContext,
828 ) -> Option<String> {
829 if is_simple_block(block, context.codemap) {
830 let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
831 let expr_str = try_opt!(block.stmts[0].rewrite(context, expr_shape));
832 let result = format!("{}{{ {} }}", prefix, expr_str);
833 if result.len() <= shape.width && !result.contains('\n') {
840 fn rewrite_block_with_visitor(
841 context: &RewriteContext,
845 ) -> Option<String> {
846 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
850 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
851 visitor.block_indent = shape.indent;
852 visitor.is_if_else_block = context.is_if_else_block;
854 ast::BlockCheckMode::Unsafe(..) => {
855 let snippet = context.snippet(block.span);
856 let open_pos = try_opt!(snippet.find_uncommented("{"));
857 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
859 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo(),
862 visitor.visit_block(block, None);
863 Some(format!("{}{}", prefix, visitor.buffer))
866 impl Rewrite for ast::Block {
867 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
868 // shape.width is used only for the single line case: either the empty block `{}`,
869 // or an unsafe expression `unsafe { e }`.
870 if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
874 let prefix = try_opt!(block_prefix(context, self, shape));
876 let result = rewrite_block_with_visitor(context, &prefix, self, shape);
877 if let Some(ref result_str) = result {
878 if result_str.lines().count() <= 3 {
879 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
889 impl Rewrite for ast::Stmt {
890 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
891 skip_out_of_file_lines_range!(context, self.span());
893 let result = match self.node {
894 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
895 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
896 let suffix = if semicolon_for_stmt(context, self) {
902 let shape = try_opt!(shape.sub_width(suffix.len()));
903 format_expr(ex, ExprType::Statement, context, shape).map(|s| s + suffix)
905 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
907 result.and_then(|res| recover_comment_removed(res, self.span(), context))
911 // Rewrite condition if the given expression has one.
912 fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
914 ast::ExprKind::Match(ref cond, _) => {
916 let cond_shape = match context.config.control_style() {
917 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
918 Style::Rfc => try_opt!(shape.offset_left(8)),
920 cond.rewrite(context, cond_shape)
922 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
923 stmt_expr(&block.stmts[0]).and_then(|e| rewrite_cond(context, e, shape))
925 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
927 String::from("\n") + &shape.indent.block_only().to_string(context.config);
929 .rewrite_cond(context, shape, &alt_block_sep)
930 .and_then(|rw| Some(rw.0))
935 // Abstraction over control flow expressions
937 struct ControlFlow<'a> {
938 cond: Option<&'a ast::Expr>,
939 block: &'a ast::Block,
940 else_block: Option<&'a ast::Expr>,
941 label: Option<ast::SpannedIdent>,
942 pat: Option<&'a ast::Pat>,
946 allow_single_line: bool,
947 // True if this is an `if` expression in an `else if` :-( hacky
952 fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'a>> {
954 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
958 else_block.as_ref().map(|e| &**e),
959 expr_type == ExprType::SubExpression,
963 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
964 Some(ControlFlow::new_if(
968 else_block.as_ref().map(|e| &**e),
969 expr_type == ExprType::SubExpression,
974 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
975 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
977 ast::ExprKind::Loop(ref block, label) => {
978 Some(ControlFlow::new_loop(block, label, expr.span))
980 ast::ExprKind::While(ref cond, ref block, label) => {
981 Some(ControlFlow::new_while(None, cond, block, label, expr.span))
983 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
984 ControlFlow::new_while(Some(pat), cond, block, label, expr.span),
990 impl<'a> ControlFlow<'a> {
993 pat: Option<&'a ast::Pat>,
994 block: &'a ast::Block,
995 else_block: Option<&'a ast::Expr>,
996 allow_single_line: bool,
999 ) -> ControlFlow<'a> {
1003 else_block: else_block,
1007 matcher: match pat {
1012 allow_single_line: allow_single_line,
1013 nested_if: nested_if,
1019 block: &'a ast::Block,
1020 label: Option<ast::SpannedIdent>,
1022 ) -> ControlFlow<'a> {
1032 allow_single_line: false,
1039 pat: Option<&'a ast::Pat>,
1040 cond: &'a ast::Expr,
1041 block: &'a ast::Block,
1042 label: Option<ast::SpannedIdent>,
1044 ) -> ControlFlow<'a> {
1052 matcher: match pat {
1057 allow_single_line: false,
1065 cond: &'a ast::Expr,
1066 block: &'a ast::Block,
1067 label: Option<ast::SpannedIdent>,
1069 ) -> ControlFlow<'a> {
1079 allow_single_line: false,
1085 fn rewrite_single_line(
1088 context: &RewriteContext,
1090 ) -> Option<String> {
1091 assert!(self.allow_single_line);
1092 let else_block = try_opt!(self.else_block);
1093 let fixed_cost = self.keyword.len() + " { } else { }".len();
1095 if let ast::ExprKind::Block(ref else_node) = else_block.node {
1096 if !is_simple_block(self.block, context.codemap)
1097 || !is_simple_block(else_node, context.codemap)
1098 || pat_expr_str.contains('\n')
1103 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
1104 let expr = &self.block.stmts[0];
1105 let if_str = try_opt!(expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
1107 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
1108 let else_expr = &else_node.stmts[0];
1110 try_opt!(else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
1112 if if_str.contains('\n') || else_str.contains('\n') {
1116 let result = format!(
1117 "{} {} {{ {} }} else {{ {} }}",
1124 if result.len() <= width {
1125 return Some(result);
1133 impl<'a> ControlFlow<'a> {
1136 context: &RewriteContext,
1138 alt_block_sep: &str,
1139 ) -> Option<(String, usize)> {
1140 // Do not take the rhs overhead from the upper expressions into account
1141 // when rewriting pattern.
1142 let new_width = context
1145 .checked_sub(shape.used_width())
1147 let fresh_shape = Shape {
1151 let constr_shape = if self.nested_if {
1152 // We are part of an if-elseif-else chain. Our constraints are tightened.
1153 // 7 = "} else " .len()
1154 try_opt!(fresh_shape.offset_left(7))
1159 let label_string = rewrite_label(self.label);
1160 // 1 = space after keyword.
1161 let offset = self.keyword.len() + label_string.len() + 1;
1163 let pat_expr_string = match self.cond {
1165 let cond_shape = match context.config.control_style() {
1166 Style::Legacy => try_opt!(constr_shape.shrink_left(offset)),
1167 Style::Rfc => try_opt!(constr_shape.offset_left(offset)),
1169 try_opt!(rewrite_pat_expr(
1179 None => String::new(),
1182 let brace_overhead =
1183 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1189 let one_line_budget = context
1192 .checked_sub(constr_shape.used_width() + offset + brace_overhead)
1194 let force_newline_brace = context.config.control_style() == Style::Rfc
1195 && (pat_expr_string.contains('\n') || pat_expr_string.len() > one_line_budget)
1196 && !last_line_extendable(&pat_expr_string);
1198 // Try to format if-else on single line.
1199 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1200 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1202 if let Some(cond_str) = trial {
1203 if cond_str.len() <= context.config.single_line_if_else_max_width() {
1204 return Some((cond_str, 0));
1209 let cond_span = if let Some(cond) = self.cond {
1212 mk_sp(self.block.span.lo(), self.block.span.lo())
1215 // `for event in event`
1216 // Do not include label in the span.
1217 let lo = self.label.map_or(self.span.lo(), |label| label.span.hi());
1218 let between_kwd_cond = mk_sp(
1221 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
1223 .map_or(cond_span.lo(), |p| if self.matcher.is_empty() {
1226 context.codemap.span_before(self.span, self.matcher.trim())
1230 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1232 let after_cond_comment =
1233 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
1235 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1237 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
1238 || force_newline_brace
1245 let used_width = if pat_expr_string.contains('\n') {
1246 last_line_width(&pat_expr_string)
1248 // 2 = spaces after keyword and condition.
1249 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1257 between_kwd_cond_comment.as_ref().map_or(
1258 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1266 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1273 impl<'a> Rewrite for ControlFlow<'a> {
1274 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1275 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1278 String::from("\n") + &shape.indent.block_only().to_string(context.config);
1279 let (cond_str, used_width) = try_opt!(self.rewrite_cond(context, shape, &alt_block_sep));
1280 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1281 if used_width == 0 {
1282 return Some(cond_str);
1285 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1286 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1287 // we should avoid the single line case.
1288 let block_width = if self.else_block.is_some() || self.nested_if {
1293 let block_shape = Shape {
1297 let mut block_context = context.clone();
1298 block_context.is_if_else_block = self.else_block.is_some();
1299 let block_str = try_opt!(rewrite_block_with_visitor(
1306 let mut result = format!("{}{}", cond_str, block_str);
1308 if let Some(else_block) = self.else_block {
1309 let shape = Shape::indented(shape.indent, context.config);
1310 let mut last_in_chain = false;
1311 let rewrite = match else_block.node {
1312 // If the else expression is another if-else expression, prevent it
1313 // from being formatted on a single line.
1314 // Note how we're passing the original shape, as the
1315 // cost of "else" should not cascade.
1316 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1317 ControlFlow::new_if(
1321 next_else_block.as_ref().map(|e| &**e),
1324 mk_sp(else_block.span.lo(), self.span.hi()),
1325 ).rewrite(context, shape)
1327 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1328 ControlFlow::new_if(
1332 next_else_block.as_ref().map(|e| &**e),
1335 mk_sp(else_block.span.lo(), self.span.hi()),
1336 ).rewrite(context, shape)
1339 last_in_chain = true;
1340 // When rewriting a block, the width is only used for single line
1341 // blocks, passing 1 lets us avoid that.
1342 let else_shape = Shape {
1343 width: min(1, shape.width),
1346 format_expr(else_block, ExprType::Statement, context, else_shape)
1350 let between_kwd_else_block = mk_sp(
1351 self.block.span.hi(),
1354 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1356 let between_kwd_else_block_comment =
1357 extract_comment(between_kwd_else_block, context, shape);
1359 let after_else = mk_sp(
1362 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1363 else_block.span.lo(),
1365 let after_else_comment = extract_comment(after_else, context, shape);
1367 let between_sep = match context.config.control_brace_style() {
1368 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1371 ControlBraceStyle::AlwaysSameLine => " ",
1373 let after_sep = match context.config.control_brace_style() {
1374 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1381 between_kwd_else_block_comment
1383 .map_or(between_sep, |s| &**s),
1384 after_else_comment.as_ref().map_or(after_sep, |s| &**s)
1387 result.push_str(&try_opt!(rewrite));
1394 fn rewrite_label(label: Option<ast::SpannedIdent>) -> Cow<'static, str> {
1396 Some(ident) => Cow::from(format!("{}: ", ident.node)),
1397 None => Cow::from(""),
1401 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1402 match rewrite_missing_comment(span, shape, context) {
1403 Some(ref comment) if !comment.is_empty() => Some(format!(
1404 "\n{indent}{}\n{indent}",
1406 indent = shape.indent.to_string(context.config)
1412 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1413 let snippet = codemap.span_to_snippet(block.span).unwrap();
1414 contains_comment(&snippet)
1417 // Checks that a block contains no statements, an expression and no comments.
1418 // FIXME: incorrectly returns false when comment is contained completely within
1420 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1421 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0])
1422 && !block_contains_comment(block, codemap))
1425 /// Checks whether a block contains at most one statement or expression, and no comments.
1426 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1427 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1430 /// Checks whether a block contains no statements, expressions, or comments.
1431 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1432 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1435 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1437 ast::StmtKind::Expr(..) => true,
1442 fn is_unsafe_block(block: &ast::Block) -> bool {
1443 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1450 // A simple wrapper type against ast::Arm. Used inside write_list().
1451 struct ArmWrapper<'a> {
1452 pub arm: &'a ast::Arm,
1453 // True if the arm is the last one in match expression. Used to decide on whether we should add
1454 // trailing comma to the match arm when `config.trailing_comma() == Never`.
1458 impl<'a> ArmWrapper<'a> {
1459 pub fn new(arm: &'a ast::Arm, is_last: bool) -> ArmWrapper<'a> {
1460 ArmWrapper { arm, is_last }
1464 impl<'a> Rewrite for ArmWrapper<'a> {
1465 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1466 rewrite_match_arm(context, self.arm, shape, self.is_last)
1471 context: &RewriteContext,
1476 attrs: &[ast::Attribute],
1477 ) -> Option<String> {
1478 if arms.is_empty() {
1482 // Do not take the rhs overhead from the upper expressions into account
1483 // when rewriting match condition.
1484 let new_width = try_opt!(context.config.max_width().checked_sub(shape.used_width()));
1485 let cond_shape = Shape {
1490 let cond_shape = match context.config.control_style() {
1491 Style::Legacy => try_opt!(cond_shape.shrink_left(6)),
1492 Style::Rfc => try_opt!(cond_shape.offset_left(6)),
1494 let cond_str = try_opt!(cond.rewrite(context, cond_shape));
1495 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1496 let block_sep = match context.config.control_brace_style() {
1497 ControlBraceStyle::AlwaysNextLine => &alt_block_sep,
1498 _ if last_line_extendable(&cond_str) => " ",
1500 _ if cond_str.contains('\n') || cond_str.len() + 2 > cond_shape.width => &alt_block_sep,
1504 let nested_indent_str = shape
1506 .block_indent(context.config)
1507 .to_string(context.config);
1508 // Inner attributes.
1509 let inner_attrs = &inner_attributes(attrs);
1510 let inner_attrs_str = if inner_attrs.is_empty() {
1515 .rewrite(context, shape)
1516 .map(|s| format!("{}{}\n", nested_indent_str, s))
1520 let open_brace_pos = if inner_attrs.is_empty() {
1523 .span_after(mk_sp(cond.span.hi(), arms[0].span().lo()), "{")
1525 inner_attrs[inner_attrs.len() - 1].span().hi()
1528 let arm_indent_str = if context.config.indent_match_arms() {
1531 shape.indent.to_string(context.config)
1535 "match {}{}{{\n{}{}{}\n{}}}",
1540 try_opt!(rewrite_match_arms(
1547 shape.indent.to_string(context.config),
1551 fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
1552 if is_last && config.trailing_comma() == SeparatorTactic::Never {
1554 } else if config.match_block_trailing_comma() {
1556 } else if let ast::ExprKind::Block(ref block) = body.node {
1557 if let ast::BlockCheckMode::Default = block.rules {
1567 fn rewrite_match_arms(
1568 context: &RewriteContext,
1572 open_brace_pos: BytePos,
1573 ) -> Option<String> {
1574 let arm_shape = if context.config.indent_match_arms() {
1575 shape.block_indent(context.config.tab_spaces())
1577 shape.block_indent(0)
1578 }.with_max_width(context.config);
1580 let arm_len = arms.len();
1581 let is_last_iter = repeat(false)
1582 .take(arm_len.checked_sub(1).unwrap_or(0))
1583 .chain(repeat(true));
1584 let items = itemize_list(
1588 .map(|(arm, is_last)| ArmWrapper::new(arm, is_last)),
1590 |arm| arm.arm.span().lo(),
1591 |arm| arm.arm.span().hi(),
1592 |arm| arm.rewrite(context, arm_shape),
1597 let arms_vec: Vec<_> = items.collect();
1598 let fmt = ListFormatting {
1599 tactic: DefinitiveListTactic::Vertical,
1600 // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
1602 trailing_separator: SeparatorTactic::Never,
1603 separator_place: SeparatorPlace::Back,
1605 ends_with_newline: true,
1606 preserve_newline: true,
1607 config: context.config,
1610 write_list(&arms_vec, &fmt)
1613 fn rewrite_match_arm(
1614 context: &RewriteContext,
1618 ) -> Option<String> {
1619 let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
1620 if contains_skip(&arm.attrs) {
1621 let (_, body) = flatten_arm_body(context, &arm.body);
1622 // `arm.span()` does not include trailing comma, add it manually.
1623 return Some(format!(
1625 context.snippet(arm.span()),
1626 arm_comma(context.config, body, is_last),
1631 arm.attrs[arm.attrs.len() - 1].span.hi(),
1632 arm.pats[0].span.lo(),
1634 try_opt!(arm.attrs.rewrite(context, shape)),
1637 (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
1639 let pats_str = try_opt!(
1640 rewrite_match_pattern(context, &arm.pats, &arm.guard, shape).and_then(|pats_str| {
1641 combine_strs_with_missing_comments(
1656 arm.guard.is_some(),
1661 fn rewrite_match_pattern(
1662 context: &RewriteContext,
1663 pats: &[ptr::P<ast::Pat>],
1664 guard: &Option<ptr::P<ast::Expr>>,
1666 ) -> Option<String> {
1669 let pat_shape = try_opt!(shape.sub_width(5));
1671 let pat_strs = try_opt!(
1673 .map(|p| p.rewrite(context, pat_shape))
1674 .collect::<Option<Vec<_>>>()
1677 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1678 let tactic = definitive_tactic(
1680 ListTactic::HorizontalVertical,
1681 Separator::VerticalBar,
1684 let fmt = ListFormatting {
1687 trailing_separator: SeparatorTactic::Never,
1688 separator_place: context.config.match_pattern_separator_break_point(),
1690 ends_with_newline: false,
1691 preserve_newline: false,
1692 config: context.config,
1694 let pats_str = try_opt!(write_list(&items, &fmt));
1697 let guard_str = try_opt!(rewrite_guard(
1701 trimmed_last_line_width(&pats_str),
1704 Some(format!("{}{}", pats_str, guard_str))
1708 // @extend: true if the arm body can be put next to `=>`
1709 // @body: flattened body, if the body is block with a single expression
1710 fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bool, &'a ast::Expr) {
1712 ast::ExprKind::Block(ref block)
1713 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) =>
1715 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1717 !context.config.multiline_match_arm_forces_block()
1718 && expr.can_be_overflowed(context, 1),
1726 !context.config.multiline_match_arm_forces_block()
1727 && body.can_be_overflowed(context, 1),
1733 fn rewrite_match_body(
1734 context: &RewriteContext,
1735 body: &ptr::P<ast::Expr>,
1740 ) -> Option<String> {
1741 let (extend, body) = flatten_arm_body(context, body);
1743 let comma = arm_comma(context.config, body, is_last);
1744 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1745 let alt_block_sep = alt_block_sep.as_str();
1746 let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
1747 (true, is_empty_block(block, context.codemap))
1752 let combine_orig_body = |body_str: &str| {
1753 let block_sep = match context.config.control_brace_style() {
1754 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
1758 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
1761 let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
1762 let next_line_indent = if is_block {
1765 shape.indent.block_indent(context.config)
1767 let combine_next_line_body = |body_str: &str| {
1769 return Some(format!(
1772 next_line_indent.to_string(context.config),
1777 let indent_str = shape.indent.to_string(context.config);
1778 let nested_indent_str = next_line_indent.to_string(context.config);
1779 let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1780 let comma = if context.config.match_block_trailing_comma() {
1785 ("{", format!("\n{}}}{}", indent_str, comma))
1787 ("", String::from(","))
1790 let block_sep = match context.config.control_brace_style() {
1791 ControlBraceStyle::AlwaysNextLine => format!("{}{}\n", alt_block_sep, body_prefix),
1792 _ if body_prefix.is_empty() => "\n".to_owned(),
1793 _ if forbid_same_line => format!("{}{}\n", alt_block_sep, body_prefix),
1794 _ => format!(" {}\n", body_prefix),
1795 } + &nested_indent_str;
1806 // Let's try and get the arm body on the same line as the condition.
1808 let orig_body_shape = shape
1809 .offset_left(extra_offset(pats_str, shape) + 4)
1810 .and_then(|shape| shape.sub_width(comma.len()));
1811 let orig_body = if let Some(body_shape) = orig_body_shape {
1812 let rewrite = nop_block_collapse(
1813 format_expr(body, ExprType::Statement, context, body_shape),
1819 if !forbid_same_line
1821 || (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
1823 return combine_orig_body(body_str);
1830 let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
1832 // Try putting body on the next line and see if it looks better.
1833 let next_line_body_shape = Shape::indented(next_line_indent, context.config);
1834 let next_line_body = nop_block_collapse(
1835 format_expr(body, ExprType::Statement, context, next_line_body_shape),
1836 next_line_body_shape.width,
1838 match (orig_body, next_line_body) {
1839 (Some(ref orig_str), Some(ref next_line_str))
1840 if forbid_same_line || prefer_next_line(orig_str, next_line_str) =>
1842 combine_next_line_body(next_line_str)
1844 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
1845 combine_orig_body(orig_str)
1847 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
1848 combine_next_line_body(next_line_str)
1850 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
1851 (None, None) => None,
1852 (Some(ref orig_str), _) => combine_orig_body(orig_str),
1856 // The `if ...` guard on a match arm.
1858 context: &RewriteContext,
1859 guard: &Option<ptr::P<ast::Expr>>,
1861 // The amount of space used up on this line for the pattern in
1862 // the arm (excludes offset).
1863 pattern_width: usize,
1864 ) -> Option<String> {
1865 if let Some(ref guard) = *guard {
1866 // First try to fit the guard string on the same line as the pattern.
1867 // 4 = ` if `, 5 = ` => {`
1868 let cond_shape = shape
1869 .offset_left(pattern_width + 4)
1870 .and_then(|s| s.sub_width(5));
1871 if let Some(cond_shape) = cond_shape {
1872 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1873 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
1874 return Some(format!(" if {}", cond_str));
1879 // Not enough space to put the guard after the pattern, try a newline.
1880 // 3 = `if `, 5 = ` => {`
1881 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
1883 .and_then(|s| s.sub_width(5));
1884 if let Some(cond_shape) = cond_shape {
1885 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1886 return Some(format!(
1888 cond_shape.indent.to_string(context.config),
1900 fn rewrite_pat_expr(
1901 context: &RewriteContext,
1902 pat: Option<&ast::Pat>,
1905 // Connecting piece between pattern and expression,
1906 // *without* trailing space.
1910 ) -> Option<String> {
1911 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1912 if let Some(pat) = pat {
1913 let matcher = if matcher.is_empty() {
1916 format!("{} ", matcher)
1919 try_opt!(try_opt!(shape.offset_left(matcher.len())).sub_width(connector.len()));
1920 let pat_string = try_opt!(pat.rewrite(context, pat_shape));
1921 let result = format!("{}{}{}", matcher, pat_string, connector);
1922 return rewrite_assign_rhs(context, result, expr, shape);
1925 let expr_rw = expr.rewrite(context, shape);
1926 // The expression may (partially) fit on the current line.
1927 // We do not allow splitting between `if` and condition.
1928 if keyword == "if" || expr_rw.is_some() {
1932 // The expression won't fit on the current line, jump to next.
1933 let nested_shape = shape
1934 .block_indent(context.config.tab_spaces())
1935 .with_max_width(context.config);
1936 let nested_indent_str = nested_shape.indent.to_string(context.config);
1937 expr.rewrite(context, nested_shape)
1938 .map(|expr_rw| format!("\n{}{}", nested_indent_str, expr_rw))
1941 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1942 let string_lit = context.snippet(span);
1944 if !context.config.format_strings() && !context.config.force_format_strings() {
1949 .all(|line| line.ends_with('\\'))
1951 let new_indent = shape.visual_indent(1).indent;
1952 return Some(String::from(
1958 new_indent.to_string(context.config),
1962 .collect::<Vec<_>>()
1967 return Some(string_lit);
1971 if !context.config.force_format_strings()
1972 && !string_requires_rewrite(context, span, &string_lit, shape)
1974 return Some(string_lit);
1977 let fmt = StringFormat {
1984 config: context.config,
1987 // Remove the quote characters.
1988 let str_lit = &string_lit[1..string_lit.len() - 1];
1990 rewrite_string(str_lit, &fmt)
1993 fn string_requires_rewrite(
1994 context: &RewriteContext,
1999 if context.codemap.lookup_char_pos(span.lo()).col.0 != shape.indent.width() {
2003 for (i, line) in string.lines().enumerate() {
2005 if line.len() > shape.width {
2008 } else if line.len() > shape.width + shape.indent.width() {
2016 pub fn rewrite_call(
2017 context: &RewriteContext,
2019 args: &[ptr::P<ast::Expr>],
2022 ) -> Option<String> {
2023 let force_trailing_comma = if context.inside_macro {
2024 span_ends_with_comma(context, span)
2031 &ptr_vec_to_ref_vec(&args),
2034 context.config.fn_call_width(),
2035 force_trailing_comma,
2039 pub fn rewrite_call_inner<'a, T>(
2040 context: &RewriteContext,
2045 args_max_width: usize,
2046 force_trailing_comma: bool,
2049 T: Rewrite + Spanned + ToExpr + 'a,
2051 // 2 = `( `, 1 = `(`
2052 let paren_overhead = if context.config.spaces_within_parens() {
2057 let used_width = extra_offset(callee_str, shape);
2058 let one_line_width = try_opt!(shape.width.checked_sub(used_width + 2 * paren_overhead));
2060 let nested_shape = try_opt!(shape_from_fn_call_style(
2063 used_width + 2 * paren_overhead,
2064 used_width + paren_overhead,
2067 let span_lo = context.codemap.span_after(span, "(");
2068 let args_span = mk_sp(span_lo, span.hi());
2070 let (extendable, list_str) = try_opt!(rewrite_call_args(
2077 force_trailing_comma,
2080 if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
2081 let mut new_context = context.clone();
2082 new_context.use_block = true;
2083 return rewrite_call_inner(
2090 force_trailing_comma,
2094 let args_shape = try_opt!(shape.sub_width(last_line_width(callee_str)));
2098 wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2102 fn need_block_indent(s: &str, shape: Shape) -> bool {
2103 s.lines().skip(1).any(|s| {
2104 s.find(|c| !char::is_whitespace(c))
2105 .map_or(false, |w| w + 1 < shape.indent.width())
2109 fn rewrite_call_args<'a, T>(
2110 context: &RewriteContext,
2114 one_line_width: usize,
2115 args_max_width: usize,
2116 force_trailing_comma: bool,
2117 ) -> Option<(bool, String)>
2119 T: Rewrite + Spanned + ToExpr + 'a,
2121 let items = itemize_list(
2125 |item| item.span().lo(),
2126 |item| item.span().hi(),
2127 |item| item.rewrite(context, shape),
2132 let mut item_vec: Vec<_> = items.collect();
2134 // Try letting the last argument overflow to the next line with block
2135 // indentation. If its first line fits on one line with the other arguments,
2136 // we format the function arguments horizontally.
2137 let tactic = try_overflow_last_arg(
2146 let fmt = ListFormatting {
2149 trailing_separator: if force_trailing_comma {
2150 SeparatorTactic::Always
2151 } else if context.inside_macro || !context.use_block_indent() {
2152 SeparatorTactic::Never
2154 context.config.trailing_comma()
2156 separator_place: SeparatorPlace::Back,
2158 ends_with_newline: context.use_block_indent() && tactic == DefinitiveListTactic::Vertical,
2159 preserve_newline: false,
2160 config: context.config,
2163 write_list(&item_vec, &fmt).map(|args_str| {
2164 (tactic != DefinitiveListTactic::Vertical, args_str)
2168 fn try_overflow_last_arg<'a, T>(
2169 context: &RewriteContext,
2170 item_vec: &mut Vec<ListItem>,
2173 one_line_width: usize,
2174 args_max_width: usize,
2175 ) -> DefinitiveListTactic
2177 T: Rewrite + Spanned + ToExpr + 'a,
2179 let overflow_last = can_be_overflowed(context, args);
2181 // Replace the last item with its first line to see if it fits with
2183 let placeholder = if overflow_last {
2184 let mut context = context.clone();
2185 if let Some(expr) = args[args.len() - 1].to_expr() {
2186 if let ast::ExprKind::MethodCall(..) = expr.node {
2187 context.force_one_line_chain = true;
2190 last_arg_shape(&context, item_vec, shape, args_max_width).and_then(|arg_shape| {
2191 rewrite_last_arg_with_overflow(&context, args, &mut item_vec[args.len() - 1], arg_shape)
2197 let mut tactic = definitive_tactic(
2199 ListTactic::LimitedHorizontalVertical(args_max_width),
2204 // Replace the stub with the full overflowing last argument if the rewrite
2205 // succeeded and its first line fits with the other arguments.
2206 match (overflow_last, tactic, placeholder) {
2207 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2208 item_vec[args.len() - 1].item = placeholder;
2210 _ if args.len() >= 1 => {
2211 item_vec[args.len() - 1].item = args.last()
2212 .and_then(|last_arg| last_arg.rewrite(context, shape));
2213 // Use horizontal layout for a function with a single argument as long as
2214 // everything fits in a single line.
2216 && args_max_width != 0 // Vertical layout is forced.
2217 && !item_vec[0].has_comment()
2218 && !item_vec[0].inner_as_ref().contains('\n')
2219 && ::lists::total_item_width(&item_vec[0]) <= one_line_width
2221 tactic = DefinitiveListTactic::Horizontal;
2223 tactic = definitive_tactic(
2225 ListTactic::LimitedHorizontalVertical(args_max_width),
2238 context: &RewriteContext,
2241 args_max_width: usize,
2242 ) -> Option<Shape> {
2243 let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
2244 acc + i.item.as_ref().map_or(0, |s| first_line_width(s))
2246 let max_width = min(args_max_width, shape.width);
2247 let arg_indent = if context.use_block_indent() {
2248 shape.block().indent.block_unindent(context.config)
2250 shape.block().indent
2253 width: try_opt!(max_width.checked_sub(overhead)),
2259 // Rewriting closure which is placed at the end of the function call's arg.
2260 // Returns `None` if the reformatted closure 'looks bad'.
2261 fn rewrite_last_closure(
2262 context: &RewriteContext,
2265 ) -> Option<String> {
2266 if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
2267 let body = match body.node {
2268 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
2269 stmt_expr(&block.stmts[0]).unwrap_or(body)
2273 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
2281 // If the closure goes multi line before its body, do not overflow the closure.
2282 if prefix.contains('\n') {
2285 let body_shape = try_opt!(shape.offset_left(extra_offset));
2286 // When overflowing the closure which consists of a single control flow expression,
2287 // force to use block if its condition uses multi line.
2288 let is_multi_lined_cond = rewrite_cond(context, body, body_shape)
2289 .map(|cond| cond.contains('\n') || cond.len() > body_shape.width)
2291 if is_multi_lined_cond {
2292 return rewrite_closure_with_block(context, body_shape, &prefix, body);
2295 // Seems fine, just format the closure in usual manner.
2296 return expr.rewrite(context, shape);
2301 fn rewrite_last_arg_with_overflow<'a, T>(
2302 context: &RewriteContext,
2304 last_item: &mut ListItem,
2308 T: Rewrite + Spanned + ToExpr + 'a,
2310 let last_arg = args[args.len() - 1];
2311 let rewrite = if let Some(expr) = last_arg.to_expr() {
2313 // When overflowing the closure which consists of a single control flow expression,
2314 // force to use block if its condition uses multi line.
2315 ast::ExprKind::Closure(..) => {
2316 // If the argument consists of multiple closures, we do not overflow
2317 // the last closure.
2322 .filter_map(|arg| arg.to_expr())
2323 .any(|expr| match expr.node {
2324 ast::ExprKind::Closure(..) => true,
2329 rewrite_last_closure(context, expr, shape)
2332 _ => expr.rewrite(context, shape),
2335 last_arg.rewrite(context, shape)
2338 if let Some(rewrite) = rewrite {
2339 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2340 last_item.item = rewrite_first_line;
2347 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2349 T: Rewrite + Spanned + ToExpr + 'a,
2352 .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2355 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2357 ast::ExprKind::Match(..) => {
2358 (context.use_block_indent() && args_len == 1)
2359 || (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
2361 ast::ExprKind::If(..) |
2362 ast::ExprKind::IfLet(..) |
2363 ast::ExprKind::ForLoop(..) |
2364 ast::ExprKind::Loop(..) |
2365 ast::ExprKind::While(..) |
2366 ast::ExprKind::WhileLet(..) => {
2367 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2369 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
2370 context.use_block_indent()
2371 || context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
2373 ast::ExprKind::Array(..) |
2374 ast::ExprKind::Call(..) |
2375 ast::ExprKind::Mac(..) |
2376 ast::ExprKind::MethodCall(..) |
2377 ast::ExprKind::Struct(..) |
2378 ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2379 ast::ExprKind::AddrOf(_, ref expr) |
2380 ast::ExprKind::Box(ref expr) |
2381 ast::ExprKind::Try(ref expr) |
2382 ast::ExprKind::Unary(_, ref expr) |
2383 ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2388 pub fn wrap_args_with_parens(
2389 context: &RewriteContext,
2391 is_extendable: bool,
2393 nested_shape: Shape,
2395 if !context.use_block_indent()
2396 || (context.inside_macro && !args_str.contains('\n')
2397 && args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2399 if context.config.spaces_within_parens() && !args_str.is_empty() {
2400 format!("( {} )", args_str)
2402 format!("({})", args_str)
2407 nested_shape.indent.to_string(context.config),
2409 shape.block().indent.to_string(context.config)
2414 fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2415 let snippet = context.snippet(span);
2417 .trim_right_matches(|c: char| c == ')' || c.is_whitespace())
2421 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2422 debug!("rewrite_paren, shape: {:?}", shape);
2423 let total_paren_overhead = paren_overhead(context);
2424 let paren_overhead = total_paren_overhead / 2;
2425 let sub_shape = try_opt!(
2427 .offset_left(paren_overhead)
2428 .and_then(|s| s.sub_width(paren_overhead))
2431 let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && !s.is_empty() {
2432 format!("( {} )", s)
2437 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2438 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2440 if subexpr_str.contains('\n')
2441 || first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
2443 Some(paren_wrapper(&subexpr_str))
2452 context: &RewriteContext,
2454 ) -> Option<String> {
2455 let expr_str = try_opt!(expr.rewrite(context, shape));
2457 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
2463 let offset = last_line_width(&expr_str) + lbr.len();
2464 let rhs_overhead = shape.rhs_overhead(context.config);
2465 let index_shape = if expr_str.contains('\n') {
2466 Shape::legacy(context.config.max_width(), shape.indent)
2467 .offset_left(offset)
2468 .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
2470 shape.visual_indent(offset).sub_width(offset + rbr.len())
2472 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
2474 // Return if index fits in a single line.
2475 match orig_index_rw {
2476 Some(ref index_str) if !index_str.contains('\n') => {
2477 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2482 // Try putting index on the next line and see if it fits in a single line.
2483 let indent = shape.indent.block_indent(context.config);
2484 let index_shape = try_opt!(Shape::indented(indent, context.config).offset_left(lbr.len()));
2485 let index_shape = try_opt!(index_shape.sub_width(rbr.len() + rhs_overhead));
2486 let new_index_rw = index.rewrite(context, index_shape);
2487 match (orig_index_rw, new_index_rw) {
2488 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
2491 indent.to_string(context.config),
2496 (None, Some(ref new_index_str)) => Some(format!(
2499 indent.to_string(context.config),
2504 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2509 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2514 fields.iter().all(|field| !field.is_shorthand)
2517 fn rewrite_struct_lit<'a>(
2518 context: &RewriteContext,
2520 fields: &'a [ast::Field],
2521 base: Option<&'a ast::Expr>,
2524 ) -> Option<String> {
2525 debug!("rewrite_struct_lit: shape {:?}", shape);
2527 enum StructLitField<'a> {
2528 Regular(&'a ast::Field),
2529 Base(&'a ast::Expr),
2533 let path_shape = try_opt!(shape.sub_width(2));
2534 let path_str = try_opt!(rewrite_path(
2542 if fields.is_empty() && base.is_none() {
2543 return Some(format!("{} {{}}", path_str));
2546 // Foo { a: Foo } - indent is +3, width is -5.
2547 let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
2549 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2550 let body_lo = context.codemap.span_after(span, "{");
2551 let fields_str = if struct_lit_can_be_aligned(fields, &base)
2552 && context.config.struct_field_align_threshold() > 0
2554 try_opt!(rewrite_with_alignment(
2558 mk_sp(body_lo, span.hi()),
2562 let field_iter = fields
2564 .map(StructLitField::Regular)
2565 .chain(base.into_iter().map(StructLitField::Base));
2567 let span_lo = |item: &StructLitField| match *item {
2568 StructLitField::Regular(field) => field.span().lo(),
2569 StructLitField::Base(expr) => {
2570 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
2571 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
2572 let pos = snippet.find_uncommented("..").unwrap();
2573 last_field_hi + BytePos(pos as u32)
2576 let span_hi = |item: &StructLitField| match *item {
2577 StructLitField::Regular(field) => field.span().hi(),
2578 StructLitField::Base(expr) => expr.span.hi(),
2580 let rewrite = |item: &StructLitField| match *item {
2581 StructLitField::Regular(field) => {
2582 // The 1 taken from the v_budget is for the comma.
2583 rewrite_field(context, field, try_opt!(v_shape.sub_width(1)), 0)
2585 StructLitField::Base(expr) => {
2587 expr.rewrite(context, try_opt!(v_shape.offset_left(2)))
2588 .map(|s| format!("..{}", s))
2592 let items = itemize_list(
2603 let item_vec = items.collect::<Vec<_>>();
2605 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2606 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2607 let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2609 try_opt!(write_list(&item_vec, &fmt))
2612 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2613 Some(format!("{} {{{}}}", path_str, fields_str))
2615 // FIXME if context.config.struct_lit_style() == Visual, but we run out
2616 // of space, we should fall back to BlockIndent.
2619 pub fn wrap_struct_field(
2620 context: &RewriteContext,
2623 nested_shape: Shape,
2624 one_line_width: usize,
2626 if context.config.struct_lit_style() == IndentStyle::Block
2627 && (fields_str.contains('\n')
2628 || context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti
2629 || fields_str.len() > one_line_width)
2633 nested_shape.indent.to_string(context.config),
2635 shape.indent.to_string(context.config)
2638 // One liner or visual indent.
2639 format!(" {} ", fields_str)
2643 pub fn struct_lit_field_separator(config: &Config) -> &str {
2645 config.space_before_struct_lit_field_colon(),
2646 config.space_after_struct_lit_field_colon(),
2650 pub fn rewrite_field(
2651 context: &RewriteContext,
2654 prefix_max_width: usize,
2655 ) -> Option<String> {
2656 if contains_skip(&field.attrs) {
2657 return Some(context.snippet(field.span()));
2659 let name = &field.ident.node.to_string();
2660 if field.is_shorthand {
2661 Some(name.to_string())
2663 let mut separator = String::from(struct_lit_field_separator(context.config));
2664 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2665 separator.push(' ');
2667 let overhead = name.len() + separator.len();
2668 let expr_shape = try_opt!(shape.offset_left(overhead));
2669 let expr = field.expr.rewrite(context, expr_shape);
2671 let mut attrs_str = try_opt!(field.attrs.rewrite(context, shape));
2672 if !attrs_str.is_empty() {
2673 attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2677 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2679 let expr_offset = shape.indent.block_indent(context.config);
2682 .rewrite(context, Shape::indented(expr_offset, context.config));
2688 expr_offset.to_string(context.config),
2697 fn shape_from_fn_call_style(
2698 context: &RewriteContext,
2702 ) -> Option<Shape> {
2703 if context.use_block_indent() {
2707 .block_indent(context.config.tab_spaces())
2708 .with_max_width(context.config)
2711 shape.visual_indent(offset).sub_width(overhead)
2715 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2716 context: &RewriteContext,
2722 T: Rewrite + Spanned + ToExpr + 'a,
2724 let mut items = items.iter();
2725 // In case of length 1, need a trailing comma
2726 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2727 if items.len() == 1 {
2729 let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
2730 return items.next().unwrap().rewrite(context, nested_shape).map(
2731 |s| if context.config.spaces_within_parens() {
2732 format!("( {}, )", s)
2739 let list_lo = context.codemap.span_after(span, "(");
2740 let nested_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
2741 let items = itemize_list(
2745 |item| item.span().lo(),
2746 |item| item.span().hi(),
2747 |item| item.rewrite(context, nested_shape),
2749 span.hi() - BytePos(1),
2752 let item_vec: Vec<_> = items.collect();
2753 let tactic = definitive_tactic(
2755 ListTactic::HorizontalVertical,
2759 let fmt = ListFormatting {
2762 trailing_separator: SeparatorTactic::Never,
2763 separator_place: SeparatorPlace::Back,
2765 ends_with_newline: false,
2766 preserve_newline: false,
2767 config: context.config,
2769 let list_str = try_opt!(write_list(&item_vec, &fmt));
2771 if context.config.spaces_within_parens() && !list_str.is_empty() {
2772 Some(format!("( {} )", list_str))
2774 Some(format!("({})", list_str))
2778 pub fn rewrite_tuple<'a, T>(
2779 context: &RewriteContext,
2785 T: Rewrite + Spanned + ToExpr + 'a,
2787 debug!("rewrite_tuple {:?}", shape);
2788 if context.use_block_indent() {
2789 // We use the same rule as function calls for rewriting tuples.
2790 let force_trailing_comma = if context.inside_macro {
2791 span_ends_with_comma(context, span)
2801 context.config.fn_call_width(),
2802 force_trailing_comma,
2805 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2809 pub fn rewrite_unary_prefix<R: Rewrite>(
2810 context: &RewriteContext,
2814 ) -> Option<String> {
2816 .rewrite(context, try_opt!(shape.offset_left(prefix.len())))
2817 .map(|r| format!("{}{}", prefix, r))
2820 // FIXME: this is probably not correct for multi-line Rewrites. we should
2821 // subtract suffix.len() from the last line budget, not the first!
2822 pub fn rewrite_unary_suffix<R: Rewrite>(
2823 context: &RewriteContext,
2827 ) -> Option<String> {
2829 .rewrite(context, try_opt!(shape.sub_width(suffix.len())))
2836 fn rewrite_unary_op(
2837 context: &RewriteContext,
2841 ) -> Option<String> {
2842 // For some reason, an UnOp is not spanned like BinOp!
2843 let operator_str = match *op {
2844 ast::UnOp::Deref => "*",
2845 ast::UnOp::Not => "!",
2846 ast::UnOp::Neg => "-",
2848 rewrite_unary_prefix(context, operator_str, expr, shape)
2851 fn rewrite_assignment(
2852 context: &RewriteContext,
2855 op: Option<&ast::BinOp>,
2857 ) -> Option<String> {
2858 let operator_str = match op {
2859 Some(op) => context.snippet(op.span),
2860 None => "=".to_owned(),
2863 // 1 = space between lhs and operator.
2864 let lhs_shape = try_opt!(shape.sub_width(operator_str.len() + 1));
2865 let lhs_str = format!(
2867 try_opt!(lhs.rewrite(context, lhs_shape)),
2871 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2874 // The left hand side must contain everything up to, and including, the
2875 // assignment operator.
2876 pub fn rewrite_assign_rhs<S: Into<String>>(
2877 context: &RewriteContext,
2881 ) -> Option<String> {
2882 let lhs = lhs.into();
2883 let last_line_width = last_line_width(&lhs) - if lhs.contains('\n') {
2884 shape.indent.width()
2888 // 1 = space between operator and rhs.
2889 let orig_shape = try_opt!(shape.offset_left(last_line_width + 1));
2890 let rhs = try_opt!(choose_rhs(
2894 ex.rewrite(context, orig_shape)
2900 context: &RewriteContext,
2903 orig_rhs: Option<String>,
2904 ) -> Option<String> {
2906 Some(ref new_str) if !new_str.contains('\n') => Some(format!(" {}", new_str)),
2908 // Expression did not fit on the same line as the identifier.
2909 // Try splitting the line and see if that works better.
2910 let new_shape = try_opt!(
2912 shape.block().indent.block_indent(context.config),
2914 ).sub_width(shape.rhs_overhead(context.config))
2916 let new_rhs = expr.rewrite(context, new_shape);
2917 let new_indent_str = &new_shape.indent.to_string(context.config);
2919 match (orig_rhs, new_rhs) {
2920 (Some(ref orig_rhs), Some(ref new_rhs)) if prefer_next_line(orig_rhs, new_rhs) => {
2921 Some(format!("\n{}{}", new_indent_str, new_rhs))
2923 (None, Some(ref new_rhs)) => Some(format!("\n{}{}", new_indent_str, new_rhs)),
2924 (None, None) => None,
2925 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2931 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {
2932 fn count_line_breaks(src: &str) -> usize {
2933 src.chars().filter(|&x| x == '\n').count()
2936 !next_line_rhs.contains('\n')
2937 || count_line_breaks(orig_rhs) > count_line_breaks(next_line_rhs) + 1
2940 fn rewrite_expr_addrof(
2941 context: &RewriteContext,
2942 mutability: ast::Mutability,
2945 ) -> Option<String> {
2946 let operator_str = match mutability {
2947 ast::Mutability::Immutable => "&",
2948 ast::Mutability::Mutable => "&mut ",
2950 rewrite_unary_prefix(context, operator_str, expr, shape)
2954 fn to_expr(&self) -> Option<&ast::Expr>;
2955 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2958 impl ToExpr for ast::Expr {
2959 fn to_expr(&self) -> Option<&ast::Expr> {
2963 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2964 can_be_overflowed_expr(context, self, len)
2968 impl ToExpr for ast::Ty {
2969 fn to_expr(&self) -> Option<&ast::Expr> {
2973 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2974 can_be_overflowed_type(context, self, len)
2978 impl<'a> ToExpr for TuplePatField<'a> {
2979 fn to_expr(&self) -> Option<&ast::Expr> {
2983 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2984 can_be_overflowed_pat(context, self, len)
2988 impl<'a> ToExpr for ast::StructField {
2989 fn to_expr(&self) -> Option<&ast::Expr> {
2993 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
2998 impl<'a> ToExpr for MacroArg {
2999 fn to_expr(&self) -> Option<&ast::Expr> {
3001 MacroArg::Expr(ref expr) => Some(expr),
3006 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
3008 MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
3009 MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
3010 MacroArg::Pat(..) => false,