1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use std::cmp::{min, Ordering};
13 use std::iter::ExactSizeIterator;
15 use syntax::{ast, ptr};
16 use syntax::codemap::{BytePos, CodeMap, Span};
17 use syntax::parse::classify;
19 use {Indent, Shape, Spanned};
20 use chains::rewrite_chain;
21 use codemap::{LineRangeUtils, SpanUtils};
22 use comment::{contains_comment, recover_comment_removed, rewrite_comment, FindUncommented};
23 use config::{Config, ControlBraceStyle, IndentStyle, MultilineStyle, Style};
24 use items::{span_hi_for_arg, span_lo_for_arg};
25 use lists::{definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting,
26 struct_lit_shape, struct_lit_tactic, write_list, DefinitiveListTactic, ListFormatting,
27 ListItem, ListTactic, SeparatorTactic};
28 use macros::{rewrite_macro, MacroPosition};
29 use patterns::{can_be_overflowed_pat, TuplePatField};
30 use rewrite::{Rewrite, RewriteContext};
31 use string::{rewrite_string, StringFormat};
32 use types::{can_be_overflowed_type, rewrite_path, PathContext};
33 use utils::{binary_search, colon_spaces, contains_skip, extra_offset, first_line_width,
34 last_line_extendable, last_line_width, left_most_sub_expr, mk_sp, paren_overhead,
35 semicolon_for_stmt, stmt_expr, trimmed_last_line_width, wrap_str};
36 use vertical::rewrite_with_alignment;
37 use visitor::FmtVisitor;
39 impl Rewrite for ast::Expr {
40 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
41 format_expr(self, ExprType::SubExpression, context, shape)
51 fn combine_attr_and_expr(
52 context: &RewriteContext,
57 let attr_str = try_opt!((&*expr.attrs).rewrite(context, shape));
58 let separator = if attr_str.is_empty() {
61 // Try to recover comments between the attributes and the expression if available.
62 let missing_snippet = context.snippet(mk_sp(
63 expr.attrs[expr.attrs.len() - 1].span.hi,
66 let comment_opening_pos = missing_snippet.chars().position(|c| c == '/');
67 let prefer_same_line = if let Some(pos) = comment_opening_pos {
68 !missing_snippet[..pos].contains('\n')
70 !missing_snippet.contains('\n')
73 let trimmed = missing_snippet.trim();
74 let missing_comment = if trimmed.is_empty() {
77 try_opt!(rewrite_comment(&trimmed, false, shape, context.config))
82 attr_str.len() + missing_comment.len() + 2 + first_line_width(expr_str);
83 let attr_expr_separator = if prefer_same_line && !missing_comment.starts_with("//") &&
84 one_line_width <= shape.width
88 format!("\n{}", shape.indent.to_string(context.config))
91 if missing_comment.is_empty() {
96 last_line_width(&attr_str) + 1 + first_line_width(&missing_comment);
97 let attr_comment_separator = if prefer_same_line && one_line_width <= shape.width {
100 format!("\n{}", shape.indent.to_string(context.config))
102 attr_comment_separator + &missing_comment + &attr_expr_separator
105 Some(format!("{}{}{}", attr_str, separator, expr_str))
111 context: &RewriteContext,
113 ) -> Option<String> {
114 skip_out_of_file_lines_range!(context, expr.span);
116 if contains_skip(&*expr.attrs) {
117 return Some(context.snippet(expr.span()));
120 let expr_rw = match expr.node {
121 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
122 expr_vec.iter().map(|e| &**e),
123 mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi),
128 ast::ExprKind::Lit(ref l) => match l.node {
129 ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
130 rewrite_string_lit(context, l.span, shape)
133 context.snippet(expr.span),
134 context.config.max_width(),
138 ast::ExprKind::Call(ref callee, ref args) => {
139 let inner_span = mk_sp(callee.span.hi, expr.span.hi);
140 rewrite_call_with_binary_search(
143 &args.iter().map(|x| &**x).collect::<Vec<_>>()[..],
148 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
149 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
150 // FIXME: format comments between operands and operator
155 &format!(" {} ", context.snippet(op.span)),
161 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
162 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
166 base.as_ref().map(|e| &**e),
170 ast::ExprKind::Tup(ref items) => rewrite_tuple(
172 &items.iter().map(|x| &**x).collect::<Vec<_>>()[..],
176 ast::ExprKind::If(..) |
177 ast::ExprKind::IfLet(..) |
178 ast::ExprKind::ForLoop(..) |
179 ast::ExprKind::Loop(..) |
180 ast::ExprKind::While(..) |
181 ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
182 .and_then(|control_flow| control_flow.rewrite(context, shape)),
183 ast::ExprKind::Block(ref block) => {
185 ExprType::Statement => {
186 if is_unsafe_block(block) {
187 block.rewrite(context, shape)
189 // Rewrite block without trying to put it in a single line.
190 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
193 let prefix = try_opt!(block_prefix(context, block, shape));
194 rewrite_block_with_visitor(context, &prefix, block, shape)
197 ExprType::SubExpression => block.rewrite(context, shape),
200 ast::ExprKind::Match(ref cond, ref arms) => {
201 rewrite_match(context, cond, arms, shape, expr.span)
203 ast::ExprKind::Path(ref qself, ref path) => {
204 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
206 ast::ExprKind::Assign(ref lhs, ref rhs) => {
207 rewrite_assignment(context, lhs, rhs, None, shape)
209 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
210 rewrite_assignment(context, lhs, rhs, Some(op), shape)
212 ast::ExprKind::Continue(ref opt_ident) => {
213 let id_str = match *opt_ident {
214 Some(ident) => format!(" {}", ident.node),
215 None => String::new(),
218 format!("continue{}", id_str),
219 context.config.max_width(),
223 ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
224 let id_str = match *opt_ident {
225 Some(ident) => format!(" {}", ident.node),
226 None => String::new(),
229 if let Some(ref expr) = *opt_expr {
230 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
233 format!("break{}", id_str),
234 context.config.max_width(),
239 ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
240 rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
242 ast::ExprKind::Try(..) |
243 ast::ExprKind::Field(..) |
244 ast::ExprKind::TupField(..) |
245 ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
246 ast::ExprKind::Mac(ref mac) => {
247 // Failure to rewrite a marco should not imply failure to
248 // rewrite the expression.
249 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
251 context.snippet(expr.span),
252 context.config.max_width(),
257 ast::ExprKind::Ret(None) => {
258 wrap_str("return".to_owned(), context.config.max_width(), shape)
260 ast::ExprKind::Ret(Some(ref expr)) => {
261 rewrite_unary_prefix(context, "return ", &**expr, shape)
263 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
264 ast::ExprKind::AddrOf(mutability, ref expr) => {
265 rewrite_expr_addrof(context, mutability, expr, shape)
267 ast::ExprKind::Cast(ref expr, ref ty) => {
268 rewrite_pair(&**expr, &**ty, "", " as ", "", context, shape)
270 ast::ExprKind::Type(ref expr, ref ty) => {
271 rewrite_pair(&**expr, &**ty, "", ": ", "", context, shape)
273 ast::ExprKind::Index(ref expr, ref index) => {
274 rewrite_index(&**expr, &**index, context, shape)
276 ast::ExprKind::Repeat(ref expr, ref repeats) => {
277 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
282 rewrite_pair(&**expr, &**repeats, lbr, "; ", rbr, context, shape)
284 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
285 let delim = match limits {
286 ast::RangeLimits::HalfOpen => "..",
287 ast::RangeLimits::Closed => "...",
290 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
292 ast::ExprKind::Lit(ref lit) => match lit.node {
293 ast::LitKind::FloatUnsuffixed(..) => {
294 context.snippet(lit.span).ends_with('.')
302 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
303 (Some(ref lhs), Some(ref rhs)) => {
304 let sp_delim = if context.config.spaces_around_ranges() {
305 format!(" {} ", delim)
306 } else if needs_space_before_range(context, lhs) {
307 format!(" {}", delim)
311 rewrite_pair(&**lhs, &**rhs, "", &sp_delim, "", context, shape)
313 (None, Some(ref rhs)) => {
314 let sp_delim = if context.config.spaces_around_ranges() {
315 format!("{} ", delim)
319 rewrite_unary_prefix(context, &sp_delim, &**rhs, shape)
321 (Some(ref lhs), None) => {
322 let sp_delim = if context.config.spaces_around_ranges() {
323 format!(" {}", delim)
327 rewrite_unary_suffix(context, &sp_delim, &**lhs, shape)
329 (None, None) => wrap_str(delim.into(), context.config.max_width(), shape),
332 // We do not format these expressions yet, but they should still
333 // satisfy our width restrictions.
334 ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => wrap_str(
335 context.snippet(expr.span),
336 context.config.max_width(),
339 ast::ExprKind::Catch(ref block) => {
340 if let rewrite @ Some(_) = rewrite_single_line_block(context, "do catch ", block, shape)
345 let budget = shape.width.checked_sub(9).unwrap_or(0);
349 try_opt!(block.rewrite(&context, Shape::legacy(budget, shape.indent)))
355 .and_then(|expr_str| {
356 recover_comment_removed(expr_str, expr.span, context, shape)
358 .and_then(|expr_str| {
359 combine_attr_and_expr(context, shape, expr, &expr_str)
363 pub fn rewrite_pair<LHS, RHS>(
369 context: &RewriteContext,
376 let sep = if infix.ends_with(' ') { " " } else { "" };
377 let infix = infix.trim_right();
378 let lhs_overhead = shape.used_width() + prefix.len() + infix.len();
379 let lhs_shape = Shape {
380 width: try_opt!(context.config.max_width().checked_sub(lhs_overhead)),
383 let lhs_result = try_opt!(
384 lhs.rewrite(context, lhs_shape)
385 .map(|lhs_str| format!("{}{}{}", prefix, lhs_str, infix))
388 // Try to the both lhs and rhs on the same line.
389 let rhs_orig_result = shape
390 .offset_left(last_line_width(&lhs_result) + suffix.len() + sep.len())
391 .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
392 if let Some(ref rhs_result) = rhs_orig_result {
393 // If the rhs looks like block expression, we allow it to stay on the same line
394 // with the lhs even if it is multi-lined.
395 let allow_same_line = rhs_result
398 .map(|first_line| first_line.ends_with('{'))
400 if !rhs_result.contains('\n') || allow_same_line {
401 return Some(format!("{}{}{}{}", lhs_result, sep, rhs_result, suffix));
405 // We have to use multiple lines.
406 // Re-evaluate the rhs because we have more space now:
407 let rhs_shape = match context.config.control_style() {
409 try_opt!(shape.sub_width(suffix.len() + prefix.len())).visual_indent(prefix.len())
412 // Try to calculate the initial constraint on the right hand side.
413 let rhs_overhead = shape.rhs_overhead(context.config);
415 Shape::indented(shape.indent.block_indent(context.config), context.config)
416 .sub_width(rhs_overhead)
420 let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape));
424 rhs_shape.indent.to_string(context.config),
430 pub fn rewrite_array<'a, I>(
433 context: &RewriteContext,
435 trailing_comma: bool,
438 I: Iterator<Item = &'a ast::Expr>,
440 let bracket_size = if context.config.spaces_within_square_brackets() {
446 let mut nested_shape = match context.config.array_layout() {
447 IndentStyle::Block => try_opt!(
450 .block_indent(context.config.tab_spaces())
451 .with_max_width(context.config)
454 IndentStyle::Visual => try_opt!(
456 .visual_indent(bracket_size)
457 .sub_width(bracket_size * 2)
461 let items = itemize_list(
467 |item| item.rewrite(context, nested_shape),
470 ).collect::<Vec<_>>();
472 if items.is_empty() {
473 if context.config.spaces_within_square_brackets() {
474 return Some("[ ]".to_string());
476 return Some("[]".to_string());
480 let has_long_item = items
482 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
484 let mut tactic = match context.config.array_layout() {
485 IndentStyle::Block => {
486 // FIXME wrong shape in one-line case
487 match shape.width.checked_sub(2 * bracket_size) {
490 ListTactic::LimitedHorizontalVertical(context.config.array_width());
491 definitive_tactic(&items, tactic, width)
493 None => DefinitiveListTactic::Vertical,
496 IndentStyle::Visual => if has_long_item || items.iter().any(ListItem::is_multiline) {
499 ListTactic::LimitedHorizontalVertical(context.config.array_width()),
503 DefinitiveListTactic::Mixed
506 let mut ends_with_newline = tactic.ends_with_newline(context.config.array_layout());
507 if context.config.array_horizontal_layout_threshold() > 0 &&
508 items.len() > context.config.array_horizontal_layout_threshold()
510 tactic = DefinitiveListTactic::Mixed;
511 ends_with_newline = false;
512 if context.config.array_layout() == IndentStyle::Block {
513 nested_shape = try_opt!(
515 .visual_indent(bracket_size)
516 .sub_width(bracket_size * 2)
521 let fmt = ListFormatting {
524 trailing_separator: if trailing_comma {
525 SeparatorTactic::Always
526 } else if context.inside_macro || context.config.array_layout() == IndentStyle::Visual {
527 SeparatorTactic::Never
529 SeparatorTactic::Vertical
532 ends_with_newline: ends_with_newline,
533 preserve_newline: false,
534 config: context.config,
536 let list_str = try_opt!(write_list(&items, &fmt));
538 let result = if context.config.array_layout() == IndentStyle::Visual ||
539 tactic != DefinitiveListTactic::Vertical
541 if context.config.spaces_within_square_brackets() && list_str.len() > 0 {
542 format!("[ {} ]", list_str)
544 format!("[{}]", list_str)
549 nested_shape.indent.to_string(context.config),
551 shape.block().indent.to_string(context.config)
558 // Return type is (prefix, extra_offset)
559 fn rewrite_closure_fn_decl(
560 capture: ast::CaptureBy,
561 fn_decl: &ast::FnDecl,
564 context: &RewriteContext,
566 ) -> Option<(String, usize)> {
567 let mover = if capture == ast::CaptureBy::Value {
572 // 4 = "|| {".len(), which is overconservative when the closure consists of
573 // a single expression.
574 let nested_shape = try_opt!(try_opt!(shape.shrink_left(mover.len())).sub_width(4));
577 let argument_offset = nested_shape.indent + 1;
578 let arg_shape = try_opt!(nested_shape.offset_left(1)).visual_indent(0);
579 let ret_str = try_opt!(fn_decl.output.rewrite(context, arg_shape));
581 let arg_items = itemize_list(
583 fn_decl.inputs.iter(),
585 |arg| span_lo_for_arg(arg),
586 |arg| span_hi_for_arg(context, arg),
587 |arg| arg.rewrite(context, arg_shape),
588 context.codemap.span_after(span, "|"),
591 let item_vec = arg_items.collect::<Vec<_>>();
592 // 1 = space between arguments and return type.
593 let horizontal_budget = nested_shape
595 .checked_sub(ret_str.len() + 1)
597 let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
598 let arg_shape = match tactic {
599 DefinitiveListTactic::Horizontal => try_opt!(arg_shape.sub_width(ret_str.len() + 1)),
603 let fmt = ListFormatting {
606 trailing_separator: SeparatorTactic::Never,
608 ends_with_newline: false,
609 preserve_newline: true,
610 config: context.config,
612 let list_str = try_opt!(write_list(&item_vec, &fmt));
613 let mut prefix = format!("{}|{}|", mover, list_str);
614 // 1 = space between `|...|` and body.
615 let extra_offset = extra_offset(&prefix, shape) + 1;
617 if !ret_str.is_empty() {
618 if prefix.contains('\n') {
620 prefix.push_str(&argument_offset.to_string(context.config));
624 prefix.push_str(&ret_str);
627 Some((prefix, extra_offset))
630 // This functions is pretty messy because of the rules around closures and blocks:
631 // FIXME - the below is probably no longer true in full.
632 // * if there is a return type, then there must be braces,
633 // * given a closure with braces, whether that is parsed to give an inner block
634 // or not depends on if there is a return type and if there are statements
636 // * if the first expression in the body ends with a block (i.e., is a
637 // statement without needing a semi-colon), then adding or removing braces
638 // can change whether it is treated as an expression or statement.
640 capture: ast::CaptureBy,
641 fn_decl: &ast::FnDecl,
644 context: &RewriteContext,
646 ) -> Option<String> {
647 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
655 // 1 = space between `|...|` and body.
656 let body_shape = try_opt!(shape.offset_left(extra_offset));
658 if let ast::ExprKind::Block(ref block) = body.node {
659 // The body of the closure is an empty block.
660 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
661 return Some(format!("{} {{}}", prefix));
664 // Figure out if the block is necessary.
665 let needs_block = block.rules != ast::BlockCheckMode::Default || block.stmts.len() > 1 ||
666 context.inside_macro ||
667 block_contains_comment(block, context.codemap) ||
668 prefix.contains('\n');
670 let no_return_type = if let ast::FunctionRetTy::Default(_) = fn_decl.output {
675 if no_return_type && !needs_block {
676 // lock.stmts.len() == 1
677 if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
678 if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
685 // We need braces, but we might still prefer a one-liner.
686 let stmt = &block.stmts[0];
687 // 4 = braces and spaces.
688 if let Some(body_shape) = body_shape.sub_width(4) {
689 // Checks if rewrite succeeded and fits on a single line.
690 if let Some(rewrite) = and_one_line(stmt.rewrite(context, body_shape)) {
691 return Some(format!("{} {{ {} }}", prefix, rewrite));
696 // Either we require a block, or tried without and failed.
697 rewrite_closure_block(&block, &prefix, context, body_shape)
699 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
700 // The closure originally had a non-block expression, but we can't fit on
701 // one line, so we'll insert a block.
702 rewrite_closure_with_block(context, body_shape, &prefix, body)
707 // Rewrite closure with a single expression wrapping its body with block.
708 fn rewrite_closure_with_block(
709 context: &RewriteContext,
713 ) -> Option<String> {
714 let block = ast::Block {
717 id: ast::NodeId::new(0),
718 node: ast::StmtKind::Expr(ptr::P(body.clone())),
722 id: ast::NodeId::new(0),
723 rules: ast::BlockCheckMode::Default,
726 rewrite_closure_block(&block, prefix, context, shape)
729 // Rewrite closure with a single expression without wrapping its body with block.
730 fn rewrite_closure_expr(
733 context: &RewriteContext,
735 ) -> Option<String> {
736 let mut rewrite = expr.rewrite(context, shape);
737 if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
738 rewrite = and_one_line(rewrite);
740 rewrite.map(|rw| format!("{} {}", prefix, rw))
743 // Rewrite closure whose body is block.
744 fn rewrite_closure_block(
747 context: &RewriteContext,
749 ) -> Option<String> {
750 // Start with visual indent, then fall back to block indent if the
752 let block_threshold = context.config.closure_block_indent_threshold();
753 if block_threshold >= 0 {
754 if let Some(block_str) = block.rewrite(&context, shape) {
755 if block_str.matches('\n').count() <= block_threshold as usize &&
756 !need_block_indent(&block_str, shape)
758 if let Some(block_str) = block_str.rewrite(context, shape) {
759 return Some(format!("{} {}", prefix, block_str));
765 // The body of the closure is big enough to be block indented, that
766 // means we must re-format.
767 let block_shape = shape.block();
768 let block_str = try_opt!(block.rewrite(&context, block_shape));
769 Some(format!("{} {}", prefix, block_str))
772 fn and_one_line(x: Option<String>) -> Option<String> {
773 x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
776 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
777 debug!("nop_block_collapse {:?} {}", block_str, budget);
778 block_str.map(|block_str| {
779 if block_str.starts_with('{') && budget >= 2 &&
780 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
789 fn rewrite_empty_block(
790 context: &RewriteContext,
793 ) -> Option<String> {
794 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
796 return Some("{}".to_owned());
799 // If a block contains only a single-line comment, then leave it on one line.
800 let user_str = context.snippet(block.span);
801 let user_str = user_str.trim();
802 if user_str.starts_with('{') && user_str.ends_with('}') {
803 let comment_str = user_str[1..user_str.len() - 1].trim();
804 if block.stmts.is_empty() && !comment_str.contains('\n') &&
805 !comment_str.starts_with("//") && comment_str.len() + 4 <= shape.width
807 return Some(format!("{{ {} }}", comment_str));
814 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
815 Some(match block.rules {
816 ast::BlockCheckMode::Unsafe(..) => {
817 let snippet = context.snippet(block.span);
818 let open_pos = try_opt!(snippet.find_uncommented("{"));
819 // Extract comment between unsafe and block start.
820 let trimmed = &snippet[6..open_pos].trim();
822 if !trimmed.is_empty() {
823 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
824 let budget = try_opt!(shape.width.checked_sub(9));
827 try_opt!(rewrite_comment(
830 Shape::legacy(budget, shape.indent + 7),
838 ast::BlockCheckMode::Default => String::new(),
842 fn rewrite_single_line_block(
843 context: &RewriteContext,
847 ) -> Option<String> {
848 if is_simple_block(block, context.codemap) {
849 let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
850 let expr_str = try_opt!(block.stmts[0].rewrite(context, expr_shape));
851 let result = format!("{}{{ {} }}", prefix, expr_str);
852 if result.len() <= shape.width && !result.contains('\n') {
859 fn rewrite_block_with_visitor(
860 context: &RewriteContext,
864 ) -> Option<String> {
865 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
869 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
870 visitor.block_indent = shape.indent;
871 visitor.is_if_else_block = context.is_if_else_block;
873 ast::BlockCheckMode::Unsafe(..) => {
874 let snippet = context.snippet(block.span);
875 let open_pos = try_opt!(snippet.find_uncommented("{"));
876 visitor.last_pos = block.span.lo + BytePos(open_pos as u32)
878 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo,
881 visitor.visit_block(block, None);
882 Some(format!("{}{}", prefix, visitor.buffer))
885 impl Rewrite for ast::Block {
886 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
887 // shape.width is used only for the single line case: either the empty block `{}`,
888 // or an unsafe expression `unsafe { e }`.
889 if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
893 let prefix = try_opt!(block_prefix(context, self, shape));
894 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
898 rewrite_block_with_visitor(context, &prefix, self, shape)
902 impl Rewrite for ast::Stmt {
903 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
904 skip_out_of_file_lines_range!(context, self.span());
906 let result = match self.node {
907 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
908 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
909 let suffix = if semicolon_for_stmt(context, self) {
918 ast::StmtKind::Expr(_) => ExprType::SubExpression,
919 ast::StmtKind::Semi(_) => ExprType::Statement,
923 try_opt!(shape.sub_width(suffix.len())),
924 ).map(|s| s + suffix)
926 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
928 result.and_then(|res| {
929 recover_comment_removed(res, self.span(), context, shape)
934 // Rewrite condition if the given expression has one.
935 fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
937 ast::ExprKind::Match(ref cond, _) => {
939 let cond_shape = match context.config.control_style() {
940 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
941 Style::Rfc => try_opt!(shape.offset_left(8)),
943 cond.rewrite(context, cond_shape)
945 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
946 stmt_expr(&block.stmts[0]).and_then(|e| rewrite_cond(context, e, shape))
948 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
950 String::from("\n") + &shape.indent.block_only().to_string(context.config);
952 .rewrite_cond(context, shape, &alt_block_sep)
953 .and_then(|rw| Some(rw.0))
958 // Abstraction over control flow expressions
960 struct ControlFlow<'a> {
961 cond: Option<&'a ast::Expr>,
962 block: &'a ast::Block,
963 else_block: Option<&'a ast::Expr>,
964 label: Option<ast::SpannedIdent>,
965 pat: Option<&'a ast::Pat>,
969 allow_single_line: bool,
970 // True if this is an `if` expression in an `else if` :-( hacky
975 fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'a>> {
977 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
981 else_block.as_ref().map(|e| &**e),
982 expr_type == ExprType::SubExpression,
986 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
987 Some(ControlFlow::new_if(
991 else_block.as_ref().map(|e| &**e),
992 expr_type == ExprType::SubExpression,
997 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
998 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
1000 ast::ExprKind::Loop(ref block, label) => {
1001 Some(ControlFlow::new_loop(block, label, expr.span))
1003 ast::ExprKind::While(ref cond, ref block, label) => {
1004 Some(ControlFlow::new_while(None, cond, block, label, expr.span))
1006 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
1007 ControlFlow::new_while(Some(pat), cond, block, label, expr.span),
1013 impl<'a> ControlFlow<'a> {
1015 cond: &'a ast::Expr,
1016 pat: Option<&'a ast::Pat>,
1017 block: &'a ast::Block,
1018 else_block: Option<&'a ast::Expr>,
1019 allow_single_line: bool,
1022 ) -> ControlFlow<'a> {
1026 else_block: else_block,
1030 matcher: match pat {
1035 allow_single_line: allow_single_line,
1036 nested_if: nested_if,
1042 block: &'a ast::Block,
1043 label: Option<ast::SpannedIdent>,
1045 ) -> ControlFlow<'a> {
1055 allow_single_line: false,
1062 pat: Option<&'a ast::Pat>,
1063 cond: &'a ast::Expr,
1064 block: &'a ast::Block,
1065 label: Option<ast::SpannedIdent>,
1067 ) -> ControlFlow<'a> {
1075 matcher: match pat {
1080 allow_single_line: false,
1088 cond: &'a ast::Expr,
1089 block: &'a ast::Block,
1090 label: Option<ast::SpannedIdent>,
1092 ) -> ControlFlow<'a> {
1102 allow_single_line: false,
1108 fn rewrite_single_line(
1111 context: &RewriteContext,
1113 ) -> Option<String> {
1114 assert!(self.allow_single_line);
1115 let else_block = try_opt!(self.else_block);
1116 let fixed_cost = self.keyword.len() + " { } else { }".len();
1118 if let ast::ExprKind::Block(ref else_node) = else_block.node {
1119 if !is_simple_block(self.block, context.codemap) ||
1120 !is_simple_block(else_node, context.codemap) ||
1121 pat_expr_str.contains('\n')
1126 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
1127 let expr = &self.block.stmts[0];
1128 let if_str = try_opt!(expr.rewrite(
1130 Shape::legacy(new_width, Indent::empty()),
1133 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
1134 let else_expr = &else_node.stmts[0];
1136 try_opt!(else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
1138 if if_str.contains('\n') || else_str.contains('\n') {
1142 let result = format!(
1143 "{} {} {{ {} }} else {{ {} }}",
1150 if result.len() <= width {
1151 return Some(result);
1159 impl<'a> ControlFlow<'a> {
1162 context: &RewriteContext,
1164 alt_block_sep: &str,
1165 ) -> Option<(String, usize)> {
1166 // Do not take the rhs overhead from the upper expressions into account
1167 // when rewriting pattern.
1168 let new_width = context
1171 .checked_sub(shape.used_width())
1173 let fresh_shape = Shape {
1177 let constr_shape = if self.nested_if {
1178 // We are part of an if-elseif-else chain. Our constraints are tightened.
1179 // 7 = "} else " .len()
1180 try_opt!(fresh_shape.offset_left(7))
1185 let label_string = rewrite_label(self.label);
1186 // 1 = space after keyword.
1187 let offset = self.keyword.len() + label_string.len() + 1;
1189 let pat_expr_string = match self.cond {
1191 let cond_shape = match context.config.control_style() {
1192 Style::Legacy => try_opt!(constr_shape.shrink_left(offset)),
1193 Style::Rfc => try_opt!(constr_shape.offset_left(offset)),
1195 try_opt!(rewrite_pat_expr(
1205 None => String::new(),
1208 let brace_overhead =
1209 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1215 let one_line_budget = context
1218 .checked_sub(constr_shape.used_width() + offset + brace_overhead)
1220 let force_newline_brace = context.config.control_style() == Style::Rfc &&
1221 (pat_expr_string.contains('\n') || pat_expr_string.len() > one_line_budget) &&
1222 !last_line_extendable(&pat_expr_string);
1224 // Try to format if-else on single line.
1225 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1226 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1228 if let Some(cond_str) = trial {
1229 if cond_str.len() <= context.config.single_line_if_else_max_width() {
1230 return Some((cond_str, 0));
1235 let cond_span = if let Some(cond) = self.cond {
1238 mk_sp(self.block.span.lo, self.block.span.lo)
1241 // for event in event
1242 let between_kwd_cond = mk_sp(
1243 context.codemap.span_after(self.span, self.keyword.trim()),
1246 |p| if self.matcher.is_empty() {
1249 context.codemap.span_before(self.span, self.matcher.trim())
1254 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1256 let after_cond_comment =
1257 extract_comment(mk_sp(cond_span.hi, self.block.span.lo), context, shape);
1259 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1261 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine ||
1269 let used_width = if pat_expr_string.contains('\n') {
1270 last_line_width(&pat_expr_string)
1272 // 2 = spaces after keyword and condition.
1273 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1281 between_kwd_cond_comment.as_ref().map_or(
1282 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1290 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1297 impl<'a> Rewrite for ControlFlow<'a> {
1298 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1299 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1302 String::from("\n") + &shape.indent.block_only().to_string(context.config);
1303 let (cond_str, used_width) = try_opt!(self.rewrite_cond(context, shape, &alt_block_sep));
1304 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1305 if used_width == 0 {
1306 return Some(cond_str);
1309 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1310 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1311 // we should avoid the single line case.
1312 let block_width = if self.else_block.is_some() || self.nested_if {
1317 let block_shape = Shape {
1321 let mut block_context = context.clone();
1322 block_context.is_if_else_block = self.else_block.is_some();
1323 let block_str = try_opt!(rewrite_block_with_visitor(
1330 let mut result = format!("{}{}", cond_str, block_str);
1332 if let Some(else_block) = self.else_block {
1333 let shape = Shape::indented(shape.indent, context.config);
1334 let mut last_in_chain = false;
1335 let rewrite = match else_block.node {
1336 // If the else expression is another if-else expression, prevent it
1337 // from being formatted on a single line.
1338 // Note how we're passing the original shape, as the
1339 // cost of "else" should not cascade.
1340 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1341 ControlFlow::new_if(
1345 next_else_block.as_ref().map(|e| &**e),
1348 mk_sp(else_block.span.lo, self.span.hi),
1349 ).rewrite(context, shape)
1351 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1352 ControlFlow::new_if(
1356 next_else_block.as_ref().map(|e| &**e),
1359 mk_sp(else_block.span.lo, self.span.hi),
1360 ).rewrite(context, shape)
1363 last_in_chain = true;
1364 // When rewriting a block, the width is only used for single line
1365 // blocks, passing 1 lets us avoid that.
1366 let else_shape = Shape {
1367 width: min(1, shape.width),
1370 format_expr(else_block, ExprType::Statement, context, else_shape)
1374 let between_kwd_else_block = mk_sp(
1378 .span_before(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1380 let between_kwd_else_block_comment =
1381 extract_comment(between_kwd_else_block, context, shape);
1383 let after_else = mk_sp(
1386 .span_after(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1389 let after_else_comment = extract_comment(after_else, context, shape);
1391 let between_sep = match context.config.control_brace_style() {
1392 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1395 ControlBraceStyle::AlwaysSameLine => " ",
1397 let after_sep = match context.config.control_brace_style() {
1398 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1405 between_kwd_else_block_comment
1407 .map_or(between_sep, |s| &**s),
1408 after_else_comment.as_ref().map_or(after_sep, |s| &**s)
1411 result.push_str(&try_opt!(rewrite));
1418 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
1420 Some(ident) => format!("{}: ", ident.node),
1421 None => "".to_owned(),
1425 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1426 let comment_str = context.snippet(span);
1427 if contains_comment(&comment_str) {
1428 let comment = try_opt!(rewrite_comment(
1435 "\n{indent}{}\n{indent}",
1437 indent = shape.indent.to_string(context.config)
1444 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1445 let snippet = codemap.span_to_snippet(block.span).unwrap();
1446 contains_comment(&snippet)
1449 // Checks that a block contains no statements, an expression and no comments.
1450 // FIXME: incorrectly returns false when comment is contained completely within
1452 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1453 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) &&
1454 !block_contains_comment(block, codemap))
1457 /// Checks whether a block contains at most one statement or expression, and no comments.
1458 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1459 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1462 /// Checks whether a block contains no statements, expressions, or comments.
1463 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1464 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1467 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1469 ast::StmtKind::Expr(..) => true,
1474 fn is_unsafe_block(block: &ast::Block) -> bool {
1475 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1482 // inter-match-arm-comment-rules:
1483 // - all comments following a match arm before the start of the next arm
1484 // are about the second arm
1485 fn rewrite_match_arm_comment(
1486 context: &RewriteContext,
1489 arm_indent_str: &str,
1490 ) -> Option<String> {
1491 // The leading "," is not part of the arm-comment
1492 let missed_str = match missed_str.find_uncommented(",") {
1493 Some(n) => &missed_str[n + 1..],
1494 None => &missed_str[..],
1497 let mut result = String::new();
1498 // any text not preceeded by a newline is pushed unmodified to the block
1499 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
1500 result.push_str(&missed_str[..first_brk]);
1501 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
1503 let first = missed_str
1504 .find(|c: char| !c.is_whitespace())
1505 .unwrap_or(missed_str.len());
1506 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
1507 // Excessive vertical whitespace before comment should be preserved
1508 // FIXME handle vertical whitespace better
1511 let missed_str = missed_str[first..].trim();
1512 if !missed_str.is_empty() {
1513 let comment = try_opt!(rewrite_comment(&missed_str, false, shape, context.config));
1515 result.push_str(arm_indent_str);
1516 result.push_str(&comment);
1523 context: &RewriteContext,
1528 ) -> Option<String> {
1529 if arms.is_empty() {
1533 // 6 = `match `, 2 = ` {`
1534 let cond_shape = match context.config.control_style() {
1535 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
1536 Style::Rfc => try_opt!(shape.offset_left(6).and_then(|s| s.sub_width(2))),
1538 let cond_str = try_opt!(cond.rewrite(context, cond_shape));
1539 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1540 let block_sep = match context.config.control_brace_style() {
1541 ControlBraceStyle::AlwaysNextLine => &alt_block_sep,
1542 _ if last_line_extendable(&cond_str) => " ",
1543 _ if cond_str.contains('\n') => &alt_block_sep,
1548 "match {}{}{{{}\n{}}}",
1551 try_opt!(rewrite_match_arms(context, arms, shape, span, cond.span.hi)),
1552 shape.indent.to_string(context.config),
1556 fn arm_comma(config: &Config, body: &ast::Expr) -> &'static str {
1557 if config.match_block_trailing_comma() {
1559 } else if let ast::ExprKind::Block(ref block) = body.node {
1560 if let ast::BlockCheckMode::Default = block.rules {
1570 fn rewrite_match_arms(
1571 context: &RewriteContext,
1575 cond_end_pos: BytePos,
1576 ) -> Option<String> {
1577 let mut result = String::new();
1579 let arm_shape = if context.config.indent_match_arms() {
1580 shape.block_indent(context.config.tab_spaces())
1582 shape.block_indent(0)
1583 }.with_max_width(context.config);
1584 let arm_indent_str = arm_shape.indent.to_string(context.config);
1586 let open_brace_pos = context
1588 .span_after(mk_sp(cond_end_pos, arms[0].span().lo), "{");
1590 let arm_num = arms.len();
1591 for (i, arm) in arms.iter().enumerate() {
1592 // Make sure we get the stuff between arms.
1593 let missed_str = if i == 0 {
1594 context.snippet(mk_sp(open_brace_pos, arm.span().lo))
1596 context.snippet(mk_sp(arms[i - 1].span().hi, arm.span().lo))
1598 let comment = try_opt!(rewrite_match_arm_comment(
1604 result.push_str(&comment);
1606 result.push_str(&arm_indent_str);
1608 let arm_str = rewrite_match_arm(context, arm, arm_shape);
1609 if let Some(ref arm_str) = arm_str {
1610 // Trim the trailing comma if necessary.
1611 if i == arm_num - 1 && context.config.trailing_comma() == SeparatorTactic::Never &&
1612 arm_str.ends_with(',')
1614 result.push_str(&arm_str[0..arm_str.len() - 1])
1616 result.push_str(arm_str)
1619 // We couldn't format the arm, just reproduce the source.
1620 let snippet = context.snippet(arm.span());
1621 result.push_str(&snippet);
1622 if context.config.trailing_comma() != SeparatorTactic::Never {
1623 result.push_str(arm_comma(context.config, &arm.body))
1627 // BytePos(1) = closing match brace.
1628 let last_span = mk_sp(arms[arms.len() - 1].span().hi, span.hi - BytePos(1));
1629 let last_comment = context.snippet(last_span);
1630 let comment = try_opt!(rewrite_match_arm_comment(
1636 result.push_str(&comment);
1641 fn rewrite_match_arm(context: &RewriteContext, arm: &ast::Arm, shape: Shape) -> Option<String> {
1642 let attr_str = if !arm.attrs.is_empty() {
1643 if contains_skip(&arm.attrs) {
1648 try_opt!(arm.attrs.rewrite(context, shape)),
1649 shape.indent.to_string(context.config)
1654 let pats_str = try_opt!(rewrite_match_pattern(context, &arm.pats, &arm.guard, shape));
1655 let pats_str = attr_str + &pats_str;
1656 rewrite_match_body(context, &arm.body, &pats_str, shape, arm.guard.is_some())
1659 fn rewrite_match_pattern(
1660 context: &RewriteContext,
1661 pats: &Vec<ptr::P<ast::Pat>>,
1662 guard: &Option<ptr::P<ast::Expr>>,
1664 ) -> Option<String> {
1667 let pat_shape = try_opt!(shape.sub_width(5));
1669 let pat_strs = try_opt!(
1671 .map(|p| p.rewrite(context, pat_shape))
1672 .collect::<Option<Vec<_>>>()
1675 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1676 let tactic = definitive_tactic(&items, ListTactic::HorizontalVertical, pat_shape.width);
1677 let fmt = ListFormatting {
1680 trailing_separator: SeparatorTactic::Never,
1682 ends_with_newline: false,
1683 preserve_newline: false,
1684 config: context.config,
1686 let pats_str = try_opt!(write_list(&items, &fmt));
1689 let guard_str = try_opt!(rewrite_guard(
1693 trimmed_last_line_width(&pats_str),
1696 Some(format!("{}{}", pats_str, guard_str))
1699 fn rewrite_match_body(
1700 context: &RewriteContext,
1701 body: &ptr::P<ast::Expr>,
1705 ) -> Option<String> {
1706 let (extend, body) = match body.node {
1707 ast::ExprKind::Block(ref block)
1708 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) =>
1710 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1711 (expr.can_be_overflowed(context, 1), &**expr)
1716 _ => (body.can_be_overflowed(context, 1), &**body),
1719 let comma = arm_comma(&context.config, body);
1720 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1721 let alt_block_sep = alt_block_sep.as_str();
1722 let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
1723 (true, is_empty_block(block, context.codemap))
1728 let combine_orig_body = |body_str: &str| {
1729 let block_sep = match context.config.control_brace_style() {
1730 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
1734 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
1737 let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
1738 let next_line_indent = if is_block {
1741 shape.indent.block_indent(context.config)
1743 let combine_next_line_body = |body_str: &str| {
1745 return Some(format!(
1748 next_line_indent.to_string(context.config),
1753 let indent_str = shape.indent.to_string(context.config);
1754 let nested_indent_str = next_line_indent.to_string(context.config);
1755 let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1756 let comma = if context.config.match_block_trailing_comma() {
1761 ("{", format!("\n{}}}{}", indent_str, comma))
1763 ("", String::from(","))
1766 let block_sep = match context.config.control_brace_style() {
1767 ControlBraceStyle::AlwaysNextLine => format!("{}{}\n", alt_block_sep, body_prefix),
1768 _ if body_prefix.is_empty() => "\n".to_owned(),
1769 _ if forbid_same_line => format!("{}{}\n", alt_block_sep, body_prefix),
1770 _ => format!(" {}\n", body_prefix),
1771 } + &nested_indent_str;
1782 // Let's try and get the arm body on the same line as the condition.
1784 let orig_body_shape = shape
1785 .offset_left(extra_offset(&pats_str, shape) + 4)
1786 .and_then(|shape| shape.sub_width(comma.len()));
1787 let orig_body = if let Some(body_shape) = orig_body_shape {
1788 let rewrite = nop_block_collapse(
1789 format_expr(body, ExprType::Statement, context, body_shape),
1795 if !forbid_same_line &&
1797 (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
1799 return combine_orig_body(body_str);
1806 let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
1808 // Try putting body on the next line and see if it looks better.
1809 let next_line_body_shape = Shape::indented(next_line_indent, context.config);
1810 let next_line_body = nop_block_collapse(
1811 format_expr(body, ExprType::Statement, context, next_line_body_shape),
1812 next_line_body_shape.width,
1814 match (orig_body, next_line_body) {
1815 (Some(ref orig_str), Some(ref next_line_str))
1816 if forbid_same_line || prefer_next_line(orig_str, next_line_str) =>
1818 combine_next_line_body(next_line_str)
1820 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
1821 combine_orig_body(orig_str)
1823 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
1824 combine_next_line_body(next_line_str)
1826 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
1827 (None, None) => None,
1828 (Some(ref orig_str), _) => combine_orig_body(orig_str),
1832 // The `if ...` guard on a match arm.
1834 context: &RewriteContext,
1835 guard: &Option<ptr::P<ast::Expr>>,
1837 // The amount of space used up on this line for the pattern in
1838 // the arm (excludes offset).
1839 pattern_width: usize,
1840 ) -> Option<String> {
1841 if let Some(ref guard) = *guard {
1842 // First try to fit the guard string on the same line as the pattern.
1843 // 4 = ` if `, 5 = ` => {`
1844 let cond_shape = shape
1845 .offset_left(pattern_width + 4)
1846 .and_then(|s| s.sub_width(5));
1847 if let Some(cond_shape) = cond_shape {
1848 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1849 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
1850 return Some(format!(" if {}", cond_str));
1855 // Not enough space to put the guard after the pattern, try a newline.
1856 // 3 = `if `, 5 = ` => {`
1857 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
1859 .and_then(|s| s.sub_width(5));
1860 if let Some(cond_shape) = cond_shape {
1861 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1862 return Some(format!(
1864 cond_shape.indent.to_string(context.config),
1876 fn rewrite_pat_expr(
1877 context: &RewriteContext,
1878 pat: Option<&ast::Pat>,
1881 // Connecting piece between pattern and expression,
1882 // *without* trailing space.
1886 ) -> Option<String> {
1887 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1888 if let Some(pat) = pat {
1889 let matcher = if matcher.is_empty() {
1892 format!("{} ", matcher)
1895 try_opt!(try_opt!(shape.offset_left(matcher.len())).sub_width(connector.len()));
1896 let pat_string = try_opt!(pat.rewrite(context, pat_shape));
1897 let result = format!("{}{}{}", matcher, pat_string, connector);
1898 return rewrite_assign_rhs(context, result, expr, shape);
1901 let expr_rw = expr.rewrite(context, shape);
1902 // The expression may (partially) fit on the current line.
1903 // We do not allow splitting between `if` and condition.
1904 if keyword == "if" || expr_rw.is_some() {
1908 // The expression won't fit on the current line, jump to next.
1909 let nested_shape = shape
1910 .block_indent(context.config.tab_spaces())
1911 .with_max_width(context.config);
1912 let nested_indent_str = nested_shape.indent.to_string(context.config);
1913 expr.rewrite(context, nested_shape)
1914 .map(|expr_rw| format!("\n{}{}", nested_indent_str, expr_rw))
1917 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1918 let string_lit = context.snippet(span);
1920 if !context.config.format_strings() && !context.config.force_format_strings() {
1925 .all(|line| line.ends_with('\\'))
1927 let new_indent = shape.visual_indent(1).indent;
1928 return Some(String::from(
1932 new_indent.to_string(context.config) + line.trim_left()
1934 .collect::<Vec<_>>()
1939 return Some(string_lit);
1943 if !context.config.force_format_strings() &&
1944 !string_requires_rewrite(context, span, &string_lit, shape)
1946 return Some(string_lit);
1949 let fmt = StringFormat {
1956 config: context.config,
1959 // Remove the quote characters.
1960 let str_lit = &string_lit[1..string_lit.len() - 1];
1962 rewrite_string(str_lit, &fmt)
1965 fn string_requires_rewrite(
1966 context: &RewriteContext,
1971 if context.codemap.lookup_char_pos(span.lo).col.0 != shape.indent.width() {
1975 for (i, line) in string.lines().enumerate() {
1977 if line.len() > shape.width {
1981 if line.len() > shape.width + shape.indent.width() {
1990 pub fn rewrite_call_with_binary_search<R>(
1991 context: &RewriteContext,
1993 args: &[&ast::Expr],
2000 let force_trailing_comma = if context.inside_macro {
2001 span_ends_with_comma(context, span)
2005 let closure = |callee_max_width| {
2006 // FIXME using byte lens instead of char lens (and probably all over the
2008 let callee_shape = Shape {
2009 width: callee_max_width,
2012 let callee_str = callee
2013 .rewrite(context, callee_shape)
2014 .ok_or(Ordering::Greater)?;
2022 context.config.fn_call_width(),
2023 force_trailing_comma,
2027 binary_search(1, shape.width, closure)
2030 pub fn rewrite_call(
2031 context: &RewriteContext,
2033 args: &[ptr::P<ast::Expr>],
2036 ) -> Option<String> {
2037 let force_trailing_comma = if context.inside_macro {
2038 span_ends_with_comma(context, span)
2045 &args.iter().map(|x| &**x).collect::<Vec<_>>(),
2048 context.config.fn_call_width(),
2049 force_trailing_comma,
2053 pub fn rewrite_call_inner<'a, T>(
2054 context: &RewriteContext,
2059 args_max_width: usize,
2060 force_trailing_comma: bool,
2061 ) -> Result<String, Ordering>
2063 T: Rewrite + Spanned + ToExpr + 'a,
2065 // 2 = `( `, 1 = `(`
2066 let paren_overhead = if context.config.spaces_within_parens() {
2071 let used_width = extra_offset(&callee_str, shape);
2072 let one_line_width = shape
2074 .checked_sub(used_width + 2 * paren_overhead)
2075 .ok_or(Ordering::Greater)?;
2077 let nested_shape = shape_from_fn_call_style(
2080 used_width + 2 * paren_overhead,
2081 used_width + paren_overhead,
2082 ).ok_or(Ordering::Greater)?;
2084 let span_lo = context.codemap.span_after(span, "(");
2085 let args_span = mk_sp(span_lo, span.hi);
2087 let (extendable, list_str) = rewrite_call_args(
2094 force_trailing_comma,
2095 ).ok_or(Ordering::Less)?;
2097 if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
2098 let mut new_context = context.clone();
2099 new_context.use_block = true;
2100 return rewrite_call_inner(
2107 force_trailing_comma,
2111 let args_shape = shape
2112 .sub_width(last_line_width(&callee_str))
2113 .ok_or(Ordering::Less)?;
2117 wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2121 fn need_block_indent(s: &str, shape: Shape) -> bool {
2122 s.lines().skip(1).any(|s| {
2123 s.find(|c| !char::is_whitespace(c))
2124 .map_or(false, |w| w + 1 < shape.indent.width())
2128 fn rewrite_call_args<'a, T>(
2129 context: &RewriteContext,
2133 one_line_width: usize,
2134 args_max_width: usize,
2135 force_trailing_comma: bool,
2136 ) -> Option<(bool, String)>
2138 T: Rewrite + Spanned + ToExpr + 'a,
2140 let items = itemize_list(
2144 |item| item.span().lo,
2145 |item| item.span().hi,
2146 |item| item.rewrite(context, shape),
2150 let mut item_vec: Vec<_> = items.collect();
2152 // Try letting the last argument overflow to the next line with block
2153 // indentation. If its first line fits on one line with the other arguments,
2154 // we format the function arguments horizontally.
2155 let tactic = try_overflow_last_arg(
2164 let fmt = ListFormatting {
2167 trailing_separator: if force_trailing_comma {
2168 SeparatorTactic::Always
2169 } else if context.inside_macro || !context.use_block_indent() {
2170 SeparatorTactic::Never
2172 context.config.trailing_comma()
2175 ends_with_newline: context.use_block_indent() && tactic == DefinitiveListTactic::Vertical,
2176 preserve_newline: false,
2177 config: context.config,
2180 write_list(&item_vec, &fmt).map(|args_str| {
2181 (tactic != DefinitiveListTactic::Vertical, args_str)
2185 fn try_overflow_last_arg<'a, T>(
2186 context: &RewriteContext,
2187 item_vec: &mut Vec<ListItem>,
2190 one_line_width: usize,
2191 args_max_width: usize,
2192 ) -> DefinitiveListTactic
2194 T: Rewrite + Spanned + ToExpr + 'a,
2196 let overflow_last = can_be_overflowed(&context, args);
2198 // Replace the last item with its first line to see if it fits with
2200 let (orig_last, placeholder) = if overflow_last {
2201 let mut context = context.clone();
2202 if let Some(expr) = args[args.len() - 1].to_expr() {
2204 ast::ExprKind::MethodCall(..) => context.force_one_line_chain = true,
2208 last_arg_shape(&context, &item_vec, shape, args_max_width)
2209 .map_or((None, None), |arg_shape| {
2210 rewrite_last_arg_with_overflow(
2213 &mut item_vec[args.len() - 1],
2221 let tactic = definitive_tactic(
2223 ListTactic::LimitedHorizontalVertical(args_max_width),
2227 // Replace the stub with the full overflowing last argument if the rewrite
2228 // succeeded and its first line fits with the other arguments.
2229 match (overflow_last, tactic, placeholder) {
2230 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2231 item_vec[args.len() - 1].item = placeholder;
2234 item_vec[args.len() - 1].item = orig_last;
2243 context: &RewriteContext,
2244 items: &Vec<ListItem>,
2246 args_max_width: usize,
2247 ) -> Option<Shape> {
2248 let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
2249 acc + i.item.as_ref().map_or(0, |s| first_line_width(&s))
2251 let max_width = min(args_max_width, shape.width);
2252 let arg_indent = if context.use_block_indent() {
2253 shape.block().indent.block_unindent(context.config)
2255 shape.block().indent
2258 width: try_opt!(max_width.checked_sub(overhead)),
2264 // Rewriting closure which is placed at the end of the function call's arg.
2265 // Returns `None` if the reformatted closure 'looks bad'.
2266 fn rewrite_last_closure(
2267 context: &RewriteContext,
2270 ) -> Option<String> {
2271 if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
2272 let body = match body.node {
2273 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
2274 stmt_expr(&block.stmts[0]).unwrap_or(body)
2278 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
2286 // If the closure goes multi line before its body, do not overflow the closure.
2287 if prefix.contains('\n') {
2290 let body_shape = try_opt!(shape.offset_left(extra_offset));
2291 // When overflowing the closure which consists of a single control flow expression,
2292 // force to use block if its condition uses multi line.
2293 let is_multi_lined_cond = rewrite_cond(context, body, body_shape)
2294 .map(|cond| cond.contains('\n') || cond.len() > body_shape.width)
2296 if is_multi_lined_cond {
2297 return rewrite_closure_with_block(context, body_shape, &prefix, body);
2300 // Seems fine, just format the closure in usual manner.
2301 return expr.rewrite(context, shape);
2306 fn rewrite_last_arg_with_overflow<'a, T>(
2307 context: &RewriteContext,
2309 last_item: &mut ListItem,
2311 ) -> (Option<String>, Option<String>)
2313 T: Rewrite + Spanned + ToExpr + 'a,
2315 let last_arg = args[args.len() - 1];
2316 let rewrite = if let Some(expr) = last_arg.to_expr() {
2318 // When overflowing the closure which consists of a single control flow expression,
2319 // force to use block if its condition uses multi line.
2320 ast::ExprKind::Closure(..) => {
2321 // If the argument consists of multiple closures, we do not overflow
2322 // the last closure.
2323 if args.len() > 1 &&
2327 .filter_map(|arg| arg.to_expr())
2328 .any(|expr| match expr.node {
2329 ast::ExprKind::Closure(..) => true,
2334 rewrite_last_closure(context, expr, shape)
2337 _ => expr.rewrite(context, shape),
2340 last_arg.rewrite(context, shape)
2342 let orig_last = last_item.item.clone();
2344 if let Some(rewrite) = rewrite {
2345 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2346 last_item.item = rewrite_first_line;
2347 (orig_last, Some(rewrite))
2353 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2355 T: Rewrite + Spanned + ToExpr + 'a,
2358 .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2361 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2363 ast::ExprKind::Match(..) => {
2364 (context.use_block_indent() && args_len == 1) ||
2365 (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
2367 ast::ExprKind::If(..) |
2368 ast::ExprKind::IfLet(..) |
2369 ast::ExprKind::ForLoop(..) |
2370 ast::ExprKind::Loop(..) |
2371 ast::ExprKind::While(..) |
2372 ast::ExprKind::WhileLet(..) => {
2373 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2375 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
2376 context.use_block_indent() ||
2377 context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
2379 ast::ExprKind::Array(..) |
2380 ast::ExprKind::Call(..) |
2381 ast::ExprKind::Mac(..) |
2382 ast::ExprKind::MethodCall(..) |
2383 ast::ExprKind::Struct(..) |
2384 ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2385 ast::ExprKind::AddrOf(_, ref expr) |
2386 ast::ExprKind::Box(ref expr) |
2387 ast::ExprKind::Try(ref expr) |
2388 ast::ExprKind::Unary(_, ref expr) |
2389 ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2394 pub fn wrap_args_with_parens(
2395 context: &RewriteContext,
2397 is_extendable: bool,
2399 nested_shape: Shape,
2401 if !context.use_block_indent() ||
2402 (context.inside_macro && !args_str.contains('\n') &&
2403 args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2405 if context.config.spaces_within_parens() && args_str.len() > 0 {
2406 format!("( {} )", args_str)
2408 format!("({})", args_str)
2413 nested_shape.indent.to_string(context.config),
2415 shape.block().indent.to_string(context.config)
2420 fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2421 let snippet = context.snippet(span);
2423 .trim_right_matches(|c: char| c == ')' || c.is_whitespace())
2427 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2428 debug!("rewrite_paren, shape: {:?}", shape);
2429 let total_paren_overhead = paren_overhead(context);
2430 let paren_overhead = total_paren_overhead / 2;
2431 let sub_shape = try_opt!(
2433 .offset_left(paren_overhead)
2434 .and_then(|s| s.sub_width(paren_overhead))
2437 let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && s.len() > 0 {
2438 format!("( {} )", s)
2443 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2444 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2446 if subexpr_str.contains('\n') ||
2447 first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
2449 Some(paren_wrapper(&subexpr_str))
2458 context: &RewriteContext,
2460 ) -> Option<String> {
2461 let expr_str = try_opt!(expr.rewrite(context, shape));
2463 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
2469 let offset = last_line_width(&expr_str) + lbr.len();
2470 let rhs_overhead = shape.rhs_overhead(context.config);
2471 let index_shape = if expr_str.contains('\n') {
2472 Shape::legacy(context.config.max_width(), shape.indent)
2473 .offset_left(offset)
2474 .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
2476 shape.visual_indent(offset).sub_width(offset + rbr.len())
2478 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
2480 // Return if index fits in a single line.
2481 match orig_index_rw {
2482 Some(ref index_str) if !index_str.contains('\n') => {
2483 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2488 // Try putting index on the next line and see if it fits in a single line.
2489 let indent = shape.indent.block_indent(context.config);
2490 let index_shape = try_opt!(Shape::indented(indent, context.config).offset_left(lbr.len()));
2491 let index_shape = try_opt!(index_shape.sub_width(rbr.len() + rhs_overhead));
2492 let new_index_rw = index.rewrite(context, index_shape);
2493 match (orig_index_rw, new_index_rw) {
2494 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
2497 indent.to_string(&context.config),
2502 (None, Some(ref new_index_str)) => Some(format!(
2505 indent.to_string(&context.config),
2510 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2515 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2520 fields.iter().all(|field| !field.is_shorthand)
2523 fn rewrite_struct_lit<'a>(
2524 context: &RewriteContext,
2526 fields: &'a [ast::Field],
2527 base: Option<&'a ast::Expr>,
2530 ) -> Option<String> {
2531 debug!("rewrite_struct_lit: shape {:?}", shape);
2533 enum StructLitField<'a> {
2534 Regular(&'a ast::Field),
2535 Base(&'a ast::Expr),
2539 let path_shape = try_opt!(shape.sub_width(2));
2540 let path_str = try_opt!(rewrite_path(
2548 if fields.len() == 0 && base.is_none() {
2549 return Some(format!("{} {{}}", path_str));
2552 // Foo { a: Foo } - indent is +3, width is -5.
2553 let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
2555 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2556 let body_lo = context.codemap.span_after(span, "{");
2557 let fields_str = if struct_lit_can_be_aligned(fields, &base) &&
2558 context.config.struct_field_align_threshold() > 0
2560 try_opt!(rewrite_with_alignment(
2564 mk_sp(body_lo, span.hi),
2568 let field_iter = fields
2570 .map(StructLitField::Regular)
2571 .chain(base.into_iter().map(StructLitField::Base));
2573 let span_lo = |item: &StructLitField| match *item {
2574 StructLitField::Regular(field) => field.span().lo,
2575 StructLitField::Base(expr) => {
2576 let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
2577 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
2578 let pos = snippet.find_uncommented("..").unwrap();
2579 last_field_hi + BytePos(pos as u32)
2582 let span_hi = |item: &StructLitField| match *item {
2583 StructLitField::Regular(field) => field.span().hi,
2584 StructLitField::Base(expr) => expr.span.hi,
2586 let rewrite = |item: &StructLitField| match *item {
2587 StructLitField::Regular(field) => {
2588 // The 1 taken from the v_budget is for the comma.
2589 rewrite_field(context, field, try_opt!(v_shape.sub_width(1)), 0)
2591 StructLitField::Base(expr) => {
2593 expr.rewrite(context, try_opt!(v_shape.offset_left(2)))
2594 .map(|s| format!("..{}", s))
2598 let items = itemize_list(
2608 let item_vec = items.collect::<Vec<_>>();
2610 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2611 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2612 let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2614 try_opt!(write_list(&item_vec, &fmt))
2617 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2618 Some(format!("{} {{{}}}", path_str, fields_str))
2620 // FIXME if context.config.struct_lit_style() == Visual, but we run out
2621 // of space, we should fall back to BlockIndent.
2624 pub fn wrap_struct_field(
2625 context: &RewriteContext,
2628 nested_shape: Shape,
2629 one_line_width: usize,
2631 if context.config.struct_lit_style() == IndentStyle::Block &&
2632 (fields_str.contains('\n') ||
2633 context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti ||
2634 fields_str.len() > one_line_width)
2638 nested_shape.indent.to_string(context.config),
2640 shape.indent.to_string(context.config)
2643 // One liner or visual indent.
2644 format!(" {} ", fields_str)
2648 pub fn struct_lit_field_separator(config: &Config) -> &str {
2650 config.space_before_struct_lit_field_colon(),
2651 config.space_after_struct_lit_field_colon(),
2655 pub fn rewrite_field(
2656 context: &RewriteContext,
2659 prefix_max_width: usize,
2660 ) -> Option<String> {
2661 if contains_skip(&field.attrs) {
2663 context.snippet(field.span()),
2664 context.config.max_width(),
2668 let name = &field.ident.node.to_string();
2669 if field.is_shorthand {
2670 Some(name.to_string())
2672 let mut separator = String::from(struct_lit_field_separator(context.config));
2673 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2674 separator.push(' ');
2676 let overhead = name.len() + separator.len();
2677 let expr_shape = try_opt!(shape.offset_left(overhead));
2678 let expr = field.expr.rewrite(context, expr_shape);
2680 let mut attrs_str = try_opt!(field.attrs.rewrite(context, shape));
2681 if !attrs_str.is_empty() {
2682 attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2686 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2688 let expr_offset = shape.indent.block_indent(context.config);
2691 .rewrite(context, Shape::indented(expr_offset, context.config));
2697 expr_offset.to_string(&context.config),
2706 fn shape_from_fn_call_style(
2707 context: &RewriteContext,
2711 ) -> Option<Shape> {
2712 if context.use_block_indent() {
2716 .block_indent(context.config.tab_spaces())
2717 .with_max_width(context.config)
2720 shape.visual_indent(offset).sub_width(overhead)
2724 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2725 context: &RewriteContext,
2731 T: Rewrite + Spanned + ToExpr + 'a,
2733 let mut items = items.iter();
2734 // In case of length 1, need a trailing comma
2735 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2736 if items.len() == 1 {
2738 let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
2739 return items.next().unwrap().rewrite(context, nested_shape).map(
2740 |s| if context.config.spaces_within_parens() {
2741 format!("( {}, )", s)
2748 let list_lo = context.codemap.span_after(span, "(");
2749 let nested_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
2750 let items = itemize_list(
2754 |item| item.span().lo,
2755 |item| item.span().hi,
2756 |item| item.rewrite(context, nested_shape),
2758 span.hi - BytePos(1),
2760 let item_vec: Vec<_> = items.collect();
2761 let tactic = definitive_tactic(
2763 ListTactic::HorizontalVertical,
2766 let fmt = ListFormatting {
2769 trailing_separator: SeparatorTactic::Never,
2771 ends_with_newline: false,
2772 preserve_newline: false,
2773 config: context.config,
2775 let list_str = try_opt!(write_list(&item_vec, &fmt));
2777 if context.config.spaces_within_parens() && list_str.len() > 0 {
2778 Some(format!("( {} )", list_str))
2780 Some(format!("({})", list_str))
2784 pub fn rewrite_tuple<'a, T>(
2785 context: &RewriteContext,
2791 T: Rewrite + Spanned + ToExpr + 'a,
2793 debug!("rewrite_tuple {:?}", shape);
2794 if context.use_block_indent() {
2795 // We use the same rule as funcation call for rewriting tuple.
2796 let force_trailing_comma = if context.inside_macro {
2797 span_ends_with_comma(context, span)
2807 context.config.fn_call_width(),
2808 force_trailing_comma,
2811 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2815 pub fn rewrite_unary_prefix<R: Rewrite>(
2816 context: &RewriteContext,
2820 ) -> Option<String> {
2822 .rewrite(context, try_opt!(shape.offset_left(prefix.len())))
2823 .map(|r| format!("{}{}", prefix, r))
2826 // FIXME: this is probably not correct for multi-line Rewrites. we should
2827 // subtract suffix.len() from the last line budget, not the first!
2828 pub fn rewrite_unary_suffix<R: Rewrite>(
2829 context: &RewriteContext,
2833 ) -> Option<String> {
2835 .rewrite(context, try_opt!(shape.sub_width(suffix.len())))
2842 fn rewrite_unary_op(
2843 context: &RewriteContext,
2847 ) -> Option<String> {
2848 // For some reason, an UnOp is not spanned like BinOp!
2849 let operator_str = match *op {
2850 ast::UnOp::Deref => "*",
2851 ast::UnOp::Not => "!",
2852 ast::UnOp::Neg => "-",
2854 rewrite_unary_prefix(context, operator_str, expr, shape)
2857 fn rewrite_assignment(
2858 context: &RewriteContext,
2861 op: Option<&ast::BinOp>,
2863 ) -> Option<String> {
2864 let operator_str = match op {
2865 Some(op) => context.snippet(op.span),
2866 None => "=".to_owned(),
2869 // 1 = space between lhs and operator.
2870 let lhs_shape = try_opt!(shape.sub_width(operator_str.len() + 1));
2871 let lhs_str = format!(
2873 try_opt!(lhs.rewrite(context, lhs_shape)),
2877 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2880 // The left hand side must contain everything up to, and including, the
2881 // assignment operator.
2882 pub fn rewrite_assign_rhs<S: Into<String>>(
2883 context: &RewriteContext,
2887 ) -> Option<String> {
2888 let lhs = lhs.into();
2889 let last_line_width = last_line_width(&lhs) - if lhs.contains('\n') {
2890 shape.indent.width()
2894 // 1 = space between operator and rhs.
2895 let orig_shape = try_opt!(shape.offset_left(last_line_width + 1));
2896 let rhs = try_opt!(choose_rhs(
2900 ex.rewrite(context, orig_shape)
2906 context: &RewriteContext,
2909 orig_rhs: Option<String>,
2910 ) -> Option<String> {
2912 Some(ref new_str) if !new_str.contains('\n') => Some(format!(" {}", new_str)),
2914 // Expression did not fit on the same line as the identifier.
2915 // Try splitting the line and see if that works better.
2916 let new_shape = try_opt!(
2918 shape.block().indent.block_indent(context.config),
2920 ).sub_width(shape.rhs_overhead(context.config))
2922 let new_rhs = expr.rewrite(context, new_shape);
2923 let new_indent_str = &new_shape.indent.to_string(context.config);
2925 match (orig_rhs, new_rhs) {
2926 (Some(ref orig_rhs), Some(ref new_rhs)) if prefer_next_line(orig_rhs, new_rhs) => {
2927 Some(format!("\n{}{}", new_indent_str, new_rhs))
2929 (None, Some(ref new_rhs)) => Some(format!("\n{}{}", new_indent_str, new_rhs)),
2930 (None, None) => None,
2931 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2937 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {
2939 fn count_line_breaks(src: &str) -> usize {
2940 src.chars().filter(|&x| x == '\n').count()
2943 !next_line_rhs.contains('\n') ||
2944 count_line_breaks(orig_rhs) > count_line_breaks(next_line_rhs) + 1
2947 fn rewrite_expr_addrof(
2948 context: &RewriteContext,
2949 mutability: ast::Mutability,
2952 ) -> Option<String> {
2953 let operator_str = match mutability {
2954 ast::Mutability::Immutable => "&",
2955 ast::Mutability::Mutable => "&mut ",
2957 rewrite_unary_prefix(context, operator_str, expr, shape)
2961 fn to_expr(&self) -> Option<&ast::Expr>;
2962 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2965 impl ToExpr for ast::Expr {
2966 fn to_expr(&self) -> Option<&ast::Expr> {
2970 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2971 can_be_overflowed_expr(context, self, len)
2975 impl ToExpr for ast::Ty {
2976 fn to_expr(&self) -> Option<&ast::Expr> {
2980 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2981 can_be_overflowed_type(context, self, len)
2985 impl<'a> ToExpr for TuplePatField<'a> {
2986 fn to_expr(&self) -> Option<&ast::Expr> {
2990 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2991 can_be_overflowed_pat(context, self, len)
2995 impl<'a> ToExpr for ast::StructField {
2996 fn to_expr(&self) -> Option<&ast::Expr> {
3000 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {