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::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, Separator, 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 if contains_skip(&*expr.attrs) {
115 return Some(context.snippet(expr.span()));
117 let expr_rw = match expr.node {
118 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
119 expr_vec.iter().map(|e| &**e),
120 mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi),
125 ast::ExprKind::Lit(ref l) => match l.node {
126 ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
127 rewrite_string_lit(context, l.span, shape)
130 context.snippet(expr.span),
131 context.config.max_width(),
135 ast::ExprKind::Call(ref callee, ref args) => {
136 let inner_span = mk_sp(callee.span.hi, expr.span.hi);
137 rewrite_call_with_binary_search(
140 &args.iter().map(|x| &**x).collect::<Vec<_>>()[..],
145 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
146 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
147 // FIXME: format comments between operands and operator
152 &format!(" {} ", context.snippet(op.span)),
158 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
159 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
163 base.as_ref().map(|e| &**e),
167 ast::ExprKind::Tup(ref items) => rewrite_tuple(
169 &items.iter().map(|x| &**x).collect::<Vec<_>>()[..],
173 ast::ExprKind::If(..) |
174 ast::ExprKind::IfLet(..) |
175 ast::ExprKind::ForLoop(..) |
176 ast::ExprKind::Loop(..) |
177 ast::ExprKind::While(..) |
178 ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
179 .and_then(|control_flow| control_flow.rewrite(context, shape)),
180 ast::ExprKind::Block(ref block) => {
182 ExprType::Statement => {
183 if is_unsafe_block(block) {
184 block.rewrite(context, shape)
186 // Rewrite block without trying to put it in a single line.
187 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
190 let prefix = try_opt!(block_prefix(context, block, shape));
191 rewrite_block_with_visitor(context, &prefix, block, shape)
194 ExprType::SubExpression => block.rewrite(context, shape),
197 ast::ExprKind::Match(ref cond, ref arms) => {
198 rewrite_match(context, cond, arms, shape, expr.span)
200 ast::ExprKind::Path(ref qself, ref path) => {
201 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
203 ast::ExprKind::Assign(ref lhs, ref rhs) => {
204 rewrite_assignment(context, lhs, rhs, None, shape)
206 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
207 rewrite_assignment(context, lhs, rhs, Some(op), shape)
209 ast::ExprKind::Continue(ref opt_ident) => {
210 let id_str = match *opt_ident {
211 Some(ident) => format!(" {}", ident.node),
212 None => String::new(),
215 format!("continue{}", id_str),
216 context.config.max_width(),
220 ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
221 let id_str = match *opt_ident {
222 Some(ident) => format!(" {}", ident.node),
223 None => String::new(),
226 if let Some(ref expr) = *opt_expr {
227 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
230 format!("break{}", id_str),
231 context.config.max_width(),
236 ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
237 rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
239 ast::ExprKind::Try(..) |
240 ast::ExprKind::Field(..) |
241 ast::ExprKind::TupField(..) |
242 ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
243 ast::ExprKind::Mac(ref mac) => {
244 // Failure to rewrite a marco should not imply failure to
245 // rewrite the expression.
246 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
248 context.snippet(expr.span),
249 context.config.max_width(),
254 ast::ExprKind::Ret(None) => {
255 wrap_str("return".to_owned(), context.config.max_width(), shape)
257 ast::ExprKind::Ret(Some(ref expr)) => {
258 rewrite_unary_prefix(context, "return ", &**expr, shape)
260 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
261 ast::ExprKind::AddrOf(mutability, ref expr) => {
262 rewrite_expr_addrof(context, mutability, expr, shape)
264 ast::ExprKind::Cast(ref expr, ref ty) => {
265 rewrite_pair(&**expr, &**ty, "", " as ", "", context, shape)
267 ast::ExprKind::Type(ref expr, ref ty) => {
268 rewrite_pair(&**expr, &**ty, "", ": ", "", context, shape)
270 ast::ExprKind::Index(ref expr, ref index) => {
271 rewrite_index(&**expr, &**index, context, shape)
273 ast::ExprKind::Repeat(ref expr, ref repeats) => {
274 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
279 rewrite_pair(&**expr, &**repeats, lbr, "; ", rbr, context, shape)
281 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
282 let delim = match limits {
283 ast::RangeLimits::HalfOpen => "..",
284 ast::RangeLimits::Closed => "...",
287 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
289 ast::ExprKind::Lit(ref lit) => match lit.node {
290 ast::LitKind::FloatUnsuffixed(..) => {
291 context.snippet(lit.span).ends_with('.')
299 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
300 (Some(ref lhs), Some(ref rhs)) => {
301 let sp_delim = if context.config.spaces_around_ranges() {
302 format!(" {} ", delim)
303 } else if needs_space_before_range(context, lhs) {
304 format!(" {}", delim)
308 rewrite_pair(&**lhs, &**rhs, "", &sp_delim, "", context, shape)
310 (None, Some(ref rhs)) => {
311 let sp_delim = if context.config.spaces_around_ranges() {
312 format!("{} ", delim)
316 rewrite_unary_prefix(context, &sp_delim, &**rhs, shape)
318 (Some(ref lhs), None) => {
319 let sp_delim = if context.config.spaces_around_ranges() {
320 format!(" {}", delim)
324 rewrite_unary_suffix(context, &sp_delim, &**lhs, shape)
326 (None, None) => wrap_str(delim.into(), context.config.max_width(), shape),
329 // We do not format these expressions yet, but they should still
330 // satisfy our width restrictions.
331 ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => wrap_str(
332 context.snippet(expr.span),
333 context.config.max_width(),
336 ast::ExprKind::Catch(ref block) => {
337 if let rewrite @ Some(_) = rewrite_single_line_block(context, "do catch ", block, shape)
342 let budget = shape.width.checked_sub(9).unwrap_or(0);
346 try_opt!(block.rewrite(&context, Shape::legacy(budget, shape.indent)))
352 .and_then(|expr_str| {
353 recover_comment_removed(expr_str, expr.span, context, shape)
355 .and_then(|expr_str| {
356 combine_attr_and_expr(context, shape, expr, &expr_str)
360 pub fn rewrite_pair<LHS, RHS>(
366 context: &RewriteContext,
373 let sep = if infix.ends_with(' ') { " " } else { "" };
374 let infix = infix.trim_right();
375 let lhs_overhead = shape.used_width() + prefix.len() + infix.len();
376 let lhs_shape = Shape {
377 width: try_opt!(context.config.max_width().checked_sub(lhs_overhead)),
380 let lhs_result = try_opt!(
381 lhs.rewrite(context, lhs_shape)
382 .map(|lhs_str| format!("{}{}{}", prefix, lhs_str, infix))
385 // Try to the both lhs and rhs on the same line.
386 let rhs_orig_result = shape
387 .offset_left(last_line_width(&lhs_result) + suffix.len() + sep.len())
388 .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
389 if let Some(ref rhs_result) = rhs_orig_result {
390 // If the rhs looks like block expression, we allow it to stay on the same line
391 // with the lhs even if it is multi-lined.
392 let allow_same_line = rhs_result
395 .map(|first_line| first_line.ends_with('{'))
397 if !rhs_result.contains('\n') || allow_same_line {
398 return Some(format!("{}{}{}{}", lhs_result, sep, rhs_result, suffix));
402 // We have to use multiple lines.
403 // Re-evaluate the rhs because we have more space now:
404 let rhs_shape = match context.config.control_style() {
406 try_opt!(shape.sub_width(suffix.len() + prefix.len())).visual_indent(prefix.len())
409 // Try to calculate the initial constraint on the right hand side.
410 let rhs_overhead = shape.rhs_overhead(context.config);
412 Shape::indented(shape.indent.block_indent(context.config), context.config)
413 .sub_width(rhs_overhead)
417 let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape));
421 rhs_shape.indent.to_string(context.config),
427 pub fn rewrite_array<'a, I>(
430 context: &RewriteContext,
432 trailing_comma: bool,
435 I: Iterator<Item = &'a ast::Expr>,
437 let bracket_size = if context.config.spaces_within_square_brackets() {
443 let mut nested_shape = match context.config.array_layout() {
444 IndentStyle::Block => try_opt!(
447 .block_indent(context.config.tab_spaces())
448 .with_max_width(context.config)
451 IndentStyle::Visual => try_opt!(
453 .visual_indent(bracket_size)
454 .sub_width(bracket_size * 2)
458 let items = itemize_list(
464 |item| item.rewrite(context, nested_shape),
467 ).collect::<Vec<_>>();
469 if items.is_empty() {
470 if context.config.spaces_within_square_brackets() {
471 return Some("[ ]".to_string());
473 return Some("[]".to_string());
477 let has_long_item = items
479 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
481 let mut tactic = match context.config.array_layout() {
482 IndentStyle::Block => {
483 // FIXME wrong shape in one-line case
484 match shape.width.checked_sub(2 * bracket_size) {
487 ListTactic::LimitedHorizontalVertical(context.config.array_width());
488 definitive_tactic(&items, tactic, Separator::Comma, width)
490 None => DefinitiveListTactic::Vertical,
493 IndentStyle::Visual => if has_long_item || items.iter().any(ListItem::is_multiline) {
496 ListTactic::LimitedHorizontalVertical(context.config.array_width()),
501 DefinitiveListTactic::Mixed
504 let mut ends_with_newline = tactic.ends_with_newline(context.config.array_layout());
505 if context.config.array_horizontal_layout_threshold() > 0 &&
506 items.len() > context.config.array_horizontal_layout_threshold()
508 tactic = DefinitiveListTactic::Mixed;
509 ends_with_newline = false;
510 if context.config.array_layout() == IndentStyle::Block {
511 nested_shape = try_opt!(
513 .visual_indent(bracket_size)
514 .sub_width(bracket_size * 2)
519 let fmt = ListFormatting {
522 trailing_separator: if trailing_comma {
523 SeparatorTactic::Always
524 } else if context.inside_macro || context.config.array_layout() == IndentStyle::Visual {
525 SeparatorTactic::Never
527 SeparatorTactic::Vertical
530 ends_with_newline: ends_with_newline,
531 preserve_newline: false,
532 config: context.config,
534 let list_str = try_opt!(write_list(&items, &fmt));
536 let result = if context.config.array_layout() == IndentStyle::Visual ||
537 tactic != DefinitiveListTactic::Vertical
539 if context.config.spaces_within_square_brackets() && list_str.len() > 0 {
540 format!("[ {} ]", list_str)
542 format!("[{}]", list_str)
547 nested_shape.indent.to_string(context.config),
549 shape.block().indent.to_string(context.config)
556 // Return type is (prefix, extra_offset)
557 fn rewrite_closure_fn_decl(
558 capture: ast::CaptureBy,
559 fn_decl: &ast::FnDecl,
562 context: &RewriteContext,
564 ) -> Option<(String, usize)> {
565 let mover = if capture == ast::CaptureBy::Value {
570 // 4 = "|| {".len(), which is overconservative when the closure consists of
571 // a single expression.
572 let nested_shape = try_opt!(try_opt!(shape.shrink_left(mover.len())).sub_width(4));
575 let argument_offset = nested_shape.indent + 1;
576 let arg_shape = try_opt!(nested_shape.offset_left(1)).visual_indent(0);
577 let ret_str = try_opt!(fn_decl.output.rewrite(context, arg_shape));
579 let arg_items = itemize_list(
581 fn_decl.inputs.iter(),
583 |arg| span_lo_for_arg(arg),
584 |arg| span_hi_for_arg(context, arg),
585 |arg| arg.rewrite(context, arg_shape),
586 context.codemap.span_after(span, "|"),
589 let item_vec = arg_items.collect::<Vec<_>>();
590 // 1 = space between arguments and return type.
591 let horizontal_budget = nested_shape
593 .checked_sub(ret_str.len() + 1)
595 let tactic = definitive_tactic(
597 ListTactic::HorizontalVertical,
601 let arg_shape = match tactic {
602 DefinitiveListTactic::Horizontal => try_opt!(arg_shape.sub_width(ret_str.len() + 1)),
606 let fmt = ListFormatting {
609 trailing_separator: SeparatorTactic::Never,
611 ends_with_newline: false,
612 preserve_newline: true,
613 config: context.config,
615 let list_str = try_opt!(write_list(&item_vec, &fmt));
616 let mut prefix = format!("{}|{}|", mover, list_str);
617 // 1 = space between `|...|` and body.
618 let extra_offset = extra_offset(&prefix, shape) + 1;
620 if !ret_str.is_empty() {
621 if prefix.contains('\n') {
623 prefix.push_str(&argument_offset.to_string(context.config));
627 prefix.push_str(&ret_str);
630 Some((prefix, extra_offset))
633 // This functions is pretty messy because of the rules around closures and blocks:
634 // FIXME - the below is probably no longer true in full.
635 // * if there is a return type, then there must be braces,
636 // * given a closure with braces, whether that is parsed to give an inner block
637 // or not depends on if there is a return type and if there are statements
639 // * if the first expression in the body ends with a block (i.e., is a
640 // statement without needing a semi-colon), then adding or removing braces
641 // can change whether it is treated as an expression or statement.
643 capture: ast::CaptureBy,
644 fn_decl: &ast::FnDecl,
647 context: &RewriteContext,
649 ) -> Option<String> {
650 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
658 // 1 = space between `|...|` and body.
659 let body_shape = try_opt!(shape.offset_left(extra_offset));
661 if let ast::ExprKind::Block(ref block) = body.node {
662 // The body of the closure is an empty block.
663 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
664 return Some(format!("{} {{}}", prefix));
667 // Figure out if the block is necessary.
668 let needs_block = block.rules != ast::BlockCheckMode::Default || block.stmts.len() > 1 ||
669 context.inside_macro ||
670 block_contains_comment(block, context.codemap) ||
671 prefix.contains('\n');
673 let no_return_type = if let ast::FunctionRetTy::Default(_) = fn_decl.output {
678 if no_return_type && !needs_block {
679 // lock.stmts.len() == 1
680 if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
681 if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
688 // We need braces, but we might still prefer a one-liner.
689 let stmt = &block.stmts[0];
690 // 4 = braces and spaces.
691 if let Some(body_shape) = body_shape.sub_width(4) {
692 // Checks if rewrite succeeded and fits on a single line.
693 if let Some(rewrite) = and_one_line(stmt.rewrite(context, body_shape)) {
694 return Some(format!("{} {{ {} }}", prefix, rewrite));
699 // Either we require a block, or tried without and failed.
700 rewrite_closure_block(&block, &prefix, context, body_shape)
702 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
703 // The closure originally had a non-block expression, but we can't fit on
704 // one line, so we'll insert a block.
705 rewrite_closure_with_block(context, body_shape, &prefix, body)
710 // Rewrite closure with a single expression wrapping its body with block.
711 fn rewrite_closure_with_block(
712 context: &RewriteContext,
716 ) -> Option<String> {
717 let block = ast::Block {
720 id: ast::NodeId::new(0),
721 node: ast::StmtKind::Expr(ptr::P(body.clone())),
725 id: ast::NodeId::new(0),
726 rules: ast::BlockCheckMode::Default,
729 rewrite_closure_block(&block, prefix, context, shape)
732 // Rewrite closure with a single expression without wrapping its body with block.
733 fn rewrite_closure_expr(
736 context: &RewriteContext,
738 ) -> Option<String> {
739 let mut rewrite = expr.rewrite(context, shape);
740 if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
741 rewrite = and_one_line(rewrite);
743 rewrite.map(|rw| format!("{} {}", prefix, rw))
746 // Rewrite closure whose body is block.
747 fn rewrite_closure_block(
750 context: &RewriteContext,
752 ) -> Option<String> {
753 // Start with visual indent, then fall back to block indent if the
755 let block_threshold = context.config.closure_block_indent_threshold();
756 if block_threshold >= 0 {
757 if let Some(block_str) = block.rewrite(&context, shape) {
758 if block_str.matches('\n').count() <= block_threshold as usize &&
759 !need_block_indent(&block_str, shape)
761 if let Some(block_str) = block_str.rewrite(context, shape) {
762 return Some(format!("{} {}", prefix, block_str));
768 // The body of the closure is big enough to be block indented, that
769 // means we must re-format.
770 let block_shape = shape.block();
771 let block_str = try_opt!(block.rewrite(&context, block_shape));
772 Some(format!("{} {}", prefix, block_str))
775 fn and_one_line(x: Option<String>) -> Option<String> {
776 x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
779 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
780 debug!("nop_block_collapse {:?} {}", block_str, budget);
781 block_str.map(|block_str| {
782 if block_str.starts_with('{') && budget >= 2 &&
783 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
792 fn rewrite_empty_block(
793 context: &RewriteContext,
796 ) -> Option<String> {
797 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
799 return Some("{}".to_owned());
802 // If a block contains only a single-line comment, then leave it on one line.
803 let user_str = context.snippet(block.span);
804 let user_str = user_str.trim();
805 if user_str.starts_with('{') && user_str.ends_with('}') {
806 let comment_str = user_str[1..user_str.len() - 1].trim();
807 if block.stmts.is_empty() && !comment_str.contains('\n') &&
808 !comment_str.starts_with("//") && comment_str.len() + 4 <= shape.width
810 return Some(format!("{{ {} }}", comment_str));
817 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
818 Some(match block.rules {
819 ast::BlockCheckMode::Unsafe(..) => {
820 let snippet = context.snippet(block.span);
821 let open_pos = try_opt!(snippet.find_uncommented("{"));
822 // Extract comment between unsafe and block start.
823 let trimmed = &snippet[6..open_pos].trim();
825 if !trimmed.is_empty() {
826 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
827 let budget = try_opt!(shape.width.checked_sub(9));
830 try_opt!(rewrite_comment(
833 Shape::legacy(budget, shape.indent + 7),
841 ast::BlockCheckMode::Default => String::new(),
845 fn rewrite_single_line_block(
846 context: &RewriteContext,
850 ) -> Option<String> {
851 if is_simple_block(block, context.codemap) {
852 let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
853 let expr_str = try_opt!(block.stmts[0].rewrite(context, expr_shape));
854 let result = format!("{}{{ {} }}", prefix, expr_str);
855 if result.len() <= shape.width && !result.contains('\n') {
862 fn rewrite_block_with_visitor(
863 context: &RewriteContext,
867 ) -> Option<String> {
868 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
872 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
873 visitor.block_indent = shape.indent;
874 visitor.is_if_else_block = context.is_if_else_block;
876 ast::BlockCheckMode::Unsafe(..) => {
877 let snippet = context.snippet(block.span);
878 let open_pos = try_opt!(snippet.find_uncommented("{"));
879 visitor.last_pos = block.span.lo + BytePos(open_pos as u32)
881 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo,
884 visitor.visit_block(block, None);
885 Some(format!("{}{}", prefix, visitor.buffer))
888 impl Rewrite for ast::Block {
889 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
890 // shape.width is used only for the single line case: either the empty block `{}`,
891 // or an unsafe expression `unsafe { e }`.
892 if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
896 let prefix = try_opt!(block_prefix(context, self, shape));
897 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
901 rewrite_block_with_visitor(context, &prefix, self, shape)
905 impl Rewrite for ast::Stmt {
906 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
907 let result = match self.node {
908 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
909 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
910 let suffix = if semicolon_for_stmt(context, self) {
919 ast::StmtKind::Expr(_) => ExprType::SubExpression,
920 ast::StmtKind::Semi(_) => ExprType::Statement,
924 try_opt!(shape.sub_width(suffix.len())),
925 ).map(|s| s + suffix)
927 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
929 result.and_then(|res| {
930 recover_comment_removed(res, self.span(), context, shape)
935 // Rewrite condition if the given expression has one.
936 fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
938 ast::ExprKind::Match(ref cond, _) => {
940 let cond_shape = match context.config.control_style() {
941 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
942 Style::Rfc => try_opt!(shape.offset_left(8)),
944 cond.rewrite(context, cond_shape)
946 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
947 stmt_expr(&block.stmts[0]).and_then(|e| rewrite_cond(context, e, shape))
949 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
951 String::from("\n") + &shape.indent.block_only().to_string(context.config);
953 .rewrite_cond(context, shape, &alt_block_sep)
954 .and_then(|rw| Some(rw.0))
959 // Abstraction over control flow expressions
961 struct ControlFlow<'a> {
962 cond: Option<&'a ast::Expr>,
963 block: &'a ast::Block,
964 else_block: Option<&'a ast::Expr>,
965 label: Option<ast::SpannedIdent>,
966 pat: Option<&'a ast::Pat>,
970 allow_single_line: bool,
971 // True if this is an `if` expression in an `else if` :-( hacky
976 fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'a>> {
978 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
982 else_block.as_ref().map(|e| &**e),
983 expr_type == ExprType::SubExpression,
987 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
988 Some(ControlFlow::new_if(
992 else_block.as_ref().map(|e| &**e),
993 expr_type == ExprType::SubExpression,
998 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
999 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
1001 ast::ExprKind::Loop(ref block, label) => {
1002 Some(ControlFlow::new_loop(block, label, expr.span))
1004 ast::ExprKind::While(ref cond, ref block, label) => {
1005 Some(ControlFlow::new_while(None, cond, block, label, expr.span))
1007 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
1008 ControlFlow::new_while(Some(pat), cond, block, label, expr.span),
1014 impl<'a> ControlFlow<'a> {
1016 cond: &'a ast::Expr,
1017 pat: Option<&'a ast::Pat>,
1018 block: &'a ast::Block,
1019 else_block: Option<&'a ast::Expr>,
1020 allow_single_line: bool,
1023 ) -> ControlFlow<'a> {
1027 else_block: else_block,
1031 matcher: match pat {
1036 allow_single_line: allow_single_line,
1037 nested_if: nested_if,
1043 block: &'a ast::Block,
1044 label: Option<ast::SpannedIdent>,
1046 ) -> ControlFlow<'a> {
1056 allow_single_line: false,
1063 pat: Option<&'a ast::Pat>,
1064 cond: &'a ast::Expr,
1065 block: &'a ast::Block,
1066 label: Option<ast::SpannedIdent>,
1068 ) -> ControlFlow<'a> {
1076 matcher: match pat {
1081 allow_single_line: false,
1089 cond: &'a ast::Expr,
1090 block: &'a ast::Block,
1091 label: Option<ast::SpannedIdent>,
1093 ) -> ControlFlow<'a> {
1103 allow_single_line: false,
1109 fn rewrite_single_line(
1112 context: &RewriteContext,
1114 ) -> Option<String> {
1115 assert!(self.allow_single_line);
1116 let else_block = try_opt!(self.else_block);
1117 let fixed_cost = self.keyword.len() + " { } else { }".len();
1119 if let ast::ExprKind::Block(ref else_node) = else_block.node {
1120 if !is_simple_block(self.block, context.codemap) ||
1121 !is_simple_block(else_node, context.codemap) ||
1122 pat_expr_str.contains('\n')
1127 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
1128 let expr = &self.block.stmts[0];
1129 let if_str = try_opt!(expr.rewrite(
1131 Shape::legacy(new_width, Indent::empty()),
1134 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
1135 let else_expr = &else_node.stmts[0];
1137 try_opt!(else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
1139 if if_str.contains('\n') || else_str.contains('\n') {
1143 let result = format!(
1144 "{} {} {{ {} }} else {{ {} }}",
1151 if result.len() <= width {
1152 return Some(result);
1160 impl<'a> ControlFlow<'a> {
1163 context: &RewriteContext,
1165 alt_block_sep: &str,
1166 ) -> Option<(String, usize)> {
1167 // Do not take the rhs overhead from the upper expressions into account
1168 // when rewriting pattern.
1169 let new_width = context
1172 .checked_sub(shape.used_width())
1174 let fresh_shape = Shape {
1178 let constr_shape = if self.nested_if {
1179 // We are part of an if-elseif-else chain. Our constraints are tightened.
1180 // 7 = "} else " .len()
1181 try_opt!(fresh_shape.offset_left(7))
1186 let label_string = rewrite_label(self.label);
1187 // 1 = space after keyword.
1188 let offset = self.keyword.len() + label_string.len() + 1;
1190 let pat_expr_string = match self.cond {
1192 let cond_shape = match context.config.control_style() {
1193 Style::Legacy => try_opt!(constr_shape.shrink_left(offset)),
1194 Style::Rfc => try_opt!(constr_shape.offset_left(offset)),
1196 try_opt!(rewrite_pat_expr(
1206 None => String::new(),
1209 let brace_overhead =
1210 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1216 let one_line_budget = context
1219 .checked_sub(constr_shape.used_width() + offset + brace_overhead)
1221 let force_newline_brace = context.config.control_style() == Style::Rfc &&
1222 (pat_expr_string.contains('\n') || pat_expr_string.len() > one_line_budget) &&
1223 !last_line_extendable(&pat_expr_string);
1225 // Try to format if-else on single line.
1226 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1227 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1229 if let Some(cond_str) = trial {
1230 if cond_str.len() <= context.config.single_line_if_else_max_width() {
1231 return Some((cond_str, 0));
1236 let cond_span = if let Some(cond) = self.cond {
1239 mk_sp(self.block.span.lo, self.block.span.lo)
1242 // for event in event
1243 let between_kwd_cond = mk_sp(
1244 context.codemap.span_after(self.span, self.keyword.trim()),
1247 |p| if self.matcher.is_empty() {
1250 context.codemap.span_before(self.span, self.matcher.trim())
1255 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1257 let after_cond_comment =
1258 extract_comment(mk_sp(cond_span.hi, self.block.span.lo), context, shape);
1260 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1262 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine ||
1270 let used_width = if pat_expr_string.contains('\n') {
1271 last_line_width(&pat_expr_string)
1273 // 2 = spaces after keyword and condition.
1274 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1282 between_kwd_cond_comment.as_ref().map_or(
1283 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1291 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1298 impl<'a> Rewrite for ControlFlow<'a> {
1299 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1300 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1303 String::from("\n") + &shape.indent.block_only().to_string(context.config);
1304 let (cond_str, used_width) = try_opt!(self.rewrite_cond(context, shape, &alt_block_sep));
1305 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1306 if used_width == 0 {
1307 return Some(cond_str);
1310 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1311 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1312 // we should avoid the single line case.
1313 let block_width = if self.else_block.is_some() || self.nested_if {
1318 let block_shape = Shape {
1322 let mut block_context = context.clone();
1323 block_context.is_if_else_block = self.else_block.is_some();
1324 let block_str = try_opt!(rewrite_block_with_visitor(
1331 let mut result = format!("{}{}", cond_str, block_str);
1333 if let Some(else_block) = self.else_block {
1334 let shape = Shape::indented(shape.indent, context.config);
1335 let mut last_in_chain = false;
1336 let rewrite = match else_block.node {
1337 // If the else expression is another if-else expression, prevent it
1338 // from being formatted on a single line.
1339 // Note how we're passing the original shape, as the
1340 // cost of "else" should not cascade.
1341 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1342 ControlFlow::new_if(
1346 next_else_block.as_ref().map(|e| &**e),
1349 mk_sp(else_block.span.lo, self.span.hi),
1350 ).rewrite(context, shape)
1352 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1353 ControlFlow::new_if(
1357 next_else_block.as_ref().map(|e| &**e),
1360 mk_sp(else_block.span.lo, self.span.hi),
1361 ).rewrite(context, shape)
1364 last_in_chain = true;
1365 // When rewriting a block, the width is only used for single line
1366 // blocks, passing 1 lets us avoid that.
1367 let else_shape = Shape {
1368 width: min(1, shape.width),
1371 format_expr(else_block, ExprType::Statement, context, else_shape)
1375 let between_kwd_else_block = mk_sp(
1379 .span_before(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1381 let between_kwd_else_block_comment =
1382 extract_comment(between_kwd_else_block, context, shape);
1384 let after_else = mk_sp(
1387 .span_after(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1390 let after_else_comment = extract_comment(after_else, context, shape);
1392 let between_sep = match context.config.control_brace_style() {
1393 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1396 ControlBraceStyle::AlwaysSameLine => " ",
1398 let after_sep = match context.config.control_brace_style() {
1399 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1406 between_kwd_else_block_comment
1408 .map_or(between_sep, |s| &**s),
1409 after_else_comment.as_ref().map_or(after_sep, |s| &**s)
1412 result.push_str(&try_opt!(rewrite));
1419 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
1421 Some(ident) => format!("{}: ", ident.node),
1422 None => "".to_owned(),
1426 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1427 let comment_str = context.snippet(span);
1428 if contains_comment(&comment_str) {
1429 let comment = try_opt!(rewrite_comment(
1436 "\n{indent}{}\n{indent}",
1438 indent = shape.indent.to_string(context.config)
1445 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1446 let snippet = codemap.span_to_snippet(block.span).unwrap();
1447 contains_comment(&snippet)
1450 // Checks that a block contains no statements, an expression and no comments.
1451 // FIXME: incorrectly returns false when comment is contained completely within
1453 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1454 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) &&
1455 !block_contains_comment(block, codemap))
1458 /// Checks whether a block contains at most one statement or expression, and no comments.
1459 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1460 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1463 /// Checks whether a block contains no statements, expressions, or comments.
1464 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1465 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1468 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1470 ast::StmtKind::Expr(..) => true,
1475 fn is_unsafe_block(block: &ast::Block) -> bool {
1476 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1483 // inter-match-arm-comment-rules:
1484 // - all comments following a match arm before the start of the next arm
1485 // are about the second arm
1486 fn rewrite_match_arm_comment(
1487 context: &RewriteContext,
1490 arm_indent_str: &str,
1491 ) -> Option<String> {
1492 // The leading "," is not part of the arm-comment
1493 let missed_str = match missed_str.find_uncommented(",") {
1494 Some(n) => &missed_str[n + 1..],
1495 None => &missed_str[..],
1498 let mut result = String::new();
1499 // any text not preceeded by a newline is pushed unmodified to the block
1500 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
1501 result.push_str(&missed_str[..first_brk]);
1502 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
1504 let first = missed_str
1505 .find(|c: char| !c.is_whitespace())
1506 .unwrap_or(missed_str.len());
1507 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
1508 // Excessive vertical whitespace before comment should be preserved
1509 // FIXME handle vertical whitespace better
1512 let missed_str = missed_str[first..].trim();
1513 if !missed_str.is_empty() {
1514 let comment = try_opt!(rewrite_comment(&missed_str, false, shape, context.config));
1516 result.push_str(arm_indent_str);
1517 result.push_str(&comment);
1524 context: &RewriteContext,
1529 ) -> Option<String> {
1530 if arms.is_empty() {
1534 // 6 = `match `, 2 = ` {`
1535 let cond_shape = match context.config.control_style() {
1536 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
1537 Style::Rfc => try_opt!(shape.offset_left(6).and_then(|s| s.sub_width(2))),
1539 let cond_str = try_opt!(cond.rewrite(context, cond_shape));
1540 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1541 let block_sep = match context.config.control_brace_style() {
1542 ControlBraceStyle::AlwaysNextLine => &alt_block_sep,
1543 _ if last_line_extendable(&cond_str) => " ",
1544 _ if cond_str.contains('\n') => &alt_block_sep,
1549 "match {}{}{{{}\n{}}}",
1552 try_opt!(rewrite_match_arms(context, arms, shape, span, cond.span.hi)),
1553 shape.indent.to_string(context.config),
1557 fn arm_comma(config: &Config, body: &ast::Expr) -> &'static str {
1558 if config.match_block_trailing_comma() {
1560 } else if let ast::ExprKind::Block(ref block) = body.node {
1561 if let ast::BlockCheckMode::Default = block.rules {
1571 fn rewrite_match_arms(
1572 context: &RewriteContext,
1576 cond_end_pos: BytePos,
1577 ) -> Option<String> {
1578 let mut result = String::new();
1580 let arm_shape = if context.config.indent_match_arms() {
1581 shape.block_indent(context.config.tab_spaces())
1583 shape.block_indent(0)
1584 }.with_max_width(context.config);
1585 let arm_indent_str = arm_shape.indent.to_string(context.config);
1587 let open_brace_pos = context
1589 .span_after(mk_sp(cond_end_pos, arms[0].span().lo), "{");
1591 let arm_num = arms.len();
1592 for (i, arm) in arms.iter().enumerate() {
1593 // Make sure we get the stuff between arms.
1594 let missed_str = if i == 0 {
1595 context.snippet(mk_sp(open_brace_pos, arm.span().lo))
1597 context.snippet(mk_sp(arms[i - 1].span().hi, arm.span().lo))
1599 let comment = try_opt!(rewrite_match_arm_comment(
1605 result.push_str(&comment);
1607 result.push_str(&arm_indent_str);
1609 let arm_str = rewrite_match_arm(context, arm, arm_shape);
1610 if let Some(ref arm_str) = arm_str {
1611 // Trim the trailing comma if necessary.
1612 if i == arm_num - 1 && context.config.trailing_comma() == SeparatorTactic::Never &&
1613 arm_str.ends_with(',')
1615 result.push_str(&arm_str[0..arm_str.len() - 1])
1617 result.push_str(arm_str)
1620 // We couldn't format the arm, just reproduce the source.
1621 let snippet = context.snippet(arm.span());
1622 result.push_str(&snippet);
1623 if context.config.trailing_comma() != SeparatorTactic::Never {
1624 result.push_str(arm_comma(context.config, &arm.body))
1628 // BytePos(1) = closing match brace.
1629 let last_span = mk_sp(arms[arms.len() - 1].span().hi, span.hi - BytePos(1));
1630 let last_comment = context.snippet(last_span);
1631 let comment = try_opt!(rewrite_match_arm_comment(
1637 result.push_str(&comment);
1642 fn rewrite_match_arm(context: &RewriteContext, arm: &ast::Arm, shape: Shape) -> Option<String> {
1643 let attr_str = if !arm.attrs.is_empty() {
1644 if contains_skip(&arm.attrs) {
1649 try_opt!(arm.attrs.rewrite(context, shape)),
1650 shape.indent.to_string(context.config)
1655 let pats_str = try_opt!(rewrite_match_pattern(context, &arm.pats, &arm.guard, shape));
1656 let pats_str = attr_str + &pats_str;
1657 rewrite_match_body(context, &arm.body, &pats_str, shape, arm.guard.is_some())
1660 fn rewrite_match_pattern(
1661 context: &RewriteContext,
1662 pats: &Vec<ptr::P<ast::Pat>>,
1663 guard: &Option<ptr::P<ast::Expr>>,
1665 ) -> Option<String> {
1668 let pat_shape = try_opt!(shape.sub_width(5));
1670 let pat_strs = try_opt!(
1672 .map(|p| p.rewrite(context, pat_shape))
1673 .collect::<Option<Vec<_>>>()
1676 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1677 let tactic = definitive_tactic(
1679 ListTactic::HorizontalVertical,
1680 Separator::VerticalBar,
1683 let fmt = ListFormatting {
1686 trailing_separator: SeparatorTactic::Never,
1688 ends_with_newline: false,
1689 preserve_newline: false,
1690 config: context.config,
1692 let pats_str = try_opt!(write_list(&items, &fmt));
1695 let guard_str = try_opt!(rewrite_guard(
1699 trimmed_last_line_width(&pats_str),
1702 Some(format!("{}{}", pats_str, guard_str))
1705 fn rewrite_match_body(
1706 context: &RewriteContext,
1707 body: &ptr::P<ast::Expr>,
1711 ) -> Option<String> {
1712 let (extend, body) = match body.node {
1713 ast::ExprKind::Block(ref block)
1714 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) =>
1716 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1717 (expr.can_be_overflowed(context, 1), &**expr)
1722 _ => (body.can_be_overflowed(context, 1), &**body),
1725 let comma = arm_comma(&context.config, body);
1726 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1727 let alt_block_sep = alt_block_sep.as_str();
1728 let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
1729 (true, is_empty_block(block, context.codemap))
1734 let combine_orig_body = |body_str: &str| {
1735 let block_sep = match context.config.control_brace_style() {
1736 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
1740 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
1743 let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
1744 let next_line_indent = if is_block {
1747 shape.indent.block_indent(context.config)
1749 let combine_next_line_body = |body_str: &str| {
1751 return Some(format!(
1754 next_line_indent.to_string(context.config),
1759 let indent_str = shape.indent.to_string(context.config);
1760 let nested_indent_str = next_line_indent.to_string(context.config);
1761 let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1762 let comma = if context.config.match_block_trailing_comma() {
1767 ("{", format!("\n{}}}{}", indent_str, comma))
1769 ("", String::from(","))
1772 let block_sep = match context.config.control_brace_style() {
1773 ControlBraceStyle::AlwaysNextLine => format!("{}{}\n", alt_block_sep, body_prefix),
1774 _ if body_prefix.is_empty() => "\n".to_owned(),
1775 _ if forbid_same_line => format!("{}{}\n", alt_block_sep, body_prefix),
1776 _ => format!(" {}\n", body_prefix),
1777 } + &nested_indent_str;
1788 // Let's try and get the arm body on the same line as the condition.
1790 let orig_body_shape = shape
1791 .offset_left(extra_offset(&pats_str, shape) + 4)
1792 .and_then(|shape| shape.sub_width(comma.len()));
1793 let orig_body = if let Some(body_shape) = orig_body_shape {
1794 let rewrite = nop_block_collapse(
1795 format_expr(body, ExprType::Statement, context, body_shape),
1801 if !forbid_same_line &&
1803 (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
1805 return combine_orig_body(body_str);
1812 let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
1814 // Try putting body on the next line and see if it looks better.
1815 let next_line_body_shape = Shape::indented(next_line_indent, context.config);
1816 let next_line_body = nop_block_collapse(
1817 format_expr(body, ExprType::Statement, context, next_line_body_shape),
1818 next_line_body_shape.width,
1820 match (orig_body, next_line_body) {
1821 (Some(ref orig_str), Some(ref next_line_str))
1822 if forbid_same_line || prefer_next_line(orig_str, next_line_str) =>
1824 combine_next_line_body(next_line_str)
1826 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
1827 combine_orig_body(orig_str)
1829 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
1830 combine_next_line_body(next_line_str)
1832 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
1833 (None, None) => None,
1834 (Some(ref orig_str), _) => combine_orig_body(orig_str),
1838 // The `if ...` guard on a match arm.
1840 context: &RewriteContext,
1841 guard: &Option<ptr::P<ast::Expr>>,
1843 // The amount of space used up on this line for the pattern in
1844 // the arm (excludes offset).
1845 pattern_width: usize,
1846 ) -> Option<String> {
1847 if let Some(ref guard) = *guard {
1848 // First try to fit the guard string on the same line as the pattern.
1849 // 4 = ` if `, 5 = ` => {`
1850 let cond_shape = shape
1851 .offset_left(pattern_width + 4)
1852 .and_then(|s| s.sub_width(5));
1853 if let Some(cond_shape) = cond_shape {
1854 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1855 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
1856 return Some(format!(" if {}", cond_str));
1861 // Not enough space to put the guard after the pattern, try a newline.
1862 // 3 = `if `, 5 = ` => {`
1863 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
1865 .and_then(|s| s.sub_width(5));
1866 if let Some(cond_shape) = cond_shape {
1867 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1868 return Some(format!(
1870 cond_shape.indent.to_string(context.config),
1882 fn rewrite_pat_expr(
1883 context: &RewriteContext,
1884 pat: Option<&ast::Pat>,
1887 // Connecting piece between pattern and expression,
1888 // *without* trailing space.
1892 ) -> Option<String> {
1893 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1894 if let Some(pat) = pat {
1895 let matcher = if matcher.is_empty() {
1898 format!("{} ", matcher)
1901 try_opt!(try_opt!(shape.offset_left(matcher.len())).sub_width(connector.len()));
1902 let pat_string = try_opt!(pat.rewrite(context, pat_shape));
1903 let result = format!("{}{}{}", matcher, pat_string, connector);
1904 return rewrite_assign_rhs(context, result, expr, shape);
1907 let expr_rw = expr.rewrite(context, shape);
1908 // The expression may (partially) fit on the current line.
1909 // We do not allow splitting between `if` and condition.
1910 if keyword == "if" || expr_rw.is_some() {
1914 // The expression won't fit on the current line, jump to next.
1915 let nested_shape = shape
1916 .block_indent(context.config.tab_spaces())
1917 .with_max_width(context.config);
1918 let nested_indent_str = nested_shape.indent.to_string(context.config);
1919 expr.rewrite(context, nested_shape)
1920 .map(|expr_rw| format!("\n{}{}", nested_indent_str, expr_rw))
1923 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1924 let string_lit = context.snippet(span);
1926 if !context.config.format_strings() && !context.config.force_format_strings() {
1931 .all(|line| line.ends_with('\\'))
1933 let new_indent = shape.visual_indent(1).indent;
1934 return Some(String::from(
1938 new_indent.to_string(context.config) + line.trim_left()
1940 .collect::<Vec<_>>()
1945 return Some(string_lit);
1949 if !context.config.force_format_strings() &&
1950 !string_requires_rewrite(context, span, &string_lit, shape)
1952 return Some(string_lit);
1955 let fmt = StringFormat {
1962 config: context.config,
1965 // Remove the quote characters.
1966 let str_lit = &string_lit[1..string_lit.len() - 1];
1968 rewrite_string(str_lit, &fmt)
1971 fn string_requires_rewrite(
1972 context: &RewriteContext,
1977 if context.codemap.lookup_char_pos(span.lo).col.0 != shape.indent.width() {
1981 for (i, line) in string.lines().enumerate() {
1983 if line.len() > shape.width {
1987 if line.len() > shape.width + shape.indent.width() {
1996 pub fn rewrite_call_with_binary_search<R>(
1997 context: &RewriteContext,
1999 args: &[&ast::Expr],
2006 let force_trailing_comma = if context.inside_macro {
2007 span_ends_with_comma(context, span)
2011 let closure = |callee_max_width| {
2012 // FIXME using byte lens instead of char lens (and probably all over the
2014 let callee_shape = Shape {
2015 width: callee_max_width,
2018 let callee_str = callee
2019 .rewrite(context, callee_shape)
2020 .ok_or(Ordering::Greater)?;
2028 context.config.fn_call_width(),
2029 force_trailing_comma,
2033 binary_search(1, shape.width, closure)
2036 pub fn rewrite_call(
2037 context: &RewriteContext,
2039 args: &[ptr::P<ast::Expr>],
2042 ) -> Option<String> {
2043 let force_trailing_comma = if context.inside_macro {
2044 span_ends_with_comma(context, span)
2051 &args.iter().map(|x| &**x).collect::<Vec<_>>(),
2054 context.config.fn_call_width(),
2055 force_trailing_comma,
2059 pub fn rewrite_call_inner<'a, T>(
2060 context: &RewriteContext,
2065 args_max_width: usize,
2066 force_trailing_comma: bool,
2067 ) -> Result<String, Ordering>
2069 T: Rewrite + Spanned + ToExpr + 'a,
2071 // 2 = `( `, 1 = `(`
2072 let paren_overhead = if context.config.spaces_within_parens() {
2077 let used_width = extra_offset(&callee_str, shape);
2078 let one_line_width = shape
2080 .checked_sub(used_width + 2 * paren_overhead)
2081 .ok_or(Ordering::Greater)?;
2083 let nested_shape = shape_from_fn_call_style(
2086 used_width + 2 * paren_overhead,
2087 used_width + paren_overhead,
2088 ).ok_or(Ordering::Greater)?;
2090 let span_lo = context.codemap.span_after(span, "(");
2091 let args_span = mk_sp(span_lo, span.hi);
2093 let (extendable, list_str) = rewrite_call_args(
2100 force_trailing_comma,
2101 ).ok_or(Ordering::Less)?;
2103 if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
2104 let mut new_context = context.clone();
2105 new_context.use_block = true;
2106 return rewrite_call_inner(
2113 force_trailing_comma,
2117 let args_shape = shape
2118 .sub_width(last_line_width(&callee_str))
2119 .ok_or(Ordering::Less)?;
2123 wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2127 fn need_block_indent(s: &str, shape: Shape) -> bool {
2128 s.lines().skip(1).any(|s| {
2129 s.find(|c| !char::is_whitespace(c))
2130 .map_or(false, |w| w + 1 < shape.indent.width())
2134 fn rewrite_call_args<'a, T>(
2135 context: &RewriteContext,
2139 one_line_width: usize,
2140 args_max_width: usize,
2141 force_trailing_comma: bool,
2142 ) -> Option<(bool, String)>
2144 T: Rewrite + Spanned + ToExpr + 'a,
2146 let items = itemize_list(
2150 |item| item.span().lo,
2151 |item| item.span().hi,
2152 |item| item.rewrite(context, shape),
2156 let mut item_vec: Vec<_> = items.collect();
2158 // Try letting the last argument overflow to the next line with block
2159 // indentation. If its first line fits on one line with the other arguments,
2160 // we format the function arguments horizontally.
2161 let tactic = try_overflow_last_arg(
2170 let fmt = ListFormatting {
2173 trailing_separator: if force_trailing_comma {
2174 SeparatorTactic::Always
2175 } else if context.inside_macro || !context.use_block_indent() {
2176 SeparatorTactic::Never
2178 context.config.trailing_comma()
2181 ends_with_newline: context.use_block_indent() && tactic == DefinitiveListTactic::Vertical,
2182 preserve_newline: false,
2183 config: context.config,
2186 write_list(&item_vec, &fmt).map(|args_str| {
2187 (tactic != DefinitiveListTactic::Vertical, args_str)
2191 fn try_overflow_last_arg<'a, T>(
2192 context: &RewriteContext,
2193 item_vec: &mut Vec<ListItem>,
2196 one_line_width: usize,
2197 args_max_width: usize,
2198 ) -> DefinitiveListTactic
2200 T: Rewrite + Spanned + ToExpr + 'a,
2202 let overflow_last = can_be_overflowed(&context, args);
2204 // Replace the last item with its first line to see if it fits with
2206 let (orig_last, placeholder) = if overflow_last {
2207 let mut context = context.clone();
2208 if let Some(expr) = args[args.len() - 1].to_expr() {
2210 ast::ExprKind::MethodCall(..) => context.force_one_line_chain = true,
2214 last_arg_shape(&context, &item_vec, shape, args_max_width)
2215 .map_or((None, None), |arg_shape| {
2216 rewrite_last_arg_with_overflow(
2219 &mut item_vec[args.len() - 1],
2227 let tactic = definitive_tactic(
2229 ListTactic::LimitedHorizontalVertical(args_max_width),
2234 // Replace the stub with the full overflowing last argument if the rewrite
2235 // succeeded and its first line fits with the other arguments.
2236 match (overflow_last, tactic, placeholder) {
2237 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2238 item_vec[args.len() - 1].item = placeholder;
2241 item_vec[args.len() - 1].item = orig_last;
2250 context: &RewriteContext,
2251 items: &Vec<ListItem>,
2253 args_max_width: usize,
2254 ) -> Option<Shape> {
2255 let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
2256 acc + i.item.as_ref().map_or(0, |s| first_line_width(&s))
2258 let max_width = min(args_max_width, shape.width);
2259 let arg_indent = if context.use_block_indent() {
2260 shape.block().indent.block_unindent(context.config)
2262 shape.block().indent
2265 width: try_opt!(max_width.checked_sub(overhead)),
2271 // Rewriting closure which is placed at the end of the function call's arg.
2272 // Returns `None` if the reformatted closure 'looks bad'.
2273 fn rewrite_last_closure(
2274 context: &RewriteContext,
2277 ) -> Option<String> {
2278 if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
2279 let body = match body.node {
2280 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
2281 stmt_expr(&block.stmts[0]).unwrap_or(body)
2285 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
2293 // If the closure goes multi line before its body, do not overflow the closure.
2294 if prefix.contains('\n') {
2297 let body_shape = try_opt!(shape.offset_left(extra_offset));
2298 // When overflowing the closure which consists of a single control flow expression,
2299 // force to use block if its condition uses multi line.
2300 let is_multi_lined_cond = rewrite_cond(context, body, body_shape)
2301 .map(|cond| cond.contains('\n') || cond.len() > body_shape.width)
2303 if is_multi_lined_cond {
2304 return rewrite_closure_with_block(context, body_shape, &prefix, body);
2307 // Seems fine, just format the closure in usual manner.
2308 return expr.rewrite(context, shape);
2313 fn rewrite_last_arg_with_overflow<'a, T>(
2314 context: &RewriteContext,
2316 last_item: &mut ListItem,
2318 ) -> (Option<String>, Option<String>)
2320 T: Rewrite + Spanned + ToExpr + 'a,
2322 let last_arg = args[args.len() - 1];
2323 let rewrite = if let Some(expr) = last_arg.to_expr() {
2325 // When overflowing the closure which consists of a single control flow expression,
2326 // force to use block if its condition uses multi line.
2327 ast::ExprKind::Closure(..) => {
2328 // If the argument consists of multiple closures, we do not overflow
2329 // the last closure.
2330 if args.len() > 1 &&
2334 .filter_map(|arg| arg.to_expr())
2335 .any(|expr| match expr.node {
2336 ast::ExprKind::Closure(..) => true,
2341 rewrite_last_closure(context, expr, shape)
2344 _ => expr.rewrite(context, shape),
2347 last_arg.rewrite(context, shape)
2349 let orig_last = last_item.item.clone();
2351 if let Some(rewrite) = rewrite {
2352 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2353 last_item.item = rewrite_first_line;
2354 (orig_last, Some(rewrite))
2360 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2362 T: Rewrite + Spanned + ToExpr + 'a,
2365 .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2368 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2370 ast::ExprKind::Match(..) => {
2371 (context.use_block_indent() && args_len == 1) ||
2372 (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
2374 ast::ExprKind::If(..) |
2375 ast::ExprKind::IfLet(..) |
2376 ast::ExprKind::ForLoop(..) |
2377 ast::ExprKind::Loop(..) |
2378 ast::ExprKind::While(..) |
2379 ast::ExprKind::WhileLet(..) => {
2380 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2382 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
2383 context.use_block_indent() ||
2384 context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
2386 ast::ExprKind::Array(..) |
2387 ast::ExprKind::Call(..) |
2388 ast::ExprKind::Mac(..) |
2389 ast::ExprKind::MethodCall(..) |
2390 ast::ExprKind::Struct(..) |
2391 ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2392 ast::ExprKind::AddrOf(_, ref expr) |
2393 ast::ExprKind::Box(ref expr) |
2394 ast::ExprKind::Try(ref expr) |
2395 ast::ExprKind::Unary(_, ref expr) |
2396 ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2401 pub fn wrap_args_with_parens(
2402 context: &RewriteContext,
2404 is_extendable: bool,
2406 nested_shape: Shape,
2408 if !context.use_block_indent() ||
2409 (context.inside_macro && !args_str.contains('\n') &&
2410 args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2412 if context.config.spaces_within_parens() && args_str.len() > 0 {
2413 format!("( {} )", args_str)
2415 format!("({})", args_str)
2420 nested_shape.indent.to_string(context.config),
2422 shape.block().indent.to_string(context.config)
2427 fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2428 let snippet = context.snippet(span);
2430 .trim_right_matches(|c: char| c == ')' || c.is_whitespace())
2434 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2435 debug!("rewrite_paren, shape: {:?}", shape);
2436 let total_paren_overhead = paren_overhead(context);
2437 let paren_overhead = total_paren_overhead / 2;
2438 let sub_shape = try_opt!(
2440 .offset_left(paren_overhead)
2441 .and_then(|s| s.sub_width(paren_overhead))
2444 let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && s.len() > 0 {
2445 format!("( {} )", s)
2450 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2451 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2453 if subexpr_str.contains('\n') ||
2454 first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
2456 Some(paren_wrapper(&subexpr_str))
2465 context: &RewriteContext,
2467 ) -> Option<String> {
2468 let expr_str = try_opt!(expr.rewrite(context, shape));
2470 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
2476 let offset = last_line_width(&expr_str) + lbr.len();
2477 let rhs_overhead = shape.rhs_overhead(context.config);
2478 let index_shape = if expr_str.contains('\n') {
2479 Shape::legacy(context.config.max_width(), shape.indent)
2480 .offset_left(offset)
2481 .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
2483 shape.visual_indent(offset).sub_width(offset + rbr.len())
2485 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
2487 // Return if index fits in a single line.
2488 match orig_index_rw {
2489 Some(ref index_str) if !index_str.contains('\n') => {
2490 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2495 // Try putting index on the next line and see if it fits in a single line.
2496 let indent = shape.indent.block_indent(context.config);
2497 let index_shape = try_opt!(Shape::indented(indent, context.config).offset_left(lbr.len()));
2498 let index_shape = try_opt!(index_shape.sub_width(rbr.len() + rhs_overhead));
2499 let new_index_rw = index.rewrite(context, index_shape);
2500 match (orig_index_rw, new_index_rw) {
2501 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
2504 indent.to_string(&context.config),
2509 (None, Some(ref new_index_str)) => Some(format!(
2512 indent.to_string(&context.config),
2517 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2522 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2527 fields.iter().all(|field| !field.is_shorthand)
2530 fn rewrite_struct_lit<'a>(
2531 context: &RewriteContext,
2533 fields: &'a [ast::Field],
2534 base: Option<&'a ast::Expr>,
2537 ) -> Option<String> {
2538 debug!("rewrite_struct_lit: shape {:?}", shape);
2540 enum StructLitField<'a> {
2541 Regular(&'a ast::Field),
2542 Base(&'a ast::Expr),
2546 let path_shape = try_opt!(shape.sub_width(2));
2547 let path_str = try_opt!(rewrite_path(
2555 if fields.len() == 0 && base.is_none() {
2556 return Some(format!("{} {{}}", path_str));
2559 // Foo { a: Foo } - indent is +3, width is -5.
2560 let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
2562 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2563 let body_lo = context.codemap.span_after(span, "{");
2564 let fields_str = if struct_lit_can_be_aligned(fields, &base) &&
2565 context.config.struct_field_align_threshold() > 0
2567 try_opt!(rewrite_with_alignment(
2571 mk_sp(body_lo, span.hi),
2575 let field_iter = fields
2577 .map(StructLitField::Regular)
2578 .chain(base.into_iter().map(StructLitField::Base));
2580 let span_lo = |item: &StructLitField| match *item {
2581 StructLitField::Regular(field) => field.span().lo,
2582 StructLitField::Base(expr) => {
2583 let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
2584 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
2585 let pos = snippet.find_uncommented("..").unwrap();
2586 last_field_hi + BytePos(pos as u32)
2589 let span_hi = |item: &StructLitField| match *item {
2590 StructLitField::Regular(field) => field.span().hi,
2591 StructLitField::Base(expr) => expr.span.hi,
2593 let rewrite = |item: &StructLitField| match *item {
2594 StructLitField::Regular(field) => {
2595 // The 1 taken from the v_budget is for the comma.
2596 rewrite_field(context, field, try_opt!(v_shape.sub_width(1)), 0)
2598 StructLitField::Base(expr) => {
2600 expr.rewrite(context, try_opt!(v_shape.offset_left(2)))
2601 .map(|s| format!("..{}", s))
2605 let items = itemize_list(
2615 let item_vec = items.collect::<Vec<_>>();
2617 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2618 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2619 let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2621 try_opt!(write_list(&item_vec, &fmt))
2624 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2625 Some(format!("{} {{{}}}", path_str, fields_str))
2627 // FIXME if context.config.struct_lit_style() == Visual, but we run out
2628 // of space, we should fall back to BlockIndent.
2631 pub fn wrap_struct_field(
2632 context: &RewriteContext,
2635 nested_shape: Shape,
2636 one_line_width: usize,
2638 if context.config.struct_lit_style() == IndentStyle::Block &&
2639 (fields_str.contains('\n') ||
2640 context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti ||
2641 fields_str.len() > one_line_width)
2645 nested_shape.indent.to_string(context.config),
2647 shape.indent.to_string(context.config)
2650 // One liner or visual indent.
2651 format!(" {} ", fields_str)
2655 pub fn struct_lit_field_separator(config: &Config) -> &str {
2657 config.space_before_struct_lit_field_colon(),
2658 config.space_after_struct_lit_field_colon(),
2662 pub fn rewrite_field(
2663 context: &RewriteContext,
2666 prefix_max_width: usize,
2667 ) -> Option<String> {
2668 if contains_skip(&field.attrs) {
2670 context.snippet(field.span()),
2671 context.config.max_width(),
2675 let name = &field.ident.node.to_string();
2676 if field.is_shorthand {
2677 Some(name.to_string())
2679 let mut separator = String::from(struct_lit_field_separator(context.config));
2680 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2681 separator.push(' ');
2683 let overhead = name.len() + separator.len();
2684 let expr_shape = try_opt!(shape.offset_left(overhead));
2685 let expr = field.expr.rewrite(context, expr_shape);
2687 let mut attrs_str = try_opt!(field.attrs.rewrite(context, shape));
2688 if !attrs_str.is_empty() {
2689 attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2693 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2695 let expr_offset = shape.indent.block_indent(context.config);
2698 .rewrite(context, Shape::indented(expr_offset, context.config));
2704 expr_offset.to_string(&context.config),
2713 fn shape_from_fn_call_style(
2714 context: &RewriteContext,
2718 ) -> Option<Shape> {
2719 if context.use_block_indent() {
2723 .block_indent(context.config.tab_spaces())
2724 .with_max_width(context.config)
2727 shape.visual_indent(offset).sub_width(overhead)
2731 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2732 context: &RewriteContext,
2738 T: Rewrite + Spanned + ToExpr + 'a,
2740 let mut items = items.iter();
2741 // In case of length 1, need a trailing comma
2742 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2743 if items.len() == 1 {
2745 let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
2746 return items.next().unwrap().rewrite(context, nested_shape).map(
2747 |s| if context.config.spaces_within_parens() {
2748 format!("( {}, )", s)
2755 let list_lo = context.codemap.span_after(span, "(");
2756 let nested_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
2757 let items = itemize_list(
2761 |item| item.span().lo,
2762 |item| item.span().hi,
2763 |item| item.rewrite(context, nested_shape),
2765 span.hi - BytePos(1),
2767 let item_vec: Vec<_> = items.collect();
2768 let tactic = definitive_tactic(
2770 ListTactic::HorizontalVertical,
2774 let fmt = ListFormatting {
2777 trailing_separator: SeparatorTactic::Never,
2779 ends_with_newline: false,
2780 preserve_newline: false,
2781 config: context.config,
2783 let list_str = try_opt!(write_list(&item_vec, &fmt));
2785 if context.config.spaces_within_parens() && list_str.len() > 0 {
2786 Some(format!("( {} )", list_str))
2788 Some(format!("({})", list_str))
2792 pub fn rewrite_tuple<'a, T>(
2793 context: &RewriteContext,
2799 T: Rewrite + Spanned + ToExpr + 'a,
2801 debug!("rewrite_tuple {:?}", shape);
2802 if context.use_block_indent() {
2803 // We use the same rule as funcation call for rewriting tuple.
2804 let force_trailing_comma = if context.inside_macro {
2805 span_ends_with_comma(context, span)
2815 context.config.fn_call_width(),
2816 force_trailing_comma,
2819 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2823 pub fn rewrite_unary_prefix<R: Rewrite>(
2824 context: &RewriteContext,
2828 ) -> Option<String> {
2830 .rewrite(context, try_opt!(shape.offset_left(prefix.len())))
2831 .map(|r| format!("{}{}", prefix, r))
2834 // FIXME: this is probably not correct for multi-line Rewrites. we should
2835 // subtract suffix.len() from the last line budget, not the first!
2836 pub fn rewrite_unary_suffix<R: Rewrite>(
2837 context: &RewriteContext,
2841 ) -> Option<String> {
2843 .rewrite(context, try_opt!(shape.sub_width(suffix.len())))
2850 fn rewrite_unary_op(
2851 context: &RewriteContext,
2855 ) -> Option<String> {
2856 // For some reason, an UnOp is not spanned like BinOp!
2857 let operator_str = match *op {
2858 ast::UnOp::Deref => "*",
2859 ast::UnOp::Not => "!",
2860 ast::UnOp::Neg => "-",
2862 rewrite_unary_prefix(context, operator_str, expr, shape)
2865 fn rewrite_assignment(
2866 context: &RewriteContext,
2869 op: Option<&ast::BinOp>,
2871 ) -> Option<String> {
2872 let operator_str = match op {
2873 Some(op) => context.snippet(op.span),
2874 None => "=".to_owned(),
2877 // 1 = space between lhs and operator.
2878 let lhs_shape = try_opt!(shape.sub_width(operator_str.len() + 1));
2879 let lhs_str = format!(
2881 try_opt!(lhs.rewrite(context, lhs_shape)),
2885 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2888 // The left hand side must contain everything up to, and including, the
2889 // assignment operator.
2890 pub fn rewrite_assign_rhs<S: Into<String>>(
2891 context: &RewriteContext,
2895 ) -> Option<String> {
2896 let lhs = lhs.into();
2897 let last_line_width = last_line_width(&lhs) - if lhs.contains('\n') {
2898 shape.indent.width()
2902 // 1 = space between operator and rhs.
2903 let orig_shape = try_opt!(shape.offset_left(last_line_width + 1));
2904 let rhs = try_opt!(choose_rhs(
2908 ex.rewrite(context, orig_shape)
2914 context: &RewriteContext,
2917 orig_rhs: Option<String>,
2918 ) -> Option<String> {
2920 Some(ref new_str) if !new_str.contains('\n') => Some(format!(" {}", new_str)),
2922 // Expression did not fit on the same line as the identifier.
2923 // Try splitting the line and see if that works better.
2924 let new_shape = try_opt!(
2926 shape.block().indent.block_indent(context.config),
2928 ).sub_width(shape.rhs_overhead(context.config))
2930 let new_rhs = expr.rewrite(context, new_shape);
2931 let new_indent_str = &new_shape.indent.to_string(context.config);
2933 match (orig_rhs, new_rhs) {
2934 (Some(ref orig_rhs), Some(ref new_rhs)) if prefer_next_line(orig_rhs, new_rhs) => {
2935 Some(format!("\n{}{}", new_indent_str, new_rhs))
2937 (None, Some(ref new_rhs)) => Some(format!("\n{}{}", new_indent_str, new_rhs)),
2938 (None, None) => None,
2939 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2945 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {
2947 fn count_line_breaks(src: &str) -> usize {
2948 src.chars().filter(|&x| x == '\n').count()
2951 !next_line_rhs.contains('\n') ||
2952 count_line_breaks(orig_rhs) > count_line_breaks(next_line_rhs) + 1
2955 fn rewrite_expr_addrof(
2956 context: &RewriteContext,
2957 mutability: ast::Mutability,
2960 ) -> Option<String> {
2961 let operator_str = match mutability {
2962 ast::Mutability::Immutable => "&",
2963 ast::Mutability::Mutable => "&mut ",
2965 rewrite_unary_prefix(context, operator_str, expr, shape)
2969 fn to_expr(&self) -> Option<&ast::Expr>;
2970 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2973 impl ToExpr for ast::Expr {
2974 fn to_expr(&self) -> Option<&ast::Expr> {
2978 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2979 can_be_overflowed_expr(context, self, len)
2983 impl ToExpr for ast::Ty {
2984 fn to_expr(&self) -> Option<&ast::Expr> {
2988 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2989 can_be_overflowed_type(context, self, len)
2993 impl<'a> ToExpr for TuplePatField<'a> {
2994 fn to_expr(&self) -> Option<&ast::Expr> {
2998 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2999 can_be_overflowed_pat(context, self, len)
3003 impl<'a> ToExpr for ast::StructField {
3004 fn to_expr(&self) -> Option<&ast::Expr> {
3008 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {