1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use std::cmp::{min, Ordering};
13 use std::iter::{repeat, ExactSizeIterator};
15 use syntax::{ast, ptr};
16 use syntax::codemap::{BytePos, CodeMap, Span};
17 use syntax::parse::classify;
19 use {Indent, Shape, Spanned};
20 use chains::rewrite_chain;
21 use codemap::{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, MacroPosition};
30 use patterns::{can_be_overflowed_pat, TuplePatField};
31 use rewrite::{Rewrite, RewriteContext};
32 use string::{rewrite_string, StringFormat};
33 use types::{can_be_overflowed_type, rewrite_path, PathContext};
34 use utils::{binary_search, colon_spaces, contains_skip, extra_offset, first_line_width,
35 inner_attributes, last_line_extendable, last_line_width, left_most_sub_expr, mk_sp,
36 outer_attributes, paren_overhead, semicolon_for_stmt, stmt_expr,
37 trimmed_last_line_width, wrap_str};
38 use vertical::rewrite_with_alignment;
39 use visitor::FmtVisitor;
41 impl Rewrite for ast::Expr {
42 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
43 format_expr(self, ExprType::SubExpression, context, shape)
56 context: &RewriteContext,
59 skip_out_of_file_lines_range!(context, expr.span);
61 if contains_skip(&*expr.attrs) {
62 return Some(context.snippet(expr.span()));
65 let expr_rw = match expr.node {
66 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
67 expr_vec.iter().map(|e| &**e),
68 mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi),
73 ast::ExprKind::Lit(ref l) => match l.node {
74 ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
75 rewrite_string_lit(context, l.span, shape)
78 context.snippet(expr.span),
79 context.config.max_width(),
83 ast::ExprKind::Call(ref callee, ref args) => {
84 let inner_span = mk_sp(callee.span.hi, expr.span.hi);
85 rewrite_call_with_binary_search(
88 &args.iter().map(|x| &**x).collect::<Vec<_>>()[..],
93 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
94 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
95 // FIXME: format comments between operands and operator
100 &format!(" {} ", context.snippet(op.span)),
106 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
107 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
111 base.as_ref().map(|e| &**e),
115 ast::ExprKind::Tup(ref items) => rewrite_tuple(
117 &items.iter().map(|x| &**x).collect::<Vec<_>>()[..],
121 ast::ExprKind::If(..) |
122 ast::ExprKind::IfLet(..) |
123 ast::ExprKind::ForLoop(..) |
124 ast::ExprKind::Loop(..) |
125 ast::ExprKind::While(..) |
126 ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
127 .and_then(|control_flow| control_flow.rewrite(context, shape)),
128 ast::ExprKind::Block(ref block) => {
130 ExprType::Statement => {
131 if is_unsafe_block(block) {
132 block.rewrite(context, shape)
133 } else if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
134 // Rewrite block without trying to put it in a single line.
137 let prefix = try_opt!(block_prefix(context, block, shape));
138 rewrite_block_with_visitor(context, &prefix, block, shape)
141 ExprType::SubExpression => block.rewrite(context, shape),
144 ast::ExprKind::Match(ref cond, ref arms) => {
145 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
147 ast::ExprKind::Path(ref qself, ref path) => {
148 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
150 ast::ExprKind::Assign(ref lhs, ref rhs) => {
151 rewrite_assignment(context, lhs, rhs, None, shape)
153 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
154 rewrite_assignment(context, lhs, rhs, Some(op), shape)
156 ast::ExprKind::Continue(ref opt_ident) => {
157 let id_str = match *opt_ident {
158 Some(ident) => format!(" {}", ident.node),
159 None => String::new(),
162 format!("continue{}", id_str),
163 context.config.max_width(),
167 ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
168 let id_str = match *opt_ident {
169 Some(ident) => format!(" {}", ident.node),
170 None => String::new(),
173 if let Some(ref expr) = *opt_expr {
174 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
177 format!("break{}", id_str),
178 context.config.max_width(),
183 ast::ExprKind::Yield(ref opt_expr) => {
184 if let Some(ref expr) = *opt_expr {
185 rewrite_unary_prefix(context, "yield ", &**expr, shape)
189 context.config.max_width(),
194 ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
195 rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
197 ast::ExprKind::Try(..) |
198 ast::ExprKind::Field(..) |
199 ast::ExprKind::TupField(..) |
200 ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
201 ast::ExprKind::Mac(ref mac) => {
202 // Failure to rewrite a marco should not imply failure to
203 // rewrite the expression.
204 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
206 context.snippet(expr.span),
207 context.config.max_width(),
212 ast::ExprKind::Ret(None) => {
213 wrap_str("return".to_owned(), context.config.max_width(), shape)
215 ast::ExprKind::Ret(Some(ref expr)) => {
216 rewrite_unary_prefix(context, "return ", &**expr, shape)
218 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
219 ast::ExprKind::AddrOf(mutability, ref expr) => {
220 rewrite_expr_addrof(context, mutability, expr, shape)
222 ast::ExprKind::Cast(ref expr, ref ty) => {
223 rewrite_pair(&**expr, &**ty, "", " as ", "", context, shape)
225 ast::ExprKind::Type(ref expr, ref ty) => {
226 rewrite_pair(&**expr, &**ty, "", ": ", "", context, shape)
228 ast::ExprKind::Index(ref expr, ref index) => {
229 rewrite_index(&**expr, &**index, context, shape)
231 ast::ExprKind::Repeat(ref expr, ref repeats) => {
232 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
237 rewrite_pair(&**expr, &**repeats, lbr, "; ", rbr, context, shape)
239 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
240 let delim = match limits {
241 ast::RangeLimits::HalfOpen => "..",
242 ast::RangeLimits::Closed => "...",
245 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
247 ast::ExprKind::Lit(ref lit) => match lit.node {
248 ast::LitKind::FloatUnsuffixed(..) => {
249 context.snippet(lit.span).ends_with('.')
257 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
258 (Some(ref lhs), Some(ref rhs)) => {
259 let sp_delim = if context.config.spaces_around_ranges() {
260 format!(" {} ", delim)
261 } else if needs_space_before_range(context, lhs) {
262 format!(" {}", delim)
266 rewrite_pair(&**lhs, &**rhs, "", &sp_delim, "", context, shape)
268 (None, Some(ref rhs)) => {
269 let sp_delim = if context.config.spaces_around_ranges() {
270 format!("{} ", delim)
274 rewrite_unary_prefix(context, &sp_delim, &**rhs, shape)
276 (Some(ref lhs), None) => {
277 let sp_delim = if context.config.spaces_around_ranges() {
278 format!(" {}", delim)
282 rewrite_unary_suffix(context, &sp_delim, &**lhs, shape)
284 (None, None) => wrap_str(delim.into(), context.config.max_width(), shape),
287 // We do not format these expressions yet, but they should still
288 // satisfy our width restrictions.
289 ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => wrap_str(
290 context.snippet(expr.span),
291 context.config.max_width(),
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, shape)
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,
337 let sep = if infix.ends_with(' ') { " " } else { "" };
338 let infix = infix.trim_right();
339 let lhs_overhead = shape.used_width() + prefix.len() + infix.len();
340 let lhs_shape = Shape {
341 width: try_opt!(context.config.max_width().checked_sub(lhs_overhead)),
344 let lhs_result = try_opt!(
345 lhs.rewrite(context, lhs_shape)
346 .map(|lhs_str| format!("{}{}{}", prefix, lhs_str, infix))
349 // Try to the both lhs and rhs on the same line.
350 let rhs_orig_result = shape
351 .offset_left(last_line_width(&lhs_result) + suffix.len() + sep.len())
352 .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
353 if let Some(ref rhs_result) = rhs_orig_result {
354 // If the rhs looks like block expression, we allow it to stay on the same line
355 // with the lhs even if it is multi-lined.
356 let allow_same_line = rhs_result
359 .map(|first_line| first_line.ends_with('{'))
361 if !rhs_result.contains('\n') || allow_same_line {
362 return Some(format!("{}{}{}{}", lhs_result, sep, rhs_result, suffix));
366 // We have to use multiple lines.
367 // Re-evaluate the rhs because we have more space now:
368 let rhs_shape = match context.config.control_style() {
370 try_opt!(shape.sub_width(suffix.len() + prefix.len())).visual_indent(prefix.len())
373 // Try to calculate the initial constraint on the right hand side.
374 let rhs_overhead = shape.rhs_overhead(context.config);
376 Shape::indented(shape.indent.block_indent(context.config), context.config)
377 .sub_width(rhs_overhead)
381 let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape));
385 rhs_shape.indent.to_string(context.config),
391 pub fn rewrite_array<'a, I>(
394 context: &RewriteContext,
396 trailing_comma: bool,
399 I: Iterator<Item = &'a ast::Expr>,
401 let bracket_size = if context.config.spaces_within_square_brackets() {
407 let nested_shape = match context.config.array_layout() {
408 IndentStyle::Block => try_opt!(
411 .block_indent(context.config.tab_spaces())
412 .with_max_width(context.config)
415 IndentStyle::Visual => try_opt!(
417 .visual_indent(bracket_size)
418 .sub_width(bracket_size * 2)
422 let items = itemize_list(
428 |item| item.rewrite(context, nested_shape),
432 ).collect::<Vec<_>>();
434 if items.is_empty() {
435 if context.config.spaces_within_square_brackets() {
436 return Some("[ ]".to_string());
438 return Some("[]".to_string());
442 let has_long_item = items
444 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
446 let mut tactic = match context.config.array_layout() {
447 IndentStyle::Block => {
448 // FIXME wrong shape in one-line case
449 match shape.width.checked_sub(2 * bracket_size) {
452 ListTactic::LimitedHorizontalVertical(context.config.array_width());
453 definitive_tactic(&items, tactic, Separator::Comma, width)
455 None => DefinitiveListTactic::Vertical,
458 IndentStyle::Visual => if has_long_item || items.iter().any(ListItem::is_multiline) {
461 ListTactic::LimitedHorizontalVertical(context.config.array_width()),
466 DefinitiveListTactic::Mixed
469 let ends_with_newline = tactic.ends_with_newline(context.config.array_layout());
470 if context.config.array_horizontal_layout_threshold() > 0 &&
471 items.len() > context.config.array_horizontal_layout_threshold()
473 tactic = DefinitiveListTactic::Mixed;
476 let fmt = ListFormatting {
479 trailing_separator: if trailing_comma {
480 SeparatorTactic::Always
481 } else if context.inside_macro || context.config.array_layout() == IndentStyle::Visual {
482 SeparatorTactic::Never
484 SeparatorTactic::Vertical
486 separator_place: SeparatorPlace::Back,
488 ends_with_newline: ends_with_newline,
489 preserve_newline: false,
490 config: context.config,
492 let list_str = try_opt!(write_list(&items, &fmt));
494 let result = if context.config.array_layout() == IndentStyle::Visual ||
495 tactic == DefinitiveListTactic::Horizontal
497 if context.config.spaces_within_square_brackets() && list_str.len() > 0 {
498 format!("[ {} ]", list_str)
500 format!("[{}]", list_str)
505 nested_shape.indent.to_string(context.config),
507 shape.block().indent.to_string(context.config)
514 // Return type is (prefix, extra_offset)
515 fn rewrite_closure_fn_decl(
516 capture: ast::CaptureBy,
517 fn_decl: &ast::FnDecl,
520 context: &RewriteContext,
522 ) -> Option<(String, usize)> {
523 let mover = if capture == ast::CaptureBy::Value {
528 // 4 = "|| {".len(), which is overconservative when the closure consists of
529 // a single expression.
530 let nested_shape = try_opt!(try_opt!(shape.shrink_left(mover.len())).sub_width(4));
533 let argument_offset = nested_shape.indent + 1;
534 let arg_shape = try_opt!(nested_shape.offset_left(1)).visual_indent(0);
535 let ret_str = try_opt!(fn_decl.output.rewrite(context, arg_shape));
537 let arg_items = itemize_list(
539 fn_decl.inputs.iter(),
541 |arg| span_lo_for_arg(arg),
542 |arg| span_hi_for_arg(context, arg),
543 |arg| arg.rewrite(context, arg_shape),
544 context.codemap.span_after(span, "|"),
548 let item_vec = arg_items.collect::<Vec<_>>();
549 // 1 = space between arguments and return type.
550 let horizontal_budget = nested_shape
552 .checked_sub(ret_str.len() + 1)
554 let tactic = definitive_tactic(
556 ListTactic::HorizontalVertical,
560 let arg_shape = match tactic {
561 DefinitiveListTactic::Horizontal => try_opt!(arg_shape.sub_width(ret_str.len() + 1)),
565 let fmt = ListFormatting {
568 trailing_separator: SeparatorTactic::Never,
569 separator_place: SeparatorPlace::Back,
571 ends_with_newline: false,
572 preserve_newline: true,
573 config: context.config,
575 let list_str = try_opt!(write_list(&item_vec, &fmt));
576 let mut prefix = format!("{}|{}|", mover, list_str);
577 // 1 = space between `|...|` and body.
578 let extra_offset = extra_offset(&prefix, shape) + 1;
580 if !ret_str.is_empty() {
581 if prefix.contains('\n') {
583 prefix.push_str(&argument_offset.to_string(context.config));
587 prefix.push_str(&ret_str);
590 Some((prefix, extra_offset))
593 // This functions is pretty messy because of the rules around closures and blocks:
594 // FIXME - the below is probably no longer true in full.
595 // * if there is a return type, then there must be braces,
596 // * given a closure with braces, whether that is parsed to give an inner block
597 // or not depends on if there is a return type and if there are statements
599 // * if the first expression in the body ends with a block (i.e., is a
600 // statement without needing a semi-colon), then adding or removing braces
601 // can change whether it is treated as an expression or statement.
603 capture: ast::CaptureBy,
604 fn_decl: &ast::FnDecl,
607 context: &RewriteContext,
609 ) -> Option<String> {
610 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
618 // 1 = space between `|...|` and body.
619 let body_shape = try_opt!(shape.offset_left(extra_offset));
621 if let ast::ExprKind::Block(ref block) = body.node {
622 // The body of the closure is an empty block.
623 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
624 return Some(format!("{} {{}}", prefix));
627 // Figure out if the block is necessary.
628 let needs_block = block.rules != ast::BlockCheckMode::Default || block.stmts.len() > 1 ||
629 context.inside_macro ||
630 block_contains_comment(block, context.codemap) ||
631 prefix.contains('\n');
633 let no_return_type = if let ast::FunctionRetTy::Default(_) = fn_decl.output {
638 if no_return_type && !needs_block {
639 // lock.stmts.len() == 1
640 if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
641 if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
648 // We need braces, but we might still prefer a one-liner.
649 let stmt = &block.stmts[0];
650 // 4 = braces and spaces.
651 if let Some(body_shape) = body_shape.sub_width(4) {
652 // Checks if rewrite succeeded and fits on a single line.
653 if let Some(rewrite) = and_one_line(stmt.rewrite(context, body_shape)) {
654 return Some(format!("{} {{ {} }}", prefix, rewrite));
659 // Either we require a block, or tried without and failed.
660 rewrite_closure_block(&block, &prefix, context, body_shape)
662 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
663 // The closure originally had a non-block expression, but we can't fit on
664 // one line, so we'll insert a block.
665 rewrite_closure_with_block(context, body_shape, &prefix, body)
670 // Rewrite closure with a single expression wrapping its body with block.
671 fn rewrite_closure_with_block(
672 context: &RewriteContext,
676 ) -> Option<String> {
677 let block = ast::Block {
680 id: ast::NodeId::new(0),
681 node: ast::StmtKind::Expr(ptr::P(body.clone())),
685 id: ast::NodeId::new(0),
686 rules: ast::BlockCheckMode::Default,
689 rewrite_closure_block(&block, prefix, context, shape)
692 // Rewrite closure with a single expression without wrapping its body with block.
693 fn rewrite_closure_expr(
696 context: &RewriteContext,
698 ) -> Option<String> {
699 let mut rewrite = expr.rewrite(context, shape);
700 if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
701 rewrite = and_one_line(rewrite);
703 rewrite = rewrite.and_then(|rw| {
704 if context.config.multiline_closure_forces_block() && rw.contains('\n') {
710 rewrite.map(|rw| format!("{} {}", prefix, rw))
713 // Rewrite closure whose body is block.
714 fn rewrite_closure_block(
717 context: &RewriteContext,
719 ) -> Option<String> {
720 // Start with visual indent, then fall back to block indent if the
722 let block_threshold = context.config.closure_block_indent_threshold();
723 if block_threshold >= 0 {
724 if let Some(block_str) = block.rewrite(&context, shape) {
725 if block_str.matches('\n').count() <= block_threshold as usize &&
726 !need_block_indent(&block_str, shape)
728 if let Some(block_str) = block_str.rewrite(context, shape) {
729 return Some(format!("{} {}", prefix, block_str));
735 // The body of the closure is big enough to be block indented, that
736 // means we must re-format.
737 let block_shape = shape.block();
738 let block_str = try_opt!(block.rewrite(&context, block_shape));
739 Some(format!("{} {}", prefix, block_str))
742 fn and_one_line(x: Option<String>) -> Option<String> {
743 x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
746 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
747 debug!("nop_block_collapse {:?} {}", block_str, budget);
748 block_str.map(|block_str| {
749 if block_str.starts_with('{') && budget >= 2 &&
750 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
759 fn rewrite_empty_block(
760 context: &RewriteContext,
763 ) -> Option<String> {
764 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
766 return Some("{}".to_owned());
769 // If a block contains only a single-line comment, then leave it on one line.
770 let user_str = context.snippet(block.span);
771 let user_str = user_str.trim();
772 if user_str.starts_with('{') && user_str.ends_with('}') {
773 let comment_str = user_str[1..user_str.len() - 1].trim();
774 if block.stmts.is_empty() && !comment_str.contains('\n') &&
775 !comment_str.starts_with("//") && comment_str.len() + 4 <= shape.width
777 return Some(format!("{{ {} }}", comment_str));
784 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
785 Some(match block.rules {
786 ast::BlockCheckMode::Unsafe(..) => {
787 let snippet = context.snippet(block.span);
788 let open_pos = try_opt!(snippet.find_uncommented("{"));
789 // Extract comment between unsafe and block start.
790 let trimmed = &snippet[6..open_pos].trim();
792 if !trimmed.is_empty() {
793 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
794 let budget = try_opt!(shape.width.checked_sub(9));
797 try_opt!(rewrite_comment(
800 Shape::legacy(budget, shape.indent + 7),
808 ast::BlockCheckMode::Default => String::new(),
812 fn rewrite_single_line_block(
813 context: &RewriteContext,
817 ) -> Option<String> {
818 if is_simple_block(block, context.codemap) {
819 let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
820 let expr_str = try_opt!(block.stmts[0].rewrite(context, expr_shape));
821 let result = format!("{}{{ {} }}", prefix, expr_str);
822 if result.len() <= shape.width && !result.contains('\n') {
829 fn rewrite_block_with_visitor(
830 context: &RewriteContext,
834 ) -> Option<String> {
835 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
839 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
840 visitor.block_indent = shape.indent;
841 visitor.is_if_else_block = context.is_if_else_block;
843 ast::BlockCheckMode::Unsafe(..) => {
844 let snippet = context.snippet(block.span);
845 let open_pos = try_opt!(snippet.find_uncommented("{"));
846 visitor.last_pos = block.span.lo + BytePos(open_pos as u32)
848 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo,
851 visitor.visit_block(block, None);
852 Some(format!("{}{}", prefix, visitor.buffer))
855 impl Rewrite for ast::Block {
856 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
857 // shape.width is used only for the single line case: either the empty block `{}`,
858 // or an unsafe expression `unsafe { e }`.
859 if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
863 let prefix = try_opt!(block_prefix(context, self, shape));
864 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
868 rewrite_block_with_visitor(context, &prefix, self, shape)
872 impl Rewrite for ast::Stmt {
873 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
874 skip_out_of_file_lines_range!(context, self.span());
876 let result = match self.node {
877 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
878 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
879 let suffix = if semicolon_for_stmt(context, self) {
885 let expr_type = match self.node {
886 ast::StmtKind::Expr(_) => ExprType::SubExpression,
887 ast::StmtKind::Semi(_) => ExprType::Statement,
890 let shape = try_opt!(shape.sub_width(suffix.len()));
891 format_expr(ex, expr_type, context, shape).map(|s| s + suffix)
893 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
895 result.and_then(|res| {
896 recover_comment_removed(res, self.span(), context, shape)
901 // Rewrite condition if the given expression has one.
902 fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
904 ast::ExprKind::Match(ref cond, _) => {
906 let cond_shape = match context.config.control_style() {
907 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
908 Style::Rfc => try_opt!(shape.offset_left(8)),
910 cond.rewrite(context, cond_shape)
912 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
913 stmt_expr(&block.stmts[0]).and_then(|e| rewrite_cond(context, e, shape))
915 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
917 String::from("\n") + &shape.indent.block_only().to_string(context.config);
919 .rewrite_cond(context, shape, &alt_block_sep)
920 .and_then(|rw| Some(rw.0))
925 // Abstraction over control flow expressions
927 struct ControlFlow<'a> {
928 cond: Option<&'a ast::Expr>,
929 block: &'a ast::Block,
930 else_block: Option<&'a ast::Expr>,
931 label: Option<ast::SpannedIdent>,
932 pat: Option<&'a ast::Pat>,
936 allow_single_line: bool,
937 // True if this is an `if` expression in an `else if` :-( hacky
942 fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'a>> {
944 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
948 else_block.as_ref().map(|e| &**e),
949 expr_type == ExprType::SubExpression,
953 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
954 Some(ControlFlow::new_if(
958 else_block.as_ref().map(|e| &**e),
959 expr_type == ExprType::SubExpression,
964 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
965 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
967 ast::ExprKind::Loop(ref block, label) => {
968 Some(ControlFlow::new_loop(block, label, expr.span))
970 ast::ExprKind::While(ref cond, ref block, label) => {
971 Some(ControlFlow::new_while(None, cond, block, label, expr.span))
973 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
974 ControlFlow::new_while(Some(pat), cond, block, label, expr.span),
980 impl<'a> ControlFlow<'a> {
983 pat: Option<&'a ast::Pat>,
984 block: &'a ast::Block,
985 else_block: Option<&'a ast::Expr>,
986 allow_single_line: bool,
989 ) -> ControlFlow<'a> {
993 else_block: else_block,
1002 allow_single_line: allow_single_line,
1003 nested_if: nested_if,
1009 block: &'a ast::Block,
1010 label: Option<ast::SpannedIdent>,
1012 ) -> ControlFlow<'a> {
1022 allow_single_line: false,
1029 pat: Option<&'a ast::Pat>,
1030 cond: &'a ast::Expr,
1031 block: &'a ast::Block,
1032 label: Option<ast::SpannedIdent>,
1034 ) -> ControlFlow<'a> {
1042 matcher: match pat {
1047 allow_single_line: false,
1055 cond: &'a ast::Expr,
1056 block: &'a ast::Block,
1057 label: Option<ast::SpannedIdent>,
1059 ) -> ControlFlow<'a> {
1069 allow_single_line: false,
1075 fn rewrite_single_line(
1078 context: &RewriteContext,
1080 ) -> Option<String> {
1081 assert!(self.allow_single_line);
1082 let else_block = try_opt!(self.else_block);
1083 let fixed_cost = self.keyword.len() + " { } else { }".len();
1085 if let ast::ExprKind::Block(ref else_node) = else_block.node {
1086 if !is_simple_block(self.block, context.codemap) ||
1087 !is_simple_block(else_node, context.codemap) ||
1088 pat_expr_str.contains('\n')
1093 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
1094 let expr = &self.block.stmts[0];
1095 let if_str = try_opt!(expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
1097 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
1098 let else_expr = &else_node.stmts[0];
1100 try_opt!(else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
1102 if if_str.contains('\n') || else_str.contains('\n') {
1106 let result = format!(
1107 "{} {} {{ {} }} else {{ {} }}",
1114 if result.len() <= width {
1115 return Some(result);
1123 impl<'a> ControlFlow<'a> {
1126 context: &RewriteContext,
1128 alt_block_sep: &str,
1129 ) -> Option<(String, usize)> {
1130 // Do not take the rhs overhead from the upper expressions into account
1131 // when rewriting pattern.
1132 let new_width = context
1135 .checked_sub(shape.used_width())
1137 let fresh_shape = Shape {
1141 let constr_shape = if self.nested_if {
1142 // We are part of an if-elseif-else chain. Our constraints are tightened.
1143 // 7 = "} else " .len()
1144 try_opt!(fresh_shape.offset_left(7))
1149 let label_string = rewrite_label(self.label);
1150 // 1 = space after keyword.
1151 let offset = self.keyword.len() + label_string.len() + 1;
1153 let pat_expr_string = match self.cond {
1155 let cond_shape = match context.config.control_style() {
1156 Style::Legacy => try_opt!(constr_shape.shrink_left(offset)),
1157 Style::Rfc => try_opt!(constr_shape.offset_left(offset)),
1159 try_opt!(rewrite_pat_expr(
1169 None => String::new(),
1172 let brace_overhead =
1173 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1179 let one_line_budget = context
1182 .checked_sub(constr_shape.used_width() + offset + brace_overhead)
1184 let force_newline_brace = context.config.control_style() == Style::Rfc &&
1185 (pat_expr_string.contains('\n') || pat_expr_string.len() > one_line_budget) &&
1186 !last_line_extendable(&pat_expr_string);
1188 // Try to format if-else on single line.
1189 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1190 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1192 if let Some(cond_str) = trial {
1193 if cond_str.len() <= context.config.single_line_if_else_max_width() {
1194 return Some((cond_str, 0));
1199 let cond_span = if let Some(cond) = self.cond {
1202 mk_sp(self.block.span.lo, self.block.span.lo)
1205 // `for event in event`
1206 // Do not include label in the span.
1207 let lo = self.label.map_or(self.span.lo, |label| label.span.hi);
1208 let between_kwd_cond = mk_sp(
1211 .span_after(mk_sp(lo, self.span.hi), self.keyword.trim()),
1213 .map_or(cond_span.lo, |p| if self.matcher.is_empty() {
1216 context.codemap.span_before(self.span, self.matcher.trim())
1220 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1222 let after_cond_comment =
1223 extract_comment(mk_sp(cond_span.hi, self.block.span.lo), context, shape);
1225 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1227 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine ||
1235 let used_width = if pat_expr_string.contains('\n') {
1236 last_line_width(&pat_expr_string)
1238 // 2 = spaces after keyword and condition.
1239 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1247 between_kwd_cond_comment.as_ref().map_or(
1248 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1256 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1263 impl<'a> Rewrite for ControlFlow<'a> {
1264 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1265 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1268 String::from("\n") + &shape.indent.block_only().to_string(context.config);
1269 let (cond_str, used_width) = try_opt!(self.rewrite_cond(context, shape, &alt_block_sep));
1270 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1271 if used_width == 0 {
1272 return Some(cond_str);
1275 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1276 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1277 // we should avoid the single line case.
1278 let block_width = if self.else_block.is_some() || self.nested_if {
1283 let block_shape = Shape {
1287 let mut block_context = context.clone();
1288 block_context.is_if_else_block = self.else_block.is_some();
1289 let block_str = try_opt!(rewrite_block_with_visitor(
1296 let mut result = format!("{}{}", cond_str, block_str);
1298 if let Some(else_block) = self.else_block {
1299 let shape = Shape::indented(shape.indent, context.config);
1300 let mut last_in_chain = false;
1301 let rewrite = match else_block.node {
1302 // If the else expression is another if-else expression, prevent it
1303 // from being formatted on a single line.
1304 // Note how we're passing the original shape, as the
1305 // cost of "else" should not cascade.
1306 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1307 ControlFlow::new_if(
1311 next_else_block.as_ref().map(|e| &**e),
1314 mk_sp(else_block.span.lo, self.span.hi),
1315 ).rewrite(context, shape)
1317 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1318 ControlFlow::new_if(
1322 next_else_block.as_ref().map(|e| &**e),
1325 mk_sp(else_block.span.lo, self.span.hi),
1326 ).rewrite(context, shape)
1329 last_in_chain = true;
1330 // When rewriting a block, the width is only used for single line
1331 // blocks, passing 1 lets us avoid that.
1332 let else_shape = Shape {
1333 width: min(1, shape.width),
1336 format_expr(else_block, ExprType::Statement, context, else_shape)
1340 let between_kwd_else_block = mk_sp(
1344 .span_before(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1346 let between_kwd_else_block_comment =
1347 extract_comment(between_kwd_else_block, context, shape);
1349 let after_else = mk_sp(
1352 .span_after(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1355 let after_else_comment = extract_comment(after_else, context, shape);
1357 let between_sep = match context.config.control_brace_style() {
1358 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1361 ControlBraceStyle::AlwaysSameLine => " ",
1363 let after_sep = match context.config.control_brace_style() {
1364 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1371 between_kwd_else_block_comment
1373 .map_or(between_sep, |s| &**s),
1374 after_else_comment.as_ref().map_or(after_sep, |s| &**s)
1377 result.push_str(&try_opt!(rewrite));
1384 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
1386 Some(ident) => format!("{}: ", ident.node),
1387 None => "".to_owned(),
1391 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1392 match rewrite_missing_comment(span, shape, context) {
1393 Some(ref comment) if !comment.is_empty() => Some(format!(
1394 "\n{indent}{}\n{indent}",
1396 indent = shape.indent.to_string(context.config)
1402 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1403 let snippet = codemap.span_to_snippet(block.span).unwrap();
1404 contains_comment(&snippet)
1407 // Checks that a block contains no statements, an expression and no comments.
1408 // FIXME: incorrectly returns false when comment is contained completely within
1410 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1411 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) &&
1412 !block_contains_comment(block, codemap))
1415 /// Checks whether a block contains at most one statement or expression, and no comments.
1416 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1417 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1420 /// Checks whether a block contains no statements, expressions, or comments.
1421 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1422 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1425 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1427 ast::StmtKind::Expr(..) => true,
1432 fn is_unsafe_block(block: &ast::Block) -> bool {
1433 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1440 // A simple wrapper type against ast::Arm. Used inside write_list().
1441 struct ArmWrapper<'a> {
1442 pub arm: &'a ast::Arm,
1443 // True if the arm is the last one in match expression. Used to decide on whether we should add
1444 // trailing comma to the match arm when `config.trailing_comma() == Never`.
1448 impl<'a> ArmWrapper<'a> {
1449 pub fn new(arm: &'a ast::Arm, is_last: bool) -> ArmWrapper<'a> {
1450 ArmWrapper { arm, is_last }
1454 impl<'a> Rewrite for ArmWrapper<'a> {
1455 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1456 rewrite_match_arm(context, self.arm, shape, self.is_last)
1461 context: &RewriteContext,
1466 attrs: &[ast::Attribute],
1467 ) -> Option<String> {
1468 if arms.is_empty() {
1472 // Do not take the rhs overhead from the upper expressions into account
1473 // when rewriting match condition.
1474 let new_width = try_opt!(context.config.max_width().checked_sub(shape.used_width()));
1475 let cond_shape = Shape {
1480 let cond_shape = match context.config.control_style() {
1481 Style::Legacy => try_opt!(cond_shape.shrink_left(6)),
1482 Style::Rfc => try_opt!(cond_shape.offset_left(6)),
1484 let cond_str = try_opt!(cond.rewrite(context, cond_shape));
1485 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1486 let block_sep = match context.config.control_brace_style() {
1487 ControlBraceStyle::AlwaysNextLine => &alt_block_sep,
1488 _ if last_line_extendable(&cond_str) => " ",
1490 _ if cond_str.contains('\n') || cond_str.len() + 2 > cond_shape.width => &alt_block_sep,
1494 let nested_indent_str = shape
1496 .block_indent(context.config)
1497 .to_string(context.config);
1498 // Inner attributes.
1499 let inner_attrs = &inner_attributes(attrs);
1500 let inner_attrs_str = if inner_attrs.is_empty() {
1505 .rewrite(context, shape)
1506 .map(|s| format!("{}{}\n", nested_indent_str, s))
1510 let open_brace_pos = if inner_attrs.is_empty() {
1513 .span_after(mk_sp(cond.span.hi, arms[0].span().lo), "{")
1515 inner_attrs[inner_attrs.len() - 1].span().hi
1518 let arm_indent_str = if context.config.indent_match_arms() {
1521 shape.indent.to_string(context.config)
1525 "match {}{}{{\n{}{}{}\n{}}}",
1530 try_opt!(rewrite_match_arms(
1537 shape.indent.to_string(context.config),
1541 fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
1542 if is_last && config.trailing_comma() == SeparatorTactic::Never {
1544 } else if config.match_block_trailing_comma() {
1546 } else if let ast::ExprKind::Block(ref block) = body.node {
1547 if let ast::BlockCheckMode::Default = block.rules {
1557 fn rewrite_match_arms(
1558 context: &RewriteContext,
1562 open_brace_pos: BytePos,
1563 ) -> Option<String> {
1564 let arm_shape = if context.config.indent_match_arms() {
1565 shape.block_indent(context.config.tab_spaces())
1567 shape.block_indent(0)
1568 }.with_max_width(context.config);
1570 let arm_len = arms.len();
1571 let is_last_iter = repeat(false)
1572 .take(arm_len.checked_sub(1).unwrap_or(0))
1573 .chain(repeat(true));
1574 let items = itemize_list(
1578 .map(|(arm, is_last)| ArmWrapper::new(arm, is_last)),
1580 |arm| arm.arm.span().lo,
1581 |arm| arm.arm.span().hi,
1582 |arm| arm.rewrite(context, arm_shape),
1587 let arms_vec: Vec<_> = items.collect();
1588 let fmt = ListFormatting {
1589 tactic: DefinitiveListTactic::Vertical,
1590 // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
1592 trailing_separator: SeparatorTactic::Never,
1593 separator_place: SeparatorPlace::Back,
1595 ends_with_newline: true,
1596 preserve_newline: true,
1597 config: context.config,
1600 write_list(&arms_vec, &fmt)
1603 fn rewrite_match_arm(
1604 context: &RewriteContext,
1608 ) -> Option<String> {
1609 let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
1610 if contains_skip(&arm.attrs) {
1611 let (_, body) = flatten_arm_body(context, &arm.body);
1612 // `arm.span()` does not include trailing comma, add it manually.
1613 return Some(format!(
1615 context.snippet(arm.span()),
1616 arm_comma(context.config, body, is_last),
1620 mk_sp(arm.attrs[arm.attrs.len() - 1].span.hi, arm.pats[0].span.lo),
1621 try_opt!(arm.attrs.rewrite(context, shape)),
1624 (mk_sp(arm.span().lo, arm.span().lo), String::new())
1626 let pats_str = try_opt!(
1627 rewrite_match_pattern(context, &arm.pats, &arm.guard, shape).and_then(|pats_str| {
1628 combine_strs_with_missing_comments(
1643 arm.guard.is_some(),
1648 fn rewrite_match_pattern(
1649 context: &RewriteContext,
1650 pats: &Vec<ptr::P<ast::Pat>>,
1651 guard: &Option<ptr::P<ast::Expr>>,
1653 ) -> Option<String> {
1656 let pat_shape = try_opt!(shape.sub_width(5));
1658 let pat_strs = try_opt!(
1660 .map(|p| p.rewrite(context, pat_shape))
1661 .collect::<Option<Vec<_>>>()
1664 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1665 let tactic = definitive_tactic(
1667 ListTactic::HorizontalVertical,
1668 Separator::VerticalBar,
1671 let fmt = ListFormatting {
1674 trailing_separator: SeparatorTactic::Never,
1675 separator_place: context.config.match_pattern_separator_break_point(),
1677 ends_with_newline: false,
1678 preserve_newline: false,
1679 config: context.config,
1681 let pats_str = try_opt!(write_list(&items, &fmt));
1684 let guard_str = try_opt!(rewrite_guard(
1688 trimmed_last_line_width(&pats_str),
1691 Some(format!("{}{}", pats_str, guard_str))
1695 // @extend: true if the arm body can be put next to `=>`
1696 // @body: flattened body, if the body is block with a single expression
1697 fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bool, &'a ast::Expr) {
1699 ast::ExprKind::Block(ref block)
1700 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) =>
1702 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1704 !context.config.multiline_match_arm_forces_block() &&
1705 expr.can_be_overflowed(context, 1),
1713 !context.config.multiline_match_arm_forces_block() &&
1714 body.can_be_overflowed(context, 1),
1720 fn rewrite_match_body(
1721 context: &RewriteContext,
1722 body: &ptr::P<ast::Expr>,
1727 ) -> Option<String> {
1728 let (extend, body) = flatten_arm_body(context, &body);
1730 let comma = arm_comma(&context.config, body, is_last);
1731 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1732 let alt_block_sep = alt_block_sep.as_str();
1733 let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
1734 (true, is_empty_block(block, context.codemap))
1739 let combine_orig_body = |body_str: &str| {
1740 let block_sep = match context.config.control_brace_style() {
1741 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
1745 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
1748 let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
1749 let next_line_indent = if is_block {
1752 shape.indent.block_indent(context.config)
1754 let combine_next_line_body = |body_str: &str| {
1756 return Some(format!(
1759 next_line_indent.to_string(context.config),
1764 let indent_str = shape.indent.to_string(context.config);
1765 let nested_indent_str = next_line_indent.to_string(context.config);
1766 let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1767 let comma = if context.config.match_block_trailing_comma() {
1772 ("{", format!("\n{}}}{}", indent_str, comma))
1774 ("", String::from(","))
1777 let block_sep = match context.config.control_brace_style() {
1778 ControlBraceStyle::AlwaysNextLine => format!("{}{}\n", alt_block_sep, body_prefix),
1779 _ if body_prefix.is_empty() => "\n".to_owned(),
1780 _ if forbid_same_line => format!("{}{}\n", alt_block_sep, body_prefix),
1781 _ => format!(" {}\n", body_prefix),
1782 } + &nested_indent_str;
1793 // Let's try and get the arm body on the same line as the condition.
1795 let orig_body_shape = shape
1796 .offset_left(extra_offset(&pats_str, shape) + 4)
1797 .and_then(|shape| shape.sub_width(comma.len()));
1798 let orig_body = if let Some(body_shape) = orig_body_shape {
1799 let rewrite = nop_block_collapse(
1800 format_expr(body, ExprType::Statement, context, body_shape),
1806 if !forbid_same_line &&
1808 (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
1810 return combine_orig_body(body_str);
1817 let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
1819 // Try putting body on the next line and see if it looks better.
1820 let next_line_body_shape = Shape::indented(next_line_indent, context.config);
1821 let next_line_body = nop_block_collapse(
1822 format_expr(body, ExprType::Statement, context, next_line_body_shape),
1823 next_line_body_shape.width,
1825 match (orig_body, next_line_body) {
1826 (Some(ref orig_str), Some(ref next_line_str))
1827 if forbid_same_line || prefer_next_line(orig_str, next_line_str) =>
1829 combine_next_line_body(next_line_str)
1831 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
1832 combine_orig_body(orig_str)
1834 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
1835 combine_next_line_body(next_line_str)
1837 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
1838 (None, None) => None,
1839 (Some(ref orig_str), _) => combine_orig_body(orig_str),
1843 // The `if ...` guard on a match arm.
1845 context: &RewriteContext,
1846 guard: &Option<ptr::P<ast::Expr>>,
1848 // The amount of space used up on this line for the pattern in
1849 // the arm (excludes offset).
1850 pattern_width: usize,
1851 ) -> Option<String> {
1852 if let Some(ref guard) = *guard {
1853 // First try to fit the guard string on the same line as the pattern.
1854 // 4 = ` if `, 5 = ` => {`
1855 let cond_shape = shape
1856 .offset_left(pattern_width + 4)
1857 .and_then(|s| s.sub_width(5));
1858 if let Some(cond_shape) = cond_shape {
1859 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1860 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
1861 return Some(format!(" if {}", cond_str));
1866 // Not enough space to put the guard after the pattern, try a newline.
1867 // 3 = `if `, 5 = ` => {`
1868 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
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 return Some(format!(
1875 cond_shape.indent.to_string(context.config),
1887 fn rewrite_pat_expr(
1888 context: &RewriteContext,
1889 pat: Option<&ast::Pat>,
1892 // Connecting piece between pattern and expression,
1893 // *without* trailing space.
1897 ) -> Option<String> {
1898 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1899 if let Some(pat) = pat {
1900 let matcher = if matcher.is_empty() {
1903 format!("{} ", matcher)
1906 try_opt!(try_opt!(shape.offset_left(matcher.len())).sub_width(connector.len()));
1907 let pat_string = try_opt!(pat.rewrite(context, pat_shape));
1908 let result = format!("{}{}{}", matcher, pat_string, connector);
1909 return rewrite_assign_rhs(context, result, expr, shape);
1912 let expr_rw = expr.rewrite(context, shape);
1913 // The expression may (partially) fit on the current line.
1914 // We do not allow splitting between `if` and condition.
1915 if keyword == "if" || expr_rw.is_some() {
1919 // The expression won't fit on the current line, jump to next.
1920 let nested_shape = shape
1921 .block_indent(context.config.tab_spaces())
1922 .with_max_width(context.config);
1923 let nested_indent_str = nested_shape.indent.to_string(context.config);
1924 expr.rewrite(context, nested_shape)
1925 .map(|expr_rw| format!("\n{}{}", nested_indent_str, expr_rw))
1928 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1929 let string_lit = context.snippet(span);
1931 if !context.config.format_strings() && !context.config.force_format_strings() {
1936 .all(|line| line.ends_with('\\'))
1938 let new_indent = shape.visual_indent(1).indent;
1939 return Some(String::from(
1943 new_indent.to_string(context.config) + line.trim_left()
1945 .collect::<Vec<_>>()
1950 return Some(string_lit);
1954 if !context.config.force_format_strings() &&
1955 !string_requires_rewrite(context, span, &string_lit, shape)
1957 return Some(string_lit);
1960 let fmt = StringFormat {
1967 config: context.config,
1970 // Remove the quote characters.
1971 let str_lit = &string_lit[1..string_lit.len() - 1];
1973 rewrite_string(str_lit, &fmt)
1976 fn string_requires_rewrite(
1977 context: &RewriteContext,
1982 if context.codemap.lookup_char_pos(span.lo).col.0 != shape.indent.width() {
1986 for (i, line) in string.lines().enumerate() {
1988 if line.len() > shape.width {
1992 if line.len() > shape.width + shape.indent.width() {
2001 pub fn rewrite_call_with_binary_search<R>(
2002 context: &RewriteContext,
2004 args: &[&ast::Expr],
2011 let force_trailing_comma = if context.inside_macro {
2012 span_ends_with_comma(context, span)
2016 let closure = |callee_max_width| {
2017 // FIXME using byte lens instead of char lens (and probably all over the
2019 let callee_shape = Shape {
2020 width: callee_max_width,
2023 let callee_str = callee
2024 .rewrite(context, callee_shape)
2025 .ok_or(Ordering::Greater)?;
2033 context.config.fn_call_width(),
2034 force_trailing_comma,
2038 binary_search(1, shape.width, closure)
2041 pub fn rewrite_call(
2042 context: &RewriteContext,
2044 args: &[ptr::P<ast::Expr>],
2047 ) -> Option<String> {
2048 let force_trailing_comma = if context.inside_macro {
2049 span_ends_with_comma(context, span)
2056 &args.iter().map(|x| &**x).collect::<Vec<_>>(),
2059 context.config.fn_call_width(),
2060 force_trailing_comma,
2064 pub fn rewrite_call_inner<'a, T>(
2065 context: &RewriteContext,
2070 args_max_width: usize,
2071 force_trailing_comma: bool,
2072 ) -> Result<String, Ordering>
2074 T: Rewrite + Spanned + ToExpr + 'a,
2076 // 2 = `( `, 1 = `(`
2077 let paren_overhead = if context.config.spaces_within_parens() {
2082 let used_width = extra_offset(&callee_str, shape);
2083 let one_line_width = shape
2085 .checked_sub(used_width + 2 * paren_overhead)
2086 .ok_or(Ordering::Greater)?;
2088 let nested_shape = shape_from_fn_call_style(
2091 used_width + 2 * paren_overhead,
2092 used_width + paren_overhead,
2093 ).ok_or(Ordering::Greater)?;
2095 let span_lo = context.codemap.span_after(span, "(");
2096 let args_span = mk_sp(span_lo, span.hi);
2098 let (extendable, list_str) = rewrite_call_args(
2105 force_trailing_comma,
2106 ).ok_or(Ordering::Less)?;
2108 if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
2109 let mut new_context = context.clone();
2110 new_context.use_block = true;
2111 return rewrite_call_inner(
2118 force_trailing_comma,
2122 let args_shape = shape
2123 .sub_width(last_line_width(&callee_str))
2124 .ok_or(Ordering::Less)?;
2128 wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2132 fn need_block_indent(s: &str, shape: Shape) -> bool {
2133 s.lines().skip(1).any(|s| {
2134 s.find(|c| !char::is_whitespace(c))
2135 .map_or(false, |w| w + 1 < shape.indent.width())
2139 fn rewrite_call_args<'a, T>(
2140 context: &RewriteContext,
2144 one_line_width: usize,
2145 args_max_width: usize,
2146 force_trailing_comma: bool,
2147 ) -> Option<(bool, String)>
2149 T: Rewrite + Spanned + ToExpr + 'a,
2151 let items = itemize_list(
2155 |item| item.span().lo,
2156 |item| item.span().hi,
2157 |item| item.rewrite(context, shape),
2162 let mut item_vec: Vec<_> = items.collect();
2164 // Try letting the last argument overflow to the next line with block
2165 // indentation. If its first line fits on one line with the other arguments,
2166 // we format the function arguments horizontally.
2167 let tactic = try_overflow_last_arg(
2176 let fmt = ListFormatting {
2179 trailing_separator: if force_trailing_comma {
2180 SeparatorTactic::Always
2181 } else if context.inside_macro || !context.use_block_indent() {
2182 SeparatorTactic::Never
2184 context.config.trailing_comma()
2186 separator_place: SeparatorPlace::Back,
2188 ends_with_newline: context.use_block_indent() && tactic == DefinitiveListTactic::Vertical,
2189 preserve_newline: false,
2190 config: context.config,
2193 write_list(&item_vec, &fmt).map(|args_str| {
2194 (tactic != DefinitiveListTactic::Vertical, args_str)
2198 fn try_overflow_last_arg<'a, T>(
2199 context: &RewriteContext,
2200 item_vec: &mut Vec<ListItem>,
2203 one_line_width: usize,
2204 args_max_width: usize,
2205 ) -> DefinitiveListTactic
2207 T: Rewrite + Spanned + ToExpr + 'a,
2209 let overflow_last = can_be_overflowed(&context, args);
2211 // Replace the last item with its first line to see if it fits with
2213 let placeholder = if overflow_last {
2214 let mut context = context.clone();
2215 if let Some(expr) = args[args.len() - 1].to_expr() {
2217 ast::ExprKind::MethodCall(..) => context.force_one_line_chain = true,
2221 last_arg_shape(&context, &item_vec, shape, args_max_width).and_then(|arg_shape| {
2222 rewrite_last_arg_with_overflow(&context, args, &mut item_vec[args.len() - 1], arg_shape)
2228 let mut tactic = definitive_tactic(
2230 ListTactic::LimitedHorizontalVertical(args_max_width),
2235 // Replace the stub with the full overflowing last argument if the rewrite
2236 // succeeded and its first line fits with the other arguments.
2237 match (overflow_last, tactic, placeholder) {
2238 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2239 item_vec[args.len() - 1].item = placeholder;
2241 _ if args.len() >= 1 => {
2242 item_vec[args.len() - 1].item = args.last()
2243 .and_then(|last_arg| last_arg.rewrite(context, shape));
2244 tactic = definitive_tactic(
2246 ListTactic::LimitedHorizontalVertical(args_max_width),
2258 context: &RewriteContext,
2259 items: &Vec<ListItem>,
2261 args_max_width: usize,
2262 ) -> Option<Shape> {
2263 let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
2264 acc + i.item.as_ref().map_or(0, |s| first_line_width(&s))
2266 let max_width = min(args_max_width, shape.width);
2267 let arg_indent = if context.use_block_indent() {
2268 shape.block().indent.block_unindent(context.config)
2270 shape.block().indent
2273 width: try_opt!(max_width.checked_sub(overhead)),
2279 // Rewriting closure which is placed at the end of the function call's arg.
2280 // Returns `None` if the reformatted closure 'looks bad'.
2281 fn rewrite_last_closure(
2282 context: &RewriteContext,
2285 ) -> Option<String> {
2286 if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
2287 let body = match body.node {
2288 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
2289 stmt_expr(&block.stmts[0]).unwrap_or(body)
2293 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
2301 // If the closure goes multi line before its body, do not overflow the closure.
2302 if prefix.contains('\n') {
2305 let body_shape = try_opt!(shape.offset_left(extra_offset));
2306 // When overflowing the closure which consists of a single control flow expression,
2307 // force to use block if its condition uses multi line.
2308 let is_multi_lined_cond = rewrite_cond(context, body, body_shape)
2309 .map(|cond| cond.contains('\n') || cond.len() > body_shape.width)
2311 if is_multi_lined_cond {
2312 return rewrite_closure_with_block(context, body_shape, &prefix, body);
2315 // Seems fine, just format the closure in usual manner.
2316 return expr.rewrite(context, shape);
2321 fn rewrite_last_arg_with_overflow<'a, T>(
2322 context: &RewriteContext,
2324 last_item: &mut ListItem,
2328 T: Rewrite + Spanned + ToExpr + 'a,
2330 let last_arg = args[args.len() - 1];
2331 let rewrite = if let Some(expr) = last_arg.to_expr() {
2333 // When overflowing the closure which consists of a single control flow expression,
2334 // force to use block if its condition uses multi line.
2335 ast::ExprKind::Closure(..) => {
2336 // If the argument consists of multiple closures, we do not overflow
2337 // the last closure.
2338 if args.len() > 1 &&
2342 .filter_map(|arg| arg.to_expr())
2343 .any(|expr| match expr.node {
2344 ast::ExprKind::Closure(..) => true,
2349 rewrite_last_closure(context, expr, shape)
2352 _ => expr.rewrite(context, shape),
2355 last_arg.rewrite(context, shape)
2358 if let Some(rewrite) = rewrite {
2359 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2360 last_item.item = rewrite_first_line;
2367 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2369 T: Rewrite + Spanned + ToExpr + 'a,
2372 .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2375 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2377 ast::ExprKind::Match(..) => {
2378 (context.use_block_indent() && args_len == 1) ||
2379 (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
2381 ast::ExprKind::If(..) |
2382 ast::ExprKind::IfLet(..) |
2383 ast::ExprKind::ForLoop(..) |
2384 ast::ExprKind::Loop(..) |
2385 ast::ExprKind::While(..) |
2386 ast::ExprKind::WhileLet(..) => {
2387 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2389 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
2390 context.use_block_indent() ||
2391 context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
2393 ast::ExprKind::Array(..) |
2394 ast::ExprKind::Call(..) |
2395 ast::ExprKind::Mac(..) |
2396 ast::ExprKind::MethodCall(..) |
2397 ast::ExprKind::Struct(..) |
2398 ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2399 ast::ExprKind::AddrOf(_, ref expr) |
2400 ast::ExprKind::Box(ref expr) |
2401 ast::ExprKind::Try(ref expr) |
2402 ast::ExprKind::Unary(_, ref expr) |
2403 ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2408 pub fn wrap_args_with_parens(
2409 context: &RewriteContext,
2411 is_extendable: bool,
2413 nested_shape: Shape,
2415 if !context.use_block_indent() ||
2416 (context.inside_macro && !args_str.contains('\n') &&
2417 args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2419 if context.config.spaces_within_parens() && args_str.len() > 0 {
2420 format!("( {} )", args_str)
2422 format!("({})", args_str)
2427 nested_shape.indent.to_string(context.config),
2429 shape.block().indent.to_string(context.config)
2434 fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2435 let snippet = context.snippet(span);
2437 .trim_right_matches(|c: char| c == ')' || c.is_whitespace())
2441 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2442 debug!("rewrite_paren, shape: {:?}", shape);
2443 let total_paren_overhead = paren_overhead(context);
2444 let paren_overhead = total_paren_overhead / 2;
2445 let sub_shape = try_opt!(
2447 .offset_left(paren_overhead)
2448 .and_then(|s| s.sub_width(paren_overhead))
2451 let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && s.len() > 0 {
2452 format!("( {} )", s)
2457 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2458 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2460 if subexpr_str.contains('\n') ||
2461 first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
2463 Some(paren_wrapper(&subexpr_str))
2472 context: &RewriteContext,
2474 ) -> Option<String> {
2475 let expr_str = try_opt!(expr.rewrite(context, shape));
2477 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
2483 let offset = last_line_width(&expr_str) + lbr.len();
2484 let rhs_overhead = shape.rhs_overhead(context.config);
2485 let index_shape = if expr_str.contains('\n') {
2486 Shape::legacy(context.config.max_width(), shape.indent)
2487 .offset_left(offset)
2488 .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
2490 shape.visual_indent(offset).sub_width(offset + rbr.len())
2492 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
2494 // Return if index fits in a single line.
2495 match orig_index_rw {
2496 Some(ref index_str) if !index_str.contains('\n') => {
2497 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2502 // Try putting index on the next line and see if it fits in a single line.
2503 let indent = shape.indent.block_indent(context.config);
2504 let index_shape = try_opt!(Shape::indented(indent, context.config).offset_left(lbr.len()));
2505 let index_shape = try_opt!(index_shape.sub_width(rbr.len() + rhs_overhead));
2506 let new_index_rw = index.rewrite(context, index_shape);
2507 match (orig_index_rw, new_index_rw) {
2508 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
2511 indent.to_string(&context.config),
2516 (None, Some(ref new_index_str)) => Some(format!(
2519 indent.to_string(&context.config),
2524 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2529 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2534 fields.iter().all(|field| !field.is_shorthand)
2537 fn rewrite_struct_lit<'a>(
2538 context: &RewriteContext,
2540 fields: &'a [ast::Field],
2541 base: Option<&'a ast::Expr>,
2544 ) -> Option<String> {
2545 debug!("rewrite_struct_lit: shape {:?}", shape);
2547 enum StructLitField<'a> {
2548 Regular(&'a ast::Field),
2549 Base(&'a ast::Expr),
2553 let path_shape = try_opt!(shape.sub_width(2));
2554 let path_str = try_opt!(rewrite_path(
2562 if fields.len() == 0 && base.is_none() {
2563 return Some(format!("{} {{}}", path_str));
2566 // Foo { a: Foo } - indent is +3, width is -5.
2567 let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
2569 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2570 let body_lo = context.codemap.span_after(span, "{");
2571 let fields_str = if struct_lit_can_be_aligned(fields, &base) &&
2572 context.config.struct_field_align_threshold() > 0
2574 try_opt!(rewrite_with_alignment(
2578 mk_sp(body_lo, span.hi),
2582 let field_iter = fields
2584 .map(StructLitField::Regular)
2585 .chain(base.into_iter().map(StructLitField::Base));
2587 let span_lo = |item: &StructLitField| match *item {
2588 StructLitField::Regular(field) => field.span().lo,
2589 StructLitField::Base(expr) => {
2590 let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
2591 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
2592 let pos = snippet.find_uncommented("..").unwrap();
2593 last_field_hi + BytePos(pos as u32)
2596 let span_hi = |item: &StructLitField| match *item {
2597 StructLitField::Regular(field) => field.span().hi,
2598 StructLitField::Base(expr) => expr.span.hi,
2600 let rewrite = |item: &StructLitField| match *item {
2601 StructLitField::Regular(field) => {
2602 // The 1 taken from the v_budget is for the comma.
2603 rewrite_field(context, field, try_opt!(v_shape.sub_width(1)), 0)
2605 StructLitField::Base(expr) => {
2607 expr.rewrite(context, try_opt!(v_shape.offset_left(2)))
2608 .map(|s| format!("..{}", s))
2612 let items = itemize_list(
2623 let item_vec = items.collect::<Vec<_>>();
2625 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2626 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2627 let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2629 try_opt!(write_list(&item_vec, &fmt))
2632 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2633 Some(format!("{} {{{}}}", path_str, fields_str))
2635 // FIXME if context.config.struct_lit_style() == Visual, but we run out
2636 // of space, we should fall back to BlockIndent.
2639 pub fn wrap_struct_field(
2640 context: &RewriteContext,
2643 nested_shape: Shape,
2644 one_line_width: usize,
2646 if context.config.struct_lit_style() == IndentStyle::Block &&
2647 (fields_str.contains('\n') ||
2648 context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti ||
2649 fields_str.len() > one_line_width)
2653 nested_shape.indent.to_string(context.config),
2655 shape.indent.to_string(context.config)
2658 // One liner or visual indent.
2659 format!(" {} ", fields_str)
2663 pub fn struct_lit_field_separator(config: &Config) -> &str {
2665 config.space_before_struct_lit_field_colon(),
2666 config.space_after_struct_lit_field_colon(),
2670 pub fn rewrite_field(
2671 context: &RewriteContext,
2674 prefix_max_width: usize,
2675 ) -> Option<String> {
2676 if contains_skip(&field.attrs) {
2678 context.snippet(field.span()),
2679 context.config.max_width(),
2683 let name = &field.ident.node.to_string();
2684 if field.is_shorthand {
2685 Some(name.to_string())
2687 let mut separator = String::from(struct_lit_field_separator(context.config));
2688 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2689 separator.push(' ');
2691 let overhead = name.len() + separator.len();
2692 let expr_shape = try_opt!(shape.offset_left(overhead));
2693 let expr = field.expr.rewrite(context, expr_shape);
2695 let mut attrs_str = try_opt!(field.attrs.rewrite(context, shape));
2696 if !attrs_str.is_empty() {
2697 attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2701 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2703 let expr_offset = shape.indent.block_indent(context.config);
2706 .rewrite(context, Shape::indented(expr_offset, context.config));
2712 expr_offset.to_string(&context.config),
2721 fn shape_from_fn_call_style(
2722 context: &RewriteContext,
2726 ) -> Option<Shape> {
2727 if context.use_block_indent() {
2731 .block_indent(context.config.tab_spaces())
2732 .with_max_width(context.config)
2735 shape.visual_indent(offset).sub_width(overhead)
2739 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2740 context: &RewriteContext,
2746 T: Rewrite + Spanned + ToExpr + 'a,
2748 let mut items = items.iter();
2749 // In case of length 1, need a trailing comma
2750 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2751 if items.len() == 1 {
2753 let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
2754 return items.next().unwrap().rewrite(context, nested_shape).map(
2755 |s| if context.config.spaces_within_parens() {
2756 format!("( {}, )", s)
2763 let list_lo = context.codemap.span_after(span, "(");
2764 let nested_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
2765 let items = itemize_list(
2769 |item| item.span().lo,
2770 |item| item.span().hi,
2771 |item| item.rewrite(context, nested_shape),
2773 span.hi - BytePos(1),
2776 let item_vec: Vec<_> = items.collect();
2777 let tactic = definitive_tactic(
2779 ListTactic::HorizontalVertical,
2783 let fmt = ListFormatting {
2786 trailing_separator: SeparatorTactic::Never,
2787 separator_place: SeparatorPlace::Back,
2789 ends_with_newline: false,
2790 preserve_newline: false,
2791 config: context.config,
2793 let list_str = try_opt!(write_list(&item_vec, &fmt));
2795 if context.config.spaces_within_parens() && list_str.len() > 0 {
2796 Some(format!("( {} )", list_str))
2798 Some(format!("({})", list_str))
2802 pub fn rewrite_tuple<'a, T>(
2803 context: &RewriteContext,
2809 T: Rewrite + Spanned + ToExpr + 'a,
2811 debug!("rewrite_tuple {:?}", shape);
2812 if context.use_block_indent() {
2813 // We use the same rule as function calls for rewriting tuples.
2814 let force_trailing_comma = if context.inside_macro {
2815 span_ends_with_comma(context, span)
2825 context.config.fn_call_width(),
2826 force_trailing_comma,
2829 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2833 pub fn rewrite_unary_prefix<R: Rewrite>(
2834 context: &RewriteContext,
2838 ) -> Option<String> {
2840 .rewrite(context, try_opt!(shape.offset_left(prefix.len())))
2841 .map(|r| format!("{}{}", prefix, r))
2844 // FIXME: this is probably not correct for multi-line Rewrites. we should
2845 // subtract suffix.len() from the last line budget, not the first!
2846 pub fn rewrite_unary_suffix<R: Rewrite>(
2847 context: &RewriteContext,
2851 ) -> Option<String> {
2853 .rewrite(context, try_opt!(shape.sub_width(suffix.len())))
2860 fn rewrite_unary_op(
2861 context: &RewriteContext,
2865 ) -> Option<String> {
2866 // For some reason, an UnOp is not spanned like BinOp!
2867 let operator_str = match *op {
2868 ast::UnOp::Deref => "*",
2869 ast::UnOp::Not => "!",
2870 ast::UnOp::Neg => "-",
2872 rewrite_unary_prefix(context, operator_str, expr, shape)
2875 fn rewrite_assignment(
2876 context: &RewriteContext,
2879 op: Option<&ast::BinOp>,
2881 ) -> Option<String> {
2882 let operator_str = match op {
2883 Some(op) => context.snippet(op.span),
2884 None => "=".to_owned(),
2887 // 1 = space between lhs and operator.
2888 let lhs_shape = try_opt!(shape.sub_width(operator_str.len() + 1));
2889 let lhs_str = format!(
2891 try_opt!(lhs.rewrite(context, lhs_shape)),
2895 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2898 // The left hand side must contain everything up to, and including, the
2899 // assignment operator.
2900 pub fn rewrite_assign_rhs<S: Into<String>>(
2901 context: &RewriteContext,
2905 ) -> Option<String> {
2906 let lhs = lhs.into();
2907 let last_line_width = last_line_width(&lhs) - if lhs.contains('\n') {
2908 shape.indent.width()
2912 // 1 = space between operator and rhs.
2913 let orig_shape = try_opt!(shape.offset_left(last_line_width + 1));
2914 let rhs = try_opt!(choose_rhs(
2918 ex.rewrite(context, orig_shape)
2924 context: &RewriteContext,
2927 orig_rhs: Option<String>,
2928 ) -> Option<String> {
2930 Some(ref new_str) if !new_str.contains('\n') => Some(format!(" {}", new_str)),
2932 // Expression did not fit on the same line as the identifier.
2933 // Try splitting the line and see if that works better.
2934 let new_shape = try_opt!(
2936 shape.block().indent.block_indent(context.config),
2938 ).sub_width(shape.rhs_overhead(context.config))
2940 let new_rhs = expr.rewrite(context, new_shape);
2941 let new_indent_str = &new_shape.indent.to_string(context.config);
2943 match (orig_rhs, new_rhs) {
2944 (Some(ref orig_rhs), Some(ref new_rhs)) if prefer_next_line(orig_rhs, new_rhs) => {
2945 Some(format!("\n{}{}", new_indent_str, new_rhs))
2947 (None, Some(ref new_rhs)) => Some(format!("\n{}{}", new_indent_str, new_rhs)),
2948 (None, None) => None,
2949 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2955 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {
2956 fn count_line_breaks(src: &str) -> usize {
2957 src.chars().filter(|&x| x == '\n').count()
2960 !next_line_rhs.contains('\n') ||
2961 count_line_breaks(orig_rhs) > count_line_breaks(next_line_rhs) + 1
2964 fn rewrite_expr_addrof(
2965 context: &RewriteContext,
2966 mutability: ast::Mutability,
2969 ) -> Option<String> {
2970 let operator_str = match mutability {
2971 ast::Mutability::Immutable => "&",
2972 ast::Mutability::Mutable => "&mut ",
2974 rewrite_unary_prefix(context, operator_str, expr, shape)
2978 fn to_expr(&self) -> Option<&ast::Expr>;
2979 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2982 impl ToExpr for ast::Expr {
2983 fn to_expr(&self) -> Option<&ast::Expr> {
2987 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2988 can_be_overflowed_expr(context, self, len)
2992 impl ToExpr for ast::Ty {
2993 fn to_expr(&self) -> Option<&ast::Expr> {
2997 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2998 can_be_overflowed_type(context, self, len)
3002 impl<'a> ToExpr for TuplePatField<'a> {
3003 fn to_expr(&self) -> Option<&ast::Expr> {
3007 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
3008 can_be_overflowed_pat(context, self, len)
3012 impl<'a> ToExpr for ast::StructField {
3013 fn to_expr(&self) -> Option<&ast::Expr> {
3017 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {