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, 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(_) =
338 rewrite_single_line_block(context, "do catch ", block, shape)
343 let budget = shape.width.checked_sub(9).unwrap_or(0);
347 try_opt!(block.rewrite(&context, Shape::legacy(budget, shape.indent)))
353 .and_then(|expr_str| {
354 recover_comment_removed(expr_str, expr.span, context, shape)
356 .and_then(|expr_str| {
357 combine_attr_and_expr(context, shape, expr, &expr_str)
361 pub fn rewrite_pair<LHS, RHS>(
367 context: &RewriteContext,
374 // Get "full width" rhs and see if it fits on the current line. This
375 // usually works fairly well since it tends to place operands of
376 // operations with high precendence close together.
377 // Note that this is non-conservative, but its just to see if it's even
378 // worth trying to put everything on one line.
379 let rhs_shape = try_opt!(shape.sub_width(suffix.len()));
380 let rhs_orig_result = rhs.rewrite(context, rhs_shape);
382 if let Some(ref rhs_result) = rhs_orig_result {
383 // This is needed in case of line break not caused by a
384 // shortage of space, but by end-of-line comments, for example.
385 if !rhs_result.contains('\n') {
387 try_opt!(try_opt!(shape.offset_left(prefix.len())).sub_width(infix.len()));
388 let lhs_result = lhs.rewrite(context, lhs_shape);
389 if let Some(lhs_result) = lhs_result {
390 let mut result = format!("{}{}{}", prefix, lhs_result, infix);
392 let remaining_width = shape
394 .checked_sub(last_line_width(&result) + suffix.len())
397 if rhs_result.len() <= remaining_width {
398 result.push_str(&rhs_result);
399 result.push_str(suffix);
403 // Try rewriting the rhs into the remaining space.
404 let rhs_shape = shape.offset_left(last_line_width(&result) + suffix.len());
405 if let Some(rhs_shape) = rhs_shape {
406 if let Some(rhs_result) = rhs.rewrite(context, rhs_shape) {
407 // FIXME this should always hold.
408 if rhs_result.len() <= remaining_width {
409 result.push_str(&rhs_result);
410 result.push_str(suffix);
419 // We have to use multiple lines.
421 // Re-evaluate the rhs because we have more space now:
422 let sep = if infix.ends_with(' ') { " " } else { "" };
423 let infix = infix.trim_right();
424 let rhs_shape = match context.config.control_style() {
426 try_opt!(shape.sub_width(suffix.len() + prefix.len())).visual_indent(prefix.len())
429 // Try to calculate the initial constraint on the right hand side.
430 let rhs_overhead = shape.rhs_overhead(context.config);
432 Shape::indented(shape.indent.block_indent(context.config), context.config)
433 .sub_width(rhs_overhead)
437 let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape));
438 let lhs_overhead = shape.used_width() + prefix.len() + infix.len();
439 let lhs_shape = Shape {
440 width: try_opt!(context.config.max_width().checked_sub(lhs_overhead)),
443 let lhs_result = try_opt!(
444 lhs.rewrite(context, lhs_shape)
445 .map(|lhs_str| format!("{}{}{}", prefix, lhs_str, infix))
447 if let Some(ref rhs_str) = rhs_orig_result {
448 if rhs_str.lines().count() <= rhs_result.lines().count() &&
452 .map_or(false, |first_line| first_line.ends_with('{')) &&
453 last_line_width(&lhs_result) + sep.len() + first_line_width(rhs_str) <= shape.width
455 return Some(format!("{}{}{}{}", lhs_result, sep, rhs_str, suffix));
461 rhs_shape.indent.to_string(context.config),
467 pub fn rewrite_array<'a, I>(
470 context: &RewriteContext,
472 trailing_comma: bool,
475 I: Iterator<Item = &'a ast::Expr>,
477 let bracket_size = if context.config.spaces_within_square_brackets() {
483 let mut nested_shape = match context.config.array_layout() {
484 IndentStyle::Block => try_opt!(
487 .block_indent(context.config.tab_spaces())
488 .with_max_width(context.config)
491 IndentStyle::Visual => try_opt!(
493 .visual_indent(bracket_size)
494 .sub_width(bracket_size * 2)
498 let items = itemize_list(
504 |item| item.rewrite(context, nested_shape),
507 ).collect::<Vec<_>>();
509 if items.is_empty() {
510 if context.config.spaces_within_square_brackets() {
511 return Some("[ ]".to_string());
513 return Some("[]".to_string());
517 let has_long_item = items
519 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
521 let mut tactic = match context.config.array_layout() {
522 IndentStyle::Block => {
523 // FIXME wrong shape in one-line case
524 match shape.width.checked_sub(2 * bracket_size) {
527 ListTactic::LimitedHorizontalVertical(context.config.array_width());
528 definitive_tactic(&items, tactic, width)
530 None => DefinitiveListTactic::Vertical,
533 IndentStyle::Visual => if has_long_item || items.iter().any(ListItem::is_multiline) {
536 ListTactic::LimitedHorizontalVertical(context.config.array_width()),
540 DefinitiveListTactic::Mixed
543 let mut ends_with_newline = tactic.ends_with_newline(context.config.array_layout());
544 if context.config.array_horizontal_layout_threshold() > 0 &&
545 items.len() > context.config.array_horizontal_layout_threshold()
547 tactic = DefinitiveListTactic::Mixed;
548 ends_with_newline = false;
549 if context.config.array_layout() == IndentStyle::Block {
550 nested_shape = try_opt!(
552 .visual_indent(bracket_size)
553 .sub_width(bracket_size * 2)
558 let fmt = ListFormatting {
561 trailing_separator: if trailing_comma {
562 SeparatorTactic::Always
563 } else if context.inside_macro || context.config.array_layout() == IndentStyle::Visual {
564 SeparatorTactic::Never
566 SeparatorTactic::Vertical
569 ends_with_newline: ends_with_newline,
570 config: context.config,
572 let list_str = try_opt!(write_list(&items, &fmt));
574 let result = if context.config.array_layout() == IndentStyle::Visual ||
575 tactic != DefinitiveListTactic::Vertical
577 if context.config.spaces_within_square_brackets() && list_str.len() > 0 {
578 format!("[ {} ]", list_str)
580 format!("[{}]", list_str)
585 nested_shape.indent.to_string(context.config),
587 shape.block().indent.to_string(context.config)
594 // Return type is (prefix, extra_offset)
595 fn rewrite_closure_fn_decl(
596 capture: ast::CaptureBy,
597 fn_decl: &ast::FnDecl,
600 context: &RewriteContext,
602 ) -> Option<(String, usize)> {
603 let mover = if capture == ast::CaptureBy::Value {
608 // 4 = "|| {".len(), which is overconservative when the closure consists of
609 // a single expression.
610 let nested_shape = try_opt!(try_opt!(shape.shrink_left(mover.len())).sub_width(4));
613 let argument_offset = nested_shape.indent + 1;
614 let arg_shape = try_opt!(nested_shape.offset_left(1)).visual_indent(0);
615 let ret_str = try_opt!(fn_decl.output.rewrite(context, arg_shape));
617 let arg_items = itemize_list(
619 fn_decl.inputs.iter(),
621 |arg| span_lo_for_arg(arg),
622 |arg| span_hi_for_arg(context, arg),
623 |arg| arg.rewrite(context, arg_shape),
624 context.codemap.span_after(span, "|"),
627 let item_vec = arg_items.collect::<Vec<_>>();
628 // 1 = space between arguments and return type.
629 let horizontal_budget = nested_shape
631 .checked_sub(ret_str.len() + 1)
633 let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
634 let arg_shape = match tactic {
635 DefinitiveListTactic::Horizontal => try_opt!(arg_shape.sub_width(ret_str.len() + 1)),
639 let fmt = ListFormatting {
642 trailing_separator: SeparatorTactic::Never,
644 ends_with_newline: false,
645 config: context.config,
647 let list_str = try_opt!(write_list(&item_vec, &fmt));
648 let mut prefix = format!("{}|{}|", mover, list_str);
649 // 1 = space between `|...|` and body.
650 let extra_offset = extra_offset(&prefix, shape) + 1;
652 if !ret_str.is_empty() {
653 if prefix.contains('\n') {
655 prefix.push_str(&argument_offset.to_string(context.config));
659 prefix.push_str(&ret_str);
662 Some((prefix, extra_offset))
665 // This functions is pretty messy because of the rules around closures and blocks:
666 // FIXME - the below is probably no longer true in full.
667 // * if there is a return type, then there must be braces,
668 // * given a closure with braces, whether that is parsed to give an inner block
669 // or not depends on if there is a return type and if there are statements
671 // * if the first expression in the body ends with a block (i.e., is a
672 // statement without needing a semi-colon), then adding or removing braces
673 // can change whether it is treated as an expression or statement.
675 capture: ast::CaptureBy,
676 fn_decl: &ast::FnDecl,
679 context: &RewriteContext,
681 ) -> Option<String> {
682 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
690 // 1 = space between `|...|` and body.
691 let body_shape = try_opt!(shape.offset_left(extra_offset));
693 if let ast::ExprKind::Block(ref block) = body.node {
694 // The body of the closure is an empty block.
695 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
696 return Some(format!("{} {{}}", prefix));
699 // Figure out if the block is necessary.
700 let needs_block = block.rules != ast::BlockCheckMode::Default ||
701 block.stmts.len() > 1 || context.inside_macro ||
702 block_contains_comment(block, context.codemap) ||
703 prefix.contains('\n');
705 let no_return_type = if let ast::FunctionRetTy::Default(_) = fn_decl.output {
710 if no_return_type && !needs_block {
711 // lock.stmts.len() == 1
712 if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
713 if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
720 // We need braces, but we might still prefer a one-liner.
721 let stmt = &block.stmts[0];
722 // 4 = braces and spaces.
723 if let Some(body_shape) = body_shape.sub_width(4) {
724 // Checks if rewrite succeeded and fits on a single line.
725 if let Some(rewrite) = and_one_line(stmt.rewrite(context, body_shape)) {
726 return Some(format!("{} {{ {} }}", prefix, rewrite));
731 // Either we require a block, or tried without and failed.
732 rewrite_closure_block(&block, &prefix, context, body_shape)
734 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
735 // The closure originally had a non-block expression, but we can't fit on
736 // one line, so we'll insert a block.
737 rewrite_closure_with_block(context, body_shape, &prefix, body)
742 // Rewrite closure with a single expression wrapping its body with block.
743 fn rewrite_closure_with_block(
744 context: &RewriteContext,
748 ) -> Option<String> {
749 let block = ast::Block {
752 id: ast::NodeId::new(0),
753 node: ast::StmtKind::Expr(ptr::P(body.clone())),
757 id: ast::NodeId::new(0),
758 rules: ast::BlockCheckMode::Default,
761 rewrite_closure_block(&block, prefix, context, shape)
764 // Rewrite closure with a single expression without wrapping its body with block.
765 fn rewrite_closure_expr(
768 context: &RewriteContext,
770 ) -> Option<String> {
771 let mut rewrite = expr.rewrite(context, shape);
772 if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
773 rewrite = and_one_line(rewrite);
775 rewrite.map(|rw| format!("{} {}", prefix, rw))
778 // Rewrite closure whose body is block.
779 fn rewrite_closure_block(
782 context: &RewriteContext,
784 ) -> Option<String> {
785 // Start with visual indent, then fall back to block indent if the
787 let block_threshold = context.config.closure_block_indent_threshold();
788 if block_threshold >= 0 {
789 if let Some(block_str) = block.rewrite(&context, shape) {
790 if block_str.matches('\n').count() <= block_threshold as usize &&
791 !need_block_indent(&block_str, shape)
793 if let Some(block_str) = block_str.rewrite(context, shape) {
794 return Some(format!("{} {}", prefix, block_str));
800 // The body of the closure is big enough to be block indented, that
801 // means we must re-format.
802 let block_shape = shape.block();
803 let block_str = try_opt!(block.rewrite(&context, block_shape));
804 Some(format!("{} {}", prefix, block_str))
807 fn and_one_line(x: Option<String>) -> Option<String> {
808 x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
811 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
812 debug!("nop_block_collapse {:?} {}", block_str, budget);
813 block_str.map(|block_str| {
814 if block_str.starts_with('{') && budget >= 2 &&
815 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
824 fn rewrite_empty_block(
825 context: &RewriteContext,
828 ) -> Option<String> {
829 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) &&
832 return Some("{}".to_owned());
835 // If a block contains only a single-line comment, then leave it on one line.
836 let user_str = context.snippet(block.span);
837 let user_str = user_str.trim();
838 if user_str.starts_with('{') && user_str.ends_with('}') {
839 let comment_str = user_str[1..user_str.len() - 1].trim();
840 if block.stmts.is_empty() && !comment_str.contains('\n') &&
841 !comment_str.starts_with("//") && comment_str.len() + 4 <= shape.width
843 return Some(format!("{{ {} }}", comment_str));
850 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
851 Some(match block.rules {
852 ast::BlockCheckMode::Unsafe(..) => {
853 let snippet = context.snippet(block.span);
854 let open_pos = try_opt!(snippet.find_uncommented("{"));
855 // Extract comment between unsafe and block start.
856 let trimmed = &snippet[6..open_pos].trim();
858 if !trimmed.is_empty() {
859 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
860 let budget = try_opt!(shape.width.checked_sub(9));
863 try_opt!(rewrite_comment(
866 Shape::legacy(budget, shape.indent + 7),
874 ast::BlockCheckMode::Default => String::new(),
878 fn rewrite_single_line_block(
879 context: &RewriteContext,
883 ) -> Option<String> {
884 if is_simple_block(block, context.codemap) {
885 let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
886 let expr_str = try_opt!(block.stmts[0].rewrite(context, expr_shape));
887 let result = format!("{}{{ {} }}", prefix, expr_str);
888 if result.len() <= shape.width && !result.contains('\n') {
895 fn rewrite_block_with_visitor(
896 context: &RewriteContext,
900 ) -> Option<String> {
901 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
905 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
906 visitor.block_indent = shape.indent;
907 visitor.is_if_else_block = context.is_if_else_block;
909 ast::BlockCheckMode::Unsafe(..) => {
910 let snippet = context.snippet(block.span);
911 let open_pos = try_opt!(snippet.find_uncommented("{"));
912 visitor.last_pos = block.span.lo + BytePos(open_pos as u32)
914 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo,
917 visitor.visit_block(block, None);
918 Some(format!("{}{}", prefix, visitor.buffer))
921 impl Rewrite for ast::Block {
922 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
923 // shape.width is used only for the single line case: either the empty block `{}`,
924 // or an unsafe expression `unsafe { e }`.
925 if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
929 let prefix = try_opt!(block_prefix(context, self, shape));
930 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
934 rewrite_block_with_visitor(context, &prefix, self, shape)
938 impl Rewrite for ast::Stmt {
939 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
940 let result = match self.node {
941 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
942 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
943 let suffix = if semicolon_for_stmt(context, self) {
952 ast::StmtKind::Expr(_) => ExprType::SubExpression,
953 ast::StmtKind::Semi(_) => ExprType::Statement,
957 try_opt!(shape.sub_width(suffix.len())),
958 ).map(|s| s + suffix)
960 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
962 result.and_then(|res| {
963 recover_comment_removed(res, self.span(), context, shape)
968 // Rewrite condition if the given expression has one.
969 fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
971 ast::ExprKind::Match(ref cond, _) => {
973 let cond_shape = match context.config.control_style() {
974 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
975 Style::Rfc => try_opt!(shape.offset_left(8)),
977 cond.rewrite(context, cond_shape)
979 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
980 stmt_expr(&block.stmts[0]).and_then(|e| rewrite_cond(context, e, shape))
982 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
984 String::from("\n") + &shape.indent.block_only().to_string(context.config);
986 .rewrite_cond(context, shape, &alt_block_sep)
987 .and_then(|rw| Some(rw.0))
992 // Abstraction over control flow expressions
994 struct ControlFlow<'a> {
995 cond: Option<&'a ast::Expr>,
996 block: &'a ast::Block,
997 else_block: Option<&'a ast::Expr>,
998 label: Option<ast::SpannedIdent>,
999 pat: Option<&'a ast::Pat>,
1003 allow_single_line: bool,
1004 // True if this is an `if` expression in an `else if` :-( hacky
1009 fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'a>> {
1011 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
1015 else_block.as_ref().map(|e| &**e),
1016 expr_type == ExprType::SubExpression,
1020 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
1021 Some(ControlFlow::new_if(
1025 else_block.as_ref().map(|e| &**e),
1026 expr_type == ExprType::SubExpression,
1031 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
1032 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
1034 ast::ExprKind::Loop(ref block, label) => {
1035 Some(ControlFlow::new_loop(block, label, expr.span))
1037 ast::ExprKind::While(ref cond, ref block, label) => {
1038 Some(ControlFlow::new_while(None, cond, block, label, expr.span))
1040 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
1041 ControlFlow::new_while(Some(pat), cond, block, label, expr.span),
1047 impl<'a> ControlFlow<'a> {
1049 cond: &'a ast::Expr,
1050 pat: Option<&'a ast::Pat>,
1051 block: &'a ast::Block,
1052 else_block: Option<&'a ast::Expr>,
1053 allow_single_line: bool,
1056 ) -> ControlFlow<'a> {
1060 else_block: else_block,
1064 matcher: match pat {
1069 allow_single_line: allow_single_line,
1070 nested_if: nested_if,
1076 block: &'a ast::Block,
1077 label: Option<ast::SpannedIdent>,
1079 ) -> ControlFlow<'a> {
1089 allow_single_line: false,
1096 pat: Option<&'a ast::Pat>,
1097 cond: &'a ast::Expr,
1098 block: &'a ast::Block,
1099 label: Option<ast::SpannedIdent>,
1101 ) -> ControlFlow<'a> {
1109 matcher: match pat {
1114 allow_single_line: false,
1122 cond: &'a ast::Expr,
1123 block: &'a ast::Block,
1124 label: Option<ast::SpannedIdent>,
1126 ) -> ControlFlow<'a> {
1136 allow_single_line: false,
1142 fn rewrite_single_line(
1145 context: &RewriteContext,
1147 ) -> Option<String> {
1148 assert!(self.allow_single_line);
1149 let else_block = try_opt!(self.else_block);
1150 let fixed_cost = self.keyword.len() + " { } else { }".len();
1152 if let ast::ExprKind::Block(ref else_node) = else_block.node {
1153 if !is_simple_block(self.block, context.codemap) ||
1154 !is_simple_block(else_node, context.codemap) ||
1155 pat_expr_str.contains('\n')
1160 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
1161 let expr = &self.block.stmts[0];
1162 let if_str = try_opt!(expr.rewrite(
1164 Shape::legacy(new_width, Indent::empty()),
1167 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
1168 let else_expr = &else_node.stmts[0];
1170 try_opt!(else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
1172 if if_str.contains('\n') || else_str.contains('\n') {
1176 let result = format!(
1177 "{} {} {{ {} }} else {{ {} }}",
1184 if result.len() <= width {
1185 return Some(result);
1193 impl<'a> ControlFlow<'a> {
1196 context: &RewriteContext,
1198 alt_block_sep: &str,
1199 ) -> Option<(String, usize)> {
1200 let constr_shape = if self.nested_if {
1201 // We are part of an if-elseif-else chain. Our constraints are tightened.
1202 // 7 = "} else " .len()
1203 try_opt!(shape.offset_left(7))
1208 let label_string = rewrite_label(self.label);
1209 // 1 = space after keyword.
1210 let offset = self.keyword.len() + label_string.len() + 1;
1212 let pat_expr_string = match self.cond {
1214 let cond_shape = match context.config.control_style() {
1215 Style::Legacy => try_opt!(constr_shape.shrink_left(offset)),
1216 Style::Rfc => try_opt!(constr_shape.offset_left(offset)),
1218 try_opt!(rewrite_pat_expr(
1228 None => String::new(),
1231 let brace_overhead =
1232 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1238 let one_line_budget = context
1241 .checked_sub(constr_shape.used_width() + offset + brace_overhead)
1243 let force_newline_brace = context.config.control_style() == Style::Rfc &&
1244 (pat_expr_string.contains('\n') || pat_expr_string.len() > one_line_budget) &&
1245 !last_line_extendable(&pat_expr_string);
1247 // Try to format if-else on single line.
1248 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1249 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1251 if let Some(cond_str) = trial {
1252 if cond_str.len() <= context.config.single_line_if_else_max_width() {
1253 return Some((cond_str, 0));
1258 let cond_span = if let Some(cond) = self.cond {
1261 mk_sp(self.block.span.lo, self.block.span.lo)
1264 // for event in event
1265 let between_kwd_cond = mk_sp(
1266 context.codemap.span_after(self.span, self.keyword.trim()),
1269 |p| if self.matcher.is_empty() {
1272 context.codemap.span_before(self.span, self.matcher.trim())
1277 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1279 let after_cond_comment =
1280 extract_comment(mk_sp(cond_span.hi, self.block.span.lo), context, shape);
1282 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1284 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine ||
1292 let used_width = if pat_expr_string.contains('\n') {
1293 last_line_width(&pat_expr_string)
1295 // 2 = spaces after keyword and condition.
1296 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1304 between_kwd_cond_comment.as_ref().map_or(
1305 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1313 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1320 impl<'a> Rewrite for ControlFlow<'a> {
1321 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1322 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1325 String::from("\n") + &shape.indent.block_only().to_string(context.config);
1326 let (cond_str, used_width) = try_opt!(self.rewrite_cond(context, shape, &alt_block_sep));
1327 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1328 if used_width == 0 {
1329 return Some(cond_str);
1332 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1333 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1334 // we should avoid the single line case.
1335 let block_width = if self.else_block.is_some() || self.nested_if {
1340 let block_shape = Shape {
1344 let mut block_context = context.clone();
1345 block_context.is_if_else_block = self.else_block.is_some();
1346 let block_str = try_opt!(rewrite_block_with_visitor(
1353 let mut result = format!("{}{}", cond_str, block_str);
1355 if let Some(else_block) = self.else_block {
1356 let shape = Shape::indented(shape.indent, context.config);
1357 let mut last_in_chain = false;
1358 let rewrite = match else_block.node {
1359 // If the else expression is another if-else expression, prevent it
1360 // from being formatted on a single line.
1361 // Note how we're passing the original shape, as the
1362 // cost of "else" should not cascade.
1363 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1364 ControlFlow::new_if(
1368 next_else_block.as_ref().map(|e| &**e),
1371 mk_sp(else_block.span.lo, self.span.hi),
1372 ).rewrite(context, shape)
1374 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1375 ControlFlow::new_if(
1379 next_else_block.as_ref().map(|e| &**e),
1382 mk_sp(else_block.span.lo, self.span.hi),
1383 ).rewrite(context, shape)
1386 last_in_chain = true;
1387 // When rewriting a block, the width is only used for single line
1388 // blocks, passing 1 lets us avoid that.
1389 let else_shape = Shape {
1390 width: min(1, shape.width),
1393 format_expr(else_block, ExprType::Statement, context, else_shape)
1397 let between_kwd_else_block = mk_sp(
1401 .span_before(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1403 let between_kwd_else_block_comment =
1404 extract_comment(between_kwd_else_block, context, shape);
1406 let after_else = mk_sp(
1409 .span_after(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1412 let after_else_comment = extract_comment(after_else, context, shape);
1414 let between_sep = match context.config.control_brace_style() {
1415 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1418 ControlBraceStyle::AlwaysSameLine => " ",
1420 let after_sep = match context.config.control_brace_style() {
1421 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1428 between_kwd_else_block_comment
1430 .map_or(between_sep, |s| &**s),
1431 after_else_comment.as_ref().map_or(after_sep, |s| &**s)
1434 result.push_str(&try_opt!(rewrite));
1441 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
1443 Some(ident) => format!("{}: ", ident.node),
1444 None => "".to_owned(),
1448 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1449 let comment_str = context.snippet(span);
1450 if contains_comment(&comment_str) {
1451 let comment = try_opt!(rewrite_comment(
1458 "\n{indent}{}\n{indent}",
1460 indent = shape.indent.to_string(context.config)
1467 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1468 let snippet = codemap.span_to_snippet(block.span).unwrap();
1469 contains_comment(&snippet)
1472 // Checks that a block contains no statements, an expression and no comments.
1473 // FIXME: incorrectly returns false when comment is contained completely within
1475 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1476 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) &&
1477 !block_contains_comment(block, codemap))
1480 /// Checks whether a block contains at most one statement or expression, and no comments.
1481 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1482 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1485 /// Checks whether a block contains no statements, expressions, or comments.
1486 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1487 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1490 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1492 ast::StmtKind::Expr(..) => true,
1497 fn is_unsafe_block(block: &ast::Block) -> bool {
1498 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1505 // inter-match-arm-comment-rules:
1506 // - all comments following a match arm before the start of the next arm
1507 // are about the second arm
1508 fn rewrite_match_arm_comment(
1509 context: &RewriteContext,
1512 arm_indent_str: &str,
1513 ) -> Option<String> {
1514 // The leading "," is not part of the arm-comment
1515 let missed_str = match missed_str.find_uncommented(",") {
1516 Some(n) => &missed_str[n + 1..],
1517 None => &missed_str[..],
1520 let mut result = String::new();
1521 // any text not preceeded by a newline is pushed unmodified to the block
1522 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
1523 result.push_str(&missed_str[..first_brk]);
1524 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
1526 let first = missed_str
1527 .find(|c: char| !c.is_whitespace())
1528 .unwrap_or(missed_str.len());
1529 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
1530 // Excessive vertical whitespace before comment should be preserved
1531 // FIXME handle vertical whitespace better
1534 let missed_str = missed_str[first..].trim();
1535 if !missed_str.is_empty() {
1536 let comment = try_opt!(rewrite_comment(&missed_str, false, shape, context.config));
1538 result.push_str(arm_indent_str);
1539 result.push_str(&comment);
1546 context: &RewriteContext,
1551 ) -> Option<String> {
1552 if arms.is_empty() {
1556 // 6 = `match `, 2 = ` {`
1557 let cond_shape = match context.config.control_style() {
1558 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
1559 Style::Rfc => try_opt!(shape.offset_left(6).and_then(|s| s.sub_width(2))),
1561 let cond_str = try_opt!(cond.rewrite(context, cond_shape));
1562 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1563 let block_sep = match context.config.control_brace_style() {
1564 ControlBraceStyle::AlwaysNextLine => &alt_block_sep,
1565 _ if last_line_extendable(&cond_str) => " ",
1566 _ if cond_str.contains('\n') => &alt_block_sep,
1571 "match {}{}{{{}\n{}}}",
1574 try_opt!(rewrite_match_arms(context, arms, shape, span, cond.span.hi)),
1575 shape.indent.to_string(context.config),
1579 fn arm_comma(config: &Config, body: &ast::Expr) -> &'static str {
1580 if config.match_block_trailing_comma() {
1582 } else if let ast::ExprKind::Block(ref block) = body.node {
1583 if let ast::BlockCheckMode::Default = block.rules {
1593 fn rewrite_match_arms(
1594 context: &RewriteContext,
1598 cond_end_pos: BytePos,
1599 ) -> Option<String> {
1600 let mut result = String::new();
1602 let arm_shape = if context.config.indent_match_arms() {
1603 shape.block_indent(context.config.tab_spaces())
1605 shape.block_indent(0)
1606 }.with_max_width(context.config);
1607 let arm_indent_str = arm_shape.indent.to_string(context.config);
1609 let open_brace_pos = context
1611 .span_after(mk_sp(cond_end_pos, arms[0].span().lo), "{");
1613 let arm_num = arms.len();
1614 for (i, arm) in arms.iter().enumerate() {
1615 // Make sure we get the stuff between arms.
1616 let missed_str = if i == 0 {
1617 context.snippet(mk_sp(open_brace_pos, arm.span().lo))
1619 context.snippet(mk_sp(arms[i - 1].span().hi, arm.span().lo))
1621 let comment = try_opt!(rewrite_match_arm_comment(
1627 result.push_str(&comment);
1629 result.push_str(&arm_indent_str);
1631 let arm_str = rewrite_match_arm(context, arm, arm_shape);
1632 if let Some(ref arm_str) = arm_str {
1633 // Trim the trailing comma if necessary.
1634 if i == arm_num - 1 && context.config.trailing_comma() == SeparatorTactic::Never &&
1635 arm_str.ends_with(',')
1637 result.push_str(&arm_str[0..arm_str.len() - 1])
1639 result.push_str(arm_str)
1642 // We couldn't format the arm, just reproduce the source.
1643 let snippet = context.snippet(arm.span());
1644 result.push_str(&snippet);
1645 if context.config.trailing_comma() != SeparatorTactic::Never {
1646 result.push_str(arm_comma(context.config, &arm.body))
1650 // BytePos(1) = closing match brace.
1651 let last_span = mk_sp(arms[arms.len() - 1].span().hi, span.hi - BytePos(1));
1652 let last_comment = context.snippet(last_span);
1653 let comment = try_opt!(rewrite_match_arm_comment(
1659 result.push_str(&comment);
1664 fn rewrite_match_arm(context: &RewriteContext, arm: &ast::Arm, shape: Shape) -> Option<String> {
1665 let attr_str = if !arm.attrs.is_empty() {
1666 if contains_skip(&arm.attrs) {
1671 try_opt!(arm.attrs.rewrite(context, shape)),
1672 shape.indent.to_string(context.config)
1677 let pats_str = try_opt!(rewrite_match_pattern(context, &arm.pats, &arm.guard, shape));
1678 let pats_str = attr_str + &pats_str;
1679 rewrite_match_body(context, &arm.body, &pats_str, shape, arm.guard.is_some())
1682 fn rewrite_match_pattern(
1683 context: &RewriteContext,
1684 pats: &Vec<ptr::P<ast::Pat>>,
1685 guard: &Option<ptr::P<ast::Expr>>,
1687 ) -> Option<String> {
1690 let pat_shape = try_opt!(shape.sub_width(5));
1692 let pat_strs = try_opt!(
1694 .map(|p| p.rewrite(context, pat_shape))
1695 .collect::<Option<Vec<_>>>()
1698 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1699 let tactic = definitive_tactic(&items, ListTactic::HorizontalVertical, pat_shape.width);
1700 let fmt = ListFormatting {
1703 trailing_separator: SeparatorTactic::Never,
1705 ends_with_newline: false,
1706 config: context.config,
1708 let pats_str = try_opt!(write_list(&items, &fmt));
1711 let guard_str = try_opt!(rewrite_guard(
1715 trimmed_last_line_width(&pats_str),
1718 Some(format!("{}{}", pats_str, guard_str))
1721 fn rewrite_match_body(
1722 context: &RewriteContext,
1723 body: &ptr::P<ast::Expr>,
1727 ) -> Option<String> {
1728 let (extend, body) = match body.node {
1729 ast::ExprKind::Block(ref block)
1730 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) =>
1732 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1733 (expr.can_be_overflowed(context, 1), &**expr)
1738 _ => (body.can_be_overflowed(context, 1), &**body),
1741 let comma = arm_comma(&context.config, body);
1742 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1743 let alt_block_sep = alt_block_sep.as_str();
1744 let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
1745 (true, is_empty_block(block, context.codemap))
1750 let combine_orig_body = |body_str: &str| {
1751 let block_sep = match context.config.control_brace_style() {
1752 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
1756 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
1759 let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
1760 let next_line_indent = if is_block {
1763 shape.indent.block_indent(context.config)
1765 let combine_next_line_body = |body_str: &str| {
1767 return Some(format!(
1770 next_line_indent.to_string(context.config),
1775 let indent_str = shape.indent.to_string(context.config);
1776 let nested_indent_str = next_line_indent.to_string(context.config);
1777 let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1778 let comma = if context.config.match_block_trailing_comma() {
1783 ("{", format!("\n{}}}{}", indent_str, comma))
1785 ("", String::from(","))
1788 let block_sep = match context.config.control_brace_style() {
1789 ControlBraceStyle::AlwaysNextLine => format!("{}{}\n", alt_block_sep, body_prefix),
1790 _ if body_prefix.is_empty() => "\n".to_owned(),
1791 _ if forbid_same_line => format!("{}{}\n", alt_block_sep, body_prefix),
1792 _ => format!(" {}\n", body_prefix),
1793 } + &nested_indent_str;
1804 // Let's try and get the arm body on the same line as the condition.
1806 let orig_body_shape = shape
1807 .offset_left(extra_offset(&pats_str, shape) + 4)
1808 .and_then(|shape| shape.sub_width(comma.len()));
1809 let orig_body = if let Some(body_shape) = orig_body_shape {
1810 let rewrite = nop_block_collapse(
1811 format_expr(body, ExprType::Statement, context, body_shape),
1817 if !forbid_same_line &&
1819 (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
1821 return combine_orig_body(body_str);
1828 let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
1830 // Try putting body on the next line and see if it looks better.
1831 let next_line_body_shape = Shape::indented(next_line_indent, context.config);
1832 let next_line_body = nop_block_collapse(
1833 format_expr(body, ExprType::Statement, context, next_line_body_shape),
1834 next_line_body_shape.width,
1836 match (orig_body, next_line_body) {
1837 (Some(ref orig_str), Some(ref next_line_str))
1838 if forbid_same_line || prefer_next_line(orig_str, next_line_str) =>
1840 combine_next_line_body(next_line_str)
1842 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
1843 combine_orig_body(orig_str)
1845 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
1846 combine_next_line_body(next_line_str)
1848 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
1849 (None, None) => None,
1850 (Some(ref orig_str), _) => combine_orig_body(orig_str),
1854 // The `if ...` guard on a match arm.
1856 context: &RewriteContext,
1857 guard: &Option<ptr::P<ast::Expr>>,
1859 // The amount of space used up on this line for the pattern in
1860 // the arm (excludes offset).
1861 pattern_width: usize,
1862 ) -> Option<String> {
1863 if let Some(ref guard) = *guard {
1864 // First try to fit the guard string on the same line as the pattern.
1865 // 4 = ` if `, 5 = ` => {`
1866 let cond_shape = shape
1867 .offset_left(pattern_width + 4)
1868 .and_then(|s| s.sub_width(5));
1869 if let Some(cond_shape) = cond_shape {
1870 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1871 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
1872 return Some(format!(" if {}", cond_str));
1877 // Not enough space to put the guard after the pattern, try a newline.
1878 // 3 = `if `, 5 = ` => {`
1879 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
1881 .and_then(|s| s.sub_width(5));
1882 if let Some(cond_shape) = cond_shape {
1883 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1884 return Some(format!(
1886 cond_shape.indent.to_string(context.config),
1898 fn rewrite_pat_expr(
1899 context: &RewriteContext,
1900 pat: Option<&ast::Pat>,
1903 // Connecting piece between pattern and expression,
1904 // *without* trailing space.
1908 ) -> Option<String> {
1909 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1910 if let Some(pat) = pat {
1911 let matcher = if matcher.is_empty() {
1914 format!("{} ", matcher)
1917 try_opt!(try_opt!(shape.offset_left(matcher.len())).sub_width(connector.len()));
1918 let pat_string = try_opt!(pat.rewrite(context, pat_shape));
1919 let result = format!("{}{}{}", matcher, pat_string, connector);
1920 return rewrite_assign_rhs(context, result, expr, shape);
1923 let expr_rw = expr.rewrite(context, shape);
1924 // The expression may (partially) fit on the current line.
1925 // We do not allow splitting between `if` and condition.
1926 if keyword == "if" || expr_rw.is_some() {
1930 // The expression won't fit on the current line, jump to next.
1931 let nested_shape = shape
1932 .block_indent(context.config.tab_spaces())
1933 .with_max_width(context.config);
1934 let nested_indent_str = nested_shape.indent.to_string(context.config);
1935 expr.rewrite(context, nested_shape)
1936 .map(|expr_rw| format!("\n{}{}", nested_indent_str, expr_rw))
1939 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1940 let string_lit = context.snippet(span);
1942 if !context.config.format_strings() && !context.config.force_format_strings() {
1947 .all(|line| line.ends_with('\\'))
1949 let new_indent = shape.visual_indent(1).indent;
1950 return Some(String::from(
1954 new_indent.to_string(context.config) + line.trim_left()
1956 .collect::<Vec<_>>()
1961 return Some(string_lit);
1965 if !context.config.force_format_strings() &&
1966 !string_requires_rewrite(context, span, &string_lit, shape)
1968 return Some(string_lit);
1971 let fmt = StringFormat {
1978 config: context.config,
1981 // Remove the quote characters.
1982 let str_lit = &string_lit[1..string_lit.len() - 1];
1984 rewrite_string(str_lit, &fmt)
1987 fn string_requires_rewrite(
1988 context: &RewriteContext,
1993 if context.codemap.lookup_char_pos(span.lo).col.0 != shape.indent.width() {
1997 for (i, line) in string.lines().enumerate() {
1999 if line.len() > shape.width {
2003 if line.len() > shape.width + shape.indent.width() {
2012 pub fn rewrite_call_with_binary_search<R>(
2013 context: &RewriteContext,
2015 args: &[&ast::Expr],
2022 let force_trailing_comma = if context.inside_macro {
2023 span_ends_with_comma(context, span)
2027 let closure = |callee_max_width| {
2028 // FIXME using byte lens instead of char lens (and probably all over the
2030 let callee_shape = Shape {
2031 width: callee_max_width,
2034 let callee_str = callee
2035 .rewrite(context, callee_shape)
2036 .ok_or(Ordering::Greater)?;
2044 context.config.fn_call_width(),
2045 force_trailing_comma,
2049 binary_search(1, shape.width, closure)
2052 pub fn rewrite_call(
2053 context: &RewriteContext,
2055 args: &[ptr::P<ast::Expr>],
2058 ) -> Option<String> {
2059 let force_trailing_comma = if context.inside_macro {
2060 span_ends_with_comma(context, span)
2067 &args.iter().map(|x| &**x).collect::<Vec<_>>(),
2070 context.config.fn_call_width(),
2071 force_trailing_comma,
2075 pub fn rewrite_call_inner<'a, T>(
2076 context: &RewriteContext,
2081 args_max_width: usize,
2082 force_trailing_comma: bool,
2083 ) -> Result<String, Ordering>
2085 T: Rewrite + Spanned + ToExpr + 'a,
2087 // 2 = `( `, 1 = `(`
2088 let paren_overhead = if context.config.spaces_within_parens() {
2093 let used_width = extra_offset(&callee_str, shape);
2094 let one_line_width = shape
2096 .checked_sub(used_width + 2 * paren_overhead)
2097 .ok_or(Ordering::Greater)?;
2099 let nested_shape = shape_from_fn_call_style(
2102 used_width + 2 * paren_overhead,
2103 used_width + paren_overhead,
2104 ).ok_or(Ordering::Greater)?;
2106 let span_lo = context.codemap.span_after(span, "(");
2107 let args_span = mk_sp(span_lo, span.hi);
2109 let (extendable, list_str) = rewrite_call_args(
2116 force_trailing_comma,
2117 ).ok_or(Ordering::Less)?;
2119 if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
2120 let mut new_context = context.clone();
2121 new_context.use_block = true;
2122 return rewrite_call_inner(
2129 force_trailing_comma,
2133 let args_shape = shape
2134 .sub_width(last_line_width(&callee_str))
2135 .ok_or(Ordering::Less)?;
2139 wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2143 fn need_block_indent(s: &str, shape: Shape) -> bool {
2144 s.lines().skip(1).any(|s| {
2145 s.find(|c| !char::is_whitespace(c))
2146 .map_or(false, |w| w + 1 < shape.indent.width())
2150 fn rewrite_call_args<'a, T>(
2151 context: &RewriteContext,
2155 one_line_width: usize,
2156 args_max_width: usize,
2157 force_trailing_comma: bool,
2158 ) -> Option<(bool, String)>
2160 T: Rewrite + Spanned + ToExpr + 'a,
2162 let items = itemize_list(
2166 |item| item.span().lo,
2167 |item| item.span().hi,
2168 |item| item.rewrite(context, shape),
2172 let mut item_vec: Vec<_> = items.collect();
2174 // Try letting the last argument overflow to the next line with block
2175 // indentation. If its first line fits on one line with the other arguments,
2176 // we format the function arguments horizontally.
2177 let tactic = try_overflow_last_arg(
2186 let fmt = ListFormatting {
2189 trailing_separator: if force_trailing_comma {
2190 SeparatorTactic::Always
2191 } else if context.inside_macro || !context.use_block_indent() {
2192 SeparatorTactic::Never
2194 context.config.trailing_comma()
2197 ends_with_newline: context.use_block_indent() && tactic == DefinitiveListTactic::Vertical,
2198 config: context.config,
2201 write_list(&item_vec, &fmt).map(|args_str| {
2202 (tactic != DefinitiveListTactic::Vertical, args_str)
2206 fn try_overflow_last_arg<'a, T>(
2207 context: &RewriteContext,
2208 item_vec: &mut Vec<ListItem>,
2211 one_line_width: usize,
2212 args_max_width: usize,
2213 ) -> DefinitiveListTactic
2215 T: Rewrite + Spanned + ToExpr + 'a,
2217 let overflow_last = can_be_overflowed(&context, args);
2219 // Replace the last item with its first line to see if it fits with
2221 let (orig_last, placeholder) = if overflow_last {
2222 let mut context = context.clone();
2223 if let Some(expr) = args[args.len() - 1].to_expr() {
2225 ast::ExprKind::MethodCall(..) => context.force_one_line_chain = true,
2229 last_arg_shape(&context, &item_vec, shape, args_max_width)
2230 .map_or((None, None), |arg_shape| {
2231 rewrite_last_arg_with_overflow(
2234 &mut item_vec[args.len() - 1],
2242 let tactic = definitive_tactic(
2244 ListTactic::LimitedHorizontalVertical(args_max_width),
2248 // Replace the stub with the full overflowing last argument if the rewrite
2249 // succeeded and its first line fits with the other arguments.
2250 match (overflow_last, tactic, placeholder) {
2251 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2252 item_vec[args.len() - 1].item = placeholder;
2255 item_vec[args.len() - 1].item = orig_last;
2264 context: &RewriteContext,
2265 items: &Vec<ListItem>,
2267 args_max_width: usize,
2268 ) -> Option<Shape> {
2269 let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
2270 acc + i.item.as_ref().map_or(0, |s| first_line_width(&s))
2272 let max_width = min(args_max_width, shape.width);
2273 let arg_indent = if context.use_block_indent() {
2274 shape.block().indent.block_unindent(context.config)
2276 shape.block().indent
2279 width: try_opt!(max_width.checked_sub(overhead)),
2285 // Rewriting closure which is placed at the end of the function call's arg.
2286 // Returns `None` if the reformatted closure 'looks bad'.
2287 fn rewrite_last_closure(
2288 context: &RewriteContext,
2291 ) -> Option<String> {
2292 if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
2293 let body = match body.node {
2294 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
2295 stmt_expr(&block.stmts[0]).unwrap_or(body)
2299 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
2307 // If the closure goes multi line before its body, do not overflow the closure.
2308 if prefix.contains('\n') {
2311 let body_shape = try_opt!(shape.offset_left(extra_offset));
2312 // When overflowing the closure which consists of a single control flow expression,
2313 // force to use block if its condition uses multi line.
2314 if rewrite_cond(context, body, body_shape)
2315 .map(|cond| cond.contains('\n'))
2318 return rewrite_closure_with_block(context, body_shape, &prefix, body);
2321 // Seems fine, just format the closure in usual manner.
2322 return expr.rewrite(context, shape);
2327 fn rewrite_last_arg_with_overflow<'a, T>(
2328 context: &RewriteContext,
2330 last_item: &mut ListItem,
2332 ) -> (Option<String>, Option<String>)
2334 T: Rewrite + Spanned + ToExpr + 'a,
2336 let last_arg = args[args.len() - 1];
2337 let rewrite = if let Some(expr) = last_arg.to_expr() {
2339 // When overflowing the closure which consists of a single control flow expression,
2340 // force to use block if its condition uses multi line.
2341 ast::ExprKind::Closure(..) => {
2342 // If the argument consists of multiple closures, we do not overflow
2343 // the last closure.
2344 if args.len() > 1 &&
2348 .filter_map(|arg| arg.to_expr())
2349 .any(|expr| match expr.node {
2350 ast::ExprKind::Closure(..) => true,
2355 rewrite_last_closure(context, expr, shape)
2358 _ => expr.rewrite(context, shape),
2361 last_arg.rewrite(context, shape)
2363 let orig_last = last_item.item.clone();
2365 if let Some(rewrite) = rewrite {
2366 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2367 last_item.item = rewrite_first_line;
2368 (orig_last, Some(rewrite))
2374 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2376 T: Rewrite + Spanned + ToExpr + 'a,
2379 .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2382 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2384 ast::ExprKind::Match(..) => {
2385 (context.use_block_indent() && args_len == 1) ||
2386 (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
2388 ast::ExprKind::If(..) |
2389 ast::ExprKind::IfLet(..) |
2390 ast::ExprKind::ForLoop(..) |
2391 ast::ExprKind::Loop(..) |
2392 ast::ExprKind::While(..) |
2393 ast::ExprKind::WhileLet(..) => {
2394 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2396 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
2397 context.use_block_indent() ||
2398 context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
2400 ast::ExprKind::Array(..) |
2401 ast::ExprKind::Call(..) |
2402 ast::ExprKind::Mac(..) |
2403 ast::ExprKind::MethodCall(..) |
2404 ast::ExprKind::Struct(..) |
2405 ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2406 ast::ExprKind::AddrOf(_, ref expr) |
2407 ast::ExprKind::Box(ref expr) |
2408 ast::ExprKind::Try(ref expr) |
2409 ast::ExprKind::Unary(_, ref expr) |
2410 ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2415 pub fn wrap_args_with_parens(
2416 context: &RewriteContext,
2418 is_extendable: bool,
2420 nested_shape: Shape,
2422 if !context.use_block_indent() ||
2423 (context.inside_macro && !args_str.contains('\n') &&
2424 args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2426 if context.config.spaces_within_parens() && args_str.len() > 0 {
2427 format!("( {} )", args_str)
2429 format!("({})", args_str)
2434 nested_shape.indent.to_string(context.config),
2436 shape.block().indent.to_string(context.config)
2441 fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2442 let snippet = context.snippet(span);
2444 .trim_right_matches(|c: char| c == ')' || c.is_whitespace())
2448 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2449 debug!("rewrite_paren, shape: {:?}", shape);
2450 let total_paren_overhead = paren_overhead(context);
2451 let paren_overhead = total_paren_overhead / 2;
2452 let sub_shape = try_opt!(
2454 .offset_left(paren_overhead)
2455 .and_then(|s| s.sub_width(paren_overhead))
2458 let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && s.len() > 0 {
2459 format!("( {} )", s)
2464 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2465 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2467 if subexpr_str.contains('\n') ||
2468 first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
2470 Some(paren_wrapper(&subexpr_str))
2479 context: &RewriteContext,
2481 ) -> Option<String> {
2482 let expr_str = try_opt!(expr.rewrite(context, shape));
2484 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
2490 let offset = last_line_width(&expr_str) + lbr.len();
2491 let rhs_overhead = shape.rhs_overhead(context.config);
2492 let index_shape = if expr_str.contains('\n') {
2493 Shape::legacy(context.config.max_width(), shape.indent)
2494 .offset_left(offset)
2495 .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
2497 shape.visual_indent(offset).sub_width(offset + rbr.len())
2499 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
2501 // Return if index fits in a single line.
2502 match orig_index_rw {
2503 Some(ref index_str) if !index_str.contains('\n') => {
2504 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2509 // Try putting index on the next line and see if it fits in a single line.
2510 let indent = shape.indent.block_indent(context.config);
2511 let index_shape = try_opt!(Shape::indented(indent, context.config).offset_left(lbr.len()));
2512 let index_shape = try_opt!(index_shape.sub_width(rbr.len() + rhs_overhead));
2513 let new_index_rw = index.rewrite(context, index_shape);
2514 match (orig_index_rw, new_index_rw) {
2515 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
2518 indent.to_string(&context.config),
2523 (None, Some(ref new_index_str)) => Some(format!(
2526 indent.to_string(&context.config),
2531 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2536 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2541 fields.iter().all(|field| !field.is_shorthand)
2544 fn rewrite_struct_lit<'a>(
2545 context: &RewriteContext,
2547 fields: &'a [ast::Field],
2548 base: Option<&'a ast::Expr>,
2551 ) -> Option<String> {
2552 debug!("rewrite_struct_lit: shape {:?}", shape);
2554 enum StructLitField<'a> {
2555 Regular(&'a ast::Field),
2556 Base(&'a ast::Expr),
2560 let path_shape = try_opt!(shape.sub_width(2));
2561 let path_str = try_opt!(rewrite_path(
2569 if fields.len() == 0 && base.is_none() {
2570 return Some(format!("{} {{}}", path_str));
2573 // Foo { a: Foo } - indent is +3, width is -5.
2574 let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
2576 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2577 let body_lo = context.codemap.span_after(span, "{");
2578 let fields_str = if struct_lit_can_be_aligned(fields, &base) &&
2579 context.config.struct_field_align_threshold() > 0
2581 try_opt!(rewrite_with_alignment(
2585 mk_sp(body_lo, span.hi),
2589 let field_iter = fields
2591 .map(StructLitField::Regular)
2592 .chain(base.into_iter().map(StructLitField::Base));
2594 let span_lo = |item: &StructLitField| match *item {
2595 StructLitField::Regular(field) => field.span().lo,
2596 StructLitField::Base(expr) => {
2597 let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
2598 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
2599 let pos = snippet.find_uncommented("..").unwrap();
2600 last_field_hi + BytePos(pos as u32)
2603 let span_hi = |item: &StructLitField| match *item {
2604 StructLitField::Regular(field) => field.span().hi,
2605 StructLitField::Base(expr) => expr.span.hi,
2607 let rewrite = |item: &StructLitField| match *item {
2608 StructLitField::Regular(field) => {
2609 // The 1 taken from the v_budget is for the comma.
2610 rewrite_field(context, field, try_opt!(v_shape.sub_width(1)), 0)
2612 StructLitField::Base(expr) => {
2614 expr.rewrite(context, try_opt!(v_shape.offset_left(2)))
2615 .map(|s| format!("..{}", s))
2619 let items = itemize_list(
2629 let item_vec = items.collect::<Vec<_>>();
2631 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2632 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2633 let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2635 try_opt!(write_list(&item_vec, &fmt))
2638 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2639 Some(format!("{} {{{}}}", path_str, fields_str))
2641 // FIXME if context.config.struct_lit_style() == Visual, but we run out
2642 // of space, we should fall back to BlockIndent.
2645 pub fn wrap_struct_field(
2646 context: &RewriteContext,
2649 nested_shape: Shape,
2650 one_line_width: usize,
2652 if context.config.struct_lit_style() == IndentStyle::Block &&
2653 (fields_str.contains('\n') ||
2654 context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti ||
2655 fields_str.len() > one_line_width)
2659 nested_shape.indent.to_string(context.config),
2661 shape.indent.to_string(context.config)
2664 // One liner or visual indent.
2665 format!(" {} ", fields_str)
2669 pub fn struct_lit_field_separator(config: &Config) -> &str {
2671 config.space_before_struct_lit_field_colon(),
2672 config.space_after_struct_lit_field_colon(),
2676 pub fn rewrite_field(
2677 context: &RewriteContext,
2680 prefix_max_width: usize,
2681 ) -> Option<String> {
2682 if contains_skip(&field.attrs) {
2684 context.snippet(field.span()),
2685 context.config.max_width(),
2689 let name = &field.ident.node.to_string();
2690 if field.is_shorthand {
2691 Some(name.to_string())
2693 let mut separator = String::from(struct_lit_field_separator(context.config));
2694 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2695 separator.push(' ');
2697 let overhead = name.len() + separator.len();
2698 let expr_shape = try_opt!(shape.offset_left(overhead));
2699 let expr = field.expr.rewrite(context, expr_shape);
2701 let mut attrs_str = try_opt!(field.attrs.rewrite(context, shape));
2702 if !attrs_str.is_empty() {
2703 attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2707 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2709 let expr_offset = shape.indent.block_indent(context.config);
2712 .rewrite(context, Shape::indented(expr_offset, context.config));
2718 expr_offset.to_string(&context.config),
2727 fn shape_from_fn_call_style(
2728 context: &RewriteContext,
2732 ) -> Option<Shape> {
2733 if context.use_block_indent() {
2737 .block_indent(context.config.tab_spaces())
2738 .with_max_width(context.config)
2741 shape.visual_indent(offset).sub_width(overhead)
2745 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2746 context: &RewriteContext,
2752 T: Rewrite + Spanned + ToExpr + 'a,
2754 let mut items = items.iter();
2755 // In case of length 1, need a trailing comma
2756 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2757 if items.len() == 1 {
2759 let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
2760 return items.next().unwrap().rewrite(context, nested_shape).map(
2761 |s| if context.config.spaces_within_parens() {
2762 format!("( {}, )", s)
2769 let list_lo = context.codemap.span_after(span, "(");
2770 let nested_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
2771 let items = itemize_list(
2775 |item| item.span().lo,
2776 |item| item.span().hi,
2777 |item| item.rewrite(context, nested_shape),
2779 span.hi - BytePos(1),
2781 let item_vec: Vec<_> = items.collect();
2782 let tactic = definitive_tactic(
2784 ListTactic::HorizontalVertical,
2787 let fmt = ListFormatting {
2790 trailing_separator: SeparatorTactic::Never,
2792 ends_with_newline: false,
2793 config: context.config,
2795 let list_str = try_opt!(write_list(&item_vec, &fmt));
2797 if context.config.spaces_within_parens() && list_str.len() > 0 {
2798 Some(format!("( {} )", list_str))
2800 Some(format!("({})", list_str))
2804 pub fn rewrite_tuple<'a, T>(
2805 context: &RewriteContext,
2811 T: Rewrite + Spanned + ToExpr + 'a,
2813 debug!("rewrite_tuple {:?}", shape);
2814 if context.use_block_indent() {
2815 // We use the same rule as funcation call for rewriting tuple.
2816 let force_trailing_comma = if context.inside_macro {
2817 span_ends_with_comma(context, span)
2827 context.config.fn_call_width(),
2828 force_trailing_comma,
2831 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2835 pub fn rewrite_unary_prefix<R: Rewrite>(
2836 context: &RewriteContext,
2840 ) -> Option<String> {
2842 .rewrite(context, try_opt!(shape.offset_left(prefix.len())))
2843 .map(|r| format!("{}{}", prefix, r))
2846 // FIXME: this is probably not correct for multi-line Rewrites. we should
2847 // subtract suffix.len() from the last line budget, not the first!
2848 pub fn rewrite_unary_suffix<R: Rewrite>(
2849 context: &RewriteContext,
2853 ) -> Option<String> {
2855 .rewrite(context, try_opt!(shape.sub_width(suffix.len())))
2862 fn rewrite_unary_op(
2863 context: &RewriteContext,
2867 ) -> Option<String> {
2868 // For some reason, an UnOp is not spanned like BinOp!
2869 let operator_str = match *op {
2870 ast::UnOp::Deref => "*",
2871 ast::UnOp::Not => "!",
2872 ast::UnOp::Neg => "-",
2874 rewrite_unary_prefix(context, operator_str, expr, shape)
2877 fn rewrite_assignment(
2878 context: &RewriteContext,
2881 op: Option<&ast::BinOp>,
2883 ) -> Option<String> {
2884 let operator_str = match op {
2885 Some(op) => context.snippet(op.span),
2886 None => "=".to_owned(),
2889 // 1 = space between lhs and operator.
2890 let lhs_shape = try_opt!(shape.sub_width(operator_str.len() + 1));
2891 let lhs_str = format!(
2893 try_opt!(lhs.rewrite(context, lhs_shape)),
2897 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2900 // The left hand side must contain everything up to, and including, the
2901 // assignment operator.
2902 pub fn rewrite_assign_rhs<S: Into<String>>(
2903 context: &RewriteContext,
2907 ) -> Option<String> {
2908 let lhs = lhs.into();
2909 let last_line_width = last_line_width(&lhs) - if lhs.contains('\n') {
2910 shape.indent.width()
2914 // 1 = space between operator and rhs.
2915 let orig_shape = try_opt!(shape.offset_left(last_line_width + 1));
2916 let rhs = try_opt!(choose_rhs(
2920 ex.rewrite(context, orig_shape)
2926 context: &RewriteContext,
2929 orig_rhs: Option<String>,
2930 ) -> Option<String> {
2932 Some(ref new_str) if !new_str.contains('\n') => Some(format!(" {}", new_str)),
2934 // Expression did not fit on the same line as the identifier.
2935 // Try splitting the line and see if that works better.
2936 let new_shape = try_opt!(
2938 shape.block().indent.block_indent(context.config),
2940 ).sub_width(shape.rhs_overhead(context.config))
2942 let new_rhs = expr.rewrite(context, new_shape);
2943 let new_indent_str = &new_shape.indent.to_string(context.config);
2945 match (orig_rhs, new_rhs) {
2946 (Some(ref orig_rhs), Some(ref new_rhs)) if prefer_next_line(orig_rhs, new_rhs) => {
2947 Some(format!("\n{}{}", new_indent_str, new_rhs))
2949 (None, Some(ref new_rhs)) => Some(format!("\n{}{}", new_indent_str, new_rhs)),
2950 (None, None) => None,
2951 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2957 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {
2959 fn count_line_breaks(src: &str) -> usize {
2960 src.chars().filter(|&x| x == '\n').count()
2963 !next_line_rhs.contains('\n') ||
2964 count_line_breaks(orig_rhs) > count_line_breaks(next_line_rhs) + 1
2967 fn rewrite_expr_addrof(
2968 context: &RewriteContext,
2969 mutability: ast::Mutability,
2972 ) -> Option<String> {
2973 let operator_str = match mutability {
2974 ast::Mutability::Immutable => "&",
2975 ast::Mutability::Mutable => "&mut ",
2977 rewrite_unary_prefix(context, operator_str, expr, shape)
2981 fn to_expr(&self) -> Option<&ast::Expr>;
2982 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2985 impl ToExpr for ast::Expr {
2986 fn to_expr(&self) -> Option<&ast::Expr> {
2990 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2991 can_be_overflowed_expr(context, self, len)
2995 impl ToExpr for ast::Ty {
2996 fn to_expr(&self) -> Option<&ast::Expr> {
3000 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
3001 can_be_overflowed_type(context, self, len)
3005 impl<'a> ToExpr for TuplePatField<'a> {
3006 fn to_expr(&self) -> Option<&ast::Expr> {
3010 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
3011 can_be_overflowed_pat(context, self, len)
3015 impl<'a> ToExpr for ast::StructField {
3016 fn to_expr(&self) -> Option<&ast::Expr> {
3020 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {