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::{Ordering, min};
12 use std::iter::ExactSizeIterator;
15 use {Indent, Shape, Spanned};
16 use codemap::SpanUtils;
17 use rewrite::{Rewrite, RewriteContext};
18 use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic,
19 DefinitiveListTactic, definitive_tactic, ListItem, struct_lit_shape,
20 struct_lit_tactic, shape_for_tactic, struct_lit_formatting};
21 use string::{StringFormat, rewrite_string};
22 use utils::{extra_offset, last_line_width, wrap_str, binary_search, first_line_width,
23 semicolon_for_stmt, trimmed_last_line_width, left_most_sub_expr, stmt_expr,
24 colon_spaces, contains_skip, mk_sp, last_line_extendable, paren_overhead};
25 use visitor::FmtVisitor;
26 use config::{Config, IndentStyle, MultilineStyle, ControlBraceStyle, Style};
27 use comment::{FindUncommented, rewrite_comment, contains_comment, recover_comment_removed};
28 use types::{rewrite_path, PathContext, can_be_overflowed_type};
29 use items::{span_lo_for_arg, span_hi_for_arg};
30 use chains::rewrite_chain;
31 use macros::{rewrite_macro, MacroPosition};
32 use patterns::{TuplePatField, can_be_overflowed_pat};
33 use vertical::rewrite_with_alignment;
35 use syntax::{ast, ptr};
36 use syntax::codemap::{CodeMap, Span, BytePos};
37 use syntax::parse::classify;
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 separator = if attr_str.is_empty() {
60 if expr_str.contains('\n') || attr_str.contains('\n') ||
61 attr_str.len() + expr_str.len() > shape.width
63 format!("\n{}", shape.indent.to_string(context.config))
68 format!("{}{}{}", attr_str, separator, expr_str)
74 context: &RewriteContext,
77 let attr_rw = (&*expr.attrs).rewrite(context, shape);
78 if contains_skip(&*expr.attrs) {
79 if let Some(attr_str) = attr_rw {
80 return Some(combine_attr_and_expr(
84 &context.snippet(expr.span),
87 return Some(context.snippet(expr.span));
90 let expr_rw = match expr.node {
91 ast::ExprKind::Array(ref expr_vec) => {
93 expr_vec.iter().map(|e| &**e),
94 mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi),
100 ast::ExprKind::Lit(ref l) => {
102 ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
103 rewrite_string_lit(context, l.span, shape)
107 context.snippet(expr.span),
108 context.config.max_width(),
114 ast::ExprKind::Call(ref callee, ref args) => {
115 let inner_span = mk_sp(callee.span.hi, expr.span.hi);
116 rewrite_call_with_binary_search(
119 &args.iter().map(|x| &**x).collect::<Vec<_>>()[..],
124 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
125 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
126 // FIXME: format comments between operands and operator
131 &format!(" {} ", context.snippet(op.span)),
137 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
138 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
143 base.as_ref().map(|e| &**e),
148 ast::ExprKind::Tup(ref items) => {
151 &items.iter().map(|x| &**x).collect::<Vec<_>>()[..],
156 ast::ExprKind::If(..) |
157 ast::ExprKind::IfLet(..) |
158 ast::ExprKind::ForLoop(..) |
159 ast::ExprKind::Loop(..) |
160 ast::ExprKind::While(..) |
161 ast::ExprKind::WhileLet(..) => {
162 to_control_flow(expr, expr_type)
163 .and_then(|control_flow| control_flow.rewrite(context, shape))
165 ast::ExprKind::Block(ref block) => {
167 ExprType::Statement => {
168 if is_unsafe_block(block) {
169 block.rewrite(context, shape)
171 // Rewrite block without trying to put it in a single line.
172 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
175 let prefix = try_opt!(block_prefix(context, block, shape));
176 rewrite_block_with_visitor(context, &prefix, block, shape)
179 ExprType::SubExpression => block.rewrite(context, shape),
182 ast::ExprKind::Match(ref cond, ref arms) => {
183 rewrite_match(context, cond, arms, shape, expr.span)
185 ast::ExprKind::Path(ref qself, ref path) => {
186 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
188 ast::ExprKind::Assign(ref lhs, ref rhs) => {
189 rewrite_assignment(context, lhs, rhs, None, shape)
191 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
192 rewrite_assignment(context, lhs, rhs, Some(op), shape)
194 ast::ExprKind::Continue(ref opt_ident) => {
195 let id_str = match *opt_ident {
196 Some(ident) => format!(" {}", ident.node),
197 None => String::new(),
200 format!("continue{}", id_str),
201 context.config.max_width(),
205 ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
206 let id_str = match *opt_ident {
207 Some(ident) => format!(" {}", ident.node),
208 None => String::new(),
211 if let Some(ref expr) = *opt_expr {
212 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
215 format!("break{}", id_str),
216 context.config.max_width(),
221 ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
222 rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
224 ast::ExprKind::Try(..) |
225 ast::ExprKind::Field(..) |
226 ast::ExprKind::TupField(..) |
227 ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
228 ast::ExprKind::Mac(ref mac) => {
229 // Failure to rewrite a marco should not imply failure to
230 // rewrite the expression.
231 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
233 context.snippet(expr.span),
234 context.config.max_width(),
239 ast::ExprKind::Ret(None) => {
240 wrap_str("return".to_owned(), context.config.max_width(), shape)
242 ast::ExprKind::Ret(Some(ref expr)) => {
243 rewrite_unary_prefix(context, "return ", &**expr, shape)
245 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
246 ast::ExprKind::AddrOf(mutability, ref expr) => {
247 rewrite_expr_addrof(context, mutability, expr, shape)
249 ast::ExprKind::Cast(ref expr, ref ty) => {
250 rewrite_pair(&**expr, &**ty, "", " as ", "", context, shape)
252 ast::ExprKind::Type(ref expr, ref ty) => {
253 rewrite_pair(&**expr, &**ty, "", ": ", "", context, shape)
255 ast::ExprKind::Index(ref expr, ref index) => {
256 rewrite_index(&**expr, &**index, context, shape)
258 ast::ExprKind::Repeat(ref expr, ref repeats) => {
259 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
264 rewrite_pair(&**expr, &**repeats, lbr, "; ", rbr, context, shape)
266 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
267 let delim = match limits {
268 ast::RangeLimits::HalfOpen => "..",
269 ast::RangeLimits::Closed => "...",
272 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
274 ast::ExprKind::Lit(ref lit) => {
276 ast::LitKind::FloatUnsuffixed(..) => {
277 context.snippet(lit.span).ends_with('.')
286 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
287 (Some(ref lhs), Some(ref rhs)) => {
288 let sp_delim = if context.config.spaces_around_ranges() {
289 format!(" {} ", delim)
290 } else if needs_space_before_range(context, lhs) {
291 format!(" {}", delim)
295 rewrite_pair(&**lhs, &**rhs, "", &sp_delim, "", context, shape)
297 (None, Some(ref rhs)) => {
298 let sp_delim = if context.config.spaces_around_ranges() {
299 format!("{} ", delim)
303 rewrite_unary_prefix(context, &sp_delim, &**rhs, shape)
305 (Some(ref lhs), None) => {
306 let sp_delim = if context.config.spaces_around_ranges() {
307 format!(" {}", delim)
311 rewrite_unary_suffix(context, &sp_delim, &**lhs, shape)
313 (None, None) => wrap_str(delim.into(), context.config.max_width(), shape),
316 // We do not format these expressions yet, but they should still
317 // satisfy our width restrictions.
318 ast::ExprKind::InPlace(..) |
319 ast::ExprKind::InlineAsm(..) => {
321 context.snippet(expr.span),
322 context.config.max_width(),
326 ast::ExprKind::Catch(ref block) => {
327 if let rewrite @ Some(_) =
328 rewrite_single_line_block(context, "do catch ", block, shape)
333 let budget = shape.width.checked_sub(9).unwrap_or(0);
337 try_opt!(block.rewrite(&context, Shape::legacy(budget, shape.indent)))
341 match (attr_rw, expr_rw) {
342 (Some(attr_str), Some(expr_str)) => {
343 recover_comment_removed(
344 combine_attr_and_expr(context, shape, &attr_str, &expr_str),
354 pub fn rewrite_pair<LHS, RHS>(
360 context: &RewriteContext,
367 // Get "full width" rhs and see if it fits on the current line. This
368 // usually works fairly well since it tends to place operands of
369 // operations with high precendence close together.
370 // Note that this is non-conservative, but its just to see if it's even
371 // worth trying to put everything on one line.
372 let rhs_shape = try_opt!(shape.sub_width(suffix.len()));
373 let rhs_result = rhs.rewrite(context, rhs_shape);
375 if let Some(rhs_result) = rhs_result {
376 // This is needed in case of line break not caused by a
377 // shortage of space, but by end-of-line comments, for example.
378 if !rhs_result.contains('\n') {
380 try_opt!(try_opt!(shape.offset_left(prefix.len())).sub_width(infix.len()));
381 let lhs_result = lhs.rewrite(context, lhs_shape);
382 if let Some(lhs_result) = lhs_result {
383 let mut result = format!("{}{}{}", prefix, lhs_result, infix);
385 let remaining_width = shape
387 .checked_sub(last_line_width(&result) + suffix.len())
390 if rhs_result.len() <= remaining_width {
391 result.push_str(&rhs_result);
392 result.push_str(suffix);
396 // Try rewriting the rhs into the remaining space.
397 let rhs_shape = shape.shrink_left(last_line_width(&result) + suffix.len());
398 if let Some(rhs_shape) = rhs_shape {
399 if let Some(rhs_result) = rhs.rewrite(context, rhs_shape) {
400 // FIXME this should always hold.
401 if rhs_result.len() <= remaining_width {
402 result.push_str(&rhs_result);
403 result.push_str(suffix);
412 // We have to use multiple lines.
414 // Re-evaluate the rhs because we have more space now:
415 let infix = infix.trim_right();
416 let rhs_shape = match context.config.control_style() {
418 try_opt!(shape.sub_width(suffix.len() + prefix.len())).visual_indent(prefix.len())
421 // Try to calculate the initial constraint on the right hand side.
422 let rhs_overhead = context
425 .checked_sub(shape.used_width() + shape.width)
428 Shape::indented(shape.indent.block_indent(context.config), context.config)
429 .sub_width(rhs_overhead)
433 let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape));
434 let lhs_overhead = shape.used_width() + prefix.len() + infix.len();
435 let lhs_shape = Shape {
436 width: try_opt!(context.config.max_width().checked_sub(lhs_overhead)),
439 let lhs_result = try_opt!(lhs.rewrite(context, lhs_shape));
445 rhs_shape.indent.to_string(context.config),
451 pub fn rewrite_array<'a, I>(
454 context: &RewriteContext,
456 trailing_comma: bool,
459 I: Iterator<Item = &'a ast::Expr>,
461 let bracket_size = if context.config.spaces_within_square_brackets() {
467 let mut nested_shape = match context.config.array_layout() {
468 IndentStyle::Block => {
472 .block_indent(context.config.tab_spaces())
473 .with_max_width(context.config)
477 IndentStyle::Visual => {
480 .visual_indent(bracket_size)
481 .sub_width(bracket_size * 2)
486 let items = itemize_list(
492 |item| item.rewrite(context, nested_shape),
495 ).collect::<Vec<_>>();
497 if items.is_empty() {
498 if context.config.spaces_within_square_brackets() {
499 return Some("[ ]".to_string());
501 return Some("[]".to_string());
505 let has_long_item = items
507 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
509 let mut tactic = match context.config.array_layout() {
510 IndentStyle::Block => {
511 // FIXME wrong shape in one-line case
512 match shape.width.checked_sub(2 * bracket_size) {
515 ListTactic::LimitedHorizontalVertical(context.config.array_width());
516 definitive_tactic(&items, tactic, width)
518 None => DefinitiveListTactic::Vertical,
521 IndentStyle::Visual => {
522 if has_long_item || items.iter().any(ListItem::is_multiline) {
525 ListTactic::LimitedHorizontalVertical(context.config.array_width()),
529 DefinitiveListTactic::Mixed
533 if context.config.array_horizontal_layout_threshold() > 0 &&
534 items.len() > context.config.array_horizontal_layout_threshold()
536 tactic = DefinitiveListTactic::Mixed;
537 if context.config.array_layout() == IndentStyle::Block {
538 nested_shape = try_opt!(
540 .visual_indent(bracket_size)
541 .sub_width(bracket_size * 2)
546 let fmt = ListFormatting {
549 trailing_separator: if trailing_comma {
550 SeparatorTactic::Always
551 } else if context.inside_macro || context.config.array_layout() == IndentStyle::Visual {
552 SeparatorTactic::Never
554 SeparatorTactic::Vertical
557 ends_with_newline: false,
558 config: context.config,
560 let list_str = try_opt!(write_list(&items, &fmt));
562 let result = if context.config.array_layout() == IndentStyle::Visual ||
563 tactic != DefinitiveListTactic::Vertical
565 if context.config.spaces_within_square_brackets() && list_str.len() > 0 {
566 format!("[ {} ]", list_str)
568 format!("[{}]", list_str)
573 nested_shape.indent.to_string(context.config),
575 shape.block().indent.to_string(context.config)
582 // Return type is (prefix, extra_offset)
583 fn rewrite_closure_fn_decl(
584 capture: ast::CaptureBy,
585 fn_decl: &ast::FnDecl,
588 context: &RewriteContext,
590 ) -> Option<(String, usize)> {
591 let mover = if capture == ast::CaptureBy::Value {
596 // 4 = "|| {".len(), which is overconservative when the closure consists of
597 // a single expression.
598 let nested_shape = try_opt!(try_opt!(shape.shrink_left(mover.len())).sub_width(4));
601 let argument_offset = nested_shape.indent + 1;
602 let arg_shape = try_opt!(nested_shape.shrink_left(1)).visual_indent(0);
603 let ret_str = try_opt!(fn_decl.output.rewrite(context, arg_shape));
605 let arg_items = itemize_list(
607 fn_decl.inputs.iter(),
609 |arg| span_lo_for_arg(arg),
610 |arg| span_hi_for_arg(context, arg),
611 |arg| arg.rewrite(context, arg_shape),
612 context.codemap.span_after(span, "|"),
615 let item_vec = arg_items.collect::<Vec<_>>();
616 // 1 = space between arguments and return type.
617 let horizontal_budget = nested_shape
619 .checked_sub(ret_str.len() + 1)
621 let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
622 let arg_shape = match tactic {
623 DefinitiveListTactic::Horizontal => try_opt!(arg_shape.sub_width(ret_str.len() + 1)),
627 let fmt = ListFormatting {
630 trailing_separator: SeparatorTactic::Never,
632 ends_with_newline: false,
633 config: context.config,
635 let list_str = try_opt!(write_list(&item_vec, &fmt));
636 let mut prefix = format!("{}|{}|", mover, list_str);
637 // 1 = space between `|...|` and body.
638 let extra_offset = extra_offset(&prefix, shape) + 1;
640 if !ret_str.is_empty() {
641 if prefix.contains('\n') {
643 prefix.push_str(&argument_offset.to_string(context.config));
647 prefix.push_str(&ret_str);
650 Some((prefix, extra_offset))
653 // This functions is pretty messy because of the rules around closures and blocks:
654 // FIXME - the below is probably no longer true in full.
655 // * if there is a return type, then there must be braces,
656 // * given a closure with braces, whether that is parsed to give an inner block
657 // or not depends on if there is a return type and if there are statements
659 // * if the first expression in the body ends with a block (i.e., is a
660 // statement without needing a semi-colon), then adding or removing braces
661 // can change whether it is treated as an expression or statement.
663 capture: ast::CaptureBy,
664 fn_decl: &ast::FnDecl,
667 context: &RewriteContext,
669 ) -> Option<String> {
670 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
678 // 1 = space between `|...|` and body.
679 let body_shape = try_opt!(shape.offset_left(extra_offset));
681 if let ast::ExprKind::Block(ref block) = body.node {
682 // The body of the closure is an empty block.
683 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
684 return Some(format!("{} {{}}", prefix));
687 // Figure out if the block is necessary.
688 let needs_block = block.rules != ast::BlockCheckMode::Default ||
689 block.stmts.len() > 1 || context.inside_macro ||
690 block_contains_comment(block, context.codemap) ||
691 prefix.contains('\n');
693 let no_return_type = if let ast::FunctionRetTy::Default(_) = fn_decl.output {
698 if no_return_type && !needs_block {
699 // lock.stmts.len() == 1
700 if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
701 if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
708 // We need braces, but we might still prefer a one-liner.
709 let stmt = &block.stmts[0];
710 // 4 = braces and spaces.
711 if let Some(body_shape) = body_shape.sub_width(4) {
712 // Checks if rewrite succeeded and fits on a single line.
713 if let Some(rewrite) = and_one_line(stmt.rewrite(context, body_shape)) {
714 return Some(format!("{} {{ {} }}", prefix, rewrite));
719 // Either we require a block, or tried without and failed.
720 rewrite_closure_block(&block, &prefix, context, body_shape)
722 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
723 // The closure originally had a non-block expression, but we can't fit on
724 // one line, so we'll insert a block.
725 rewrite_closure_with_block(context, body_shape, &prefix, body)
730 // Rewrite closure with a single expression wrapping its body with block.
731 fn rewrite_closure_with_block(
732 context: &RewriteContext,
736 ) -> Option<String> {
737 let block = ast::Block {
740 id: ast::NodeId::new(0),
741 node: ast::StmtKind::Expr(ptr::P(body.clone())),
745 id: ast::NodeId::new(0),
746 rules: ast::BlockCheckMode::Default,
749 rewrite_closure_block(&block, prefix, context, shape)
752 // Rewrite closure with a single expression without wrapping its body with block.
753 fn rewrite_closure_expr(
756 context: &RewriteContext,
758 ) -> Option<String> {
759 let mut rewrite = expr.rewrite(context, shape);
760 if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
761 rewrite = and_one_line(rewrite);
763 rewrite.map(|rw| format!("{} {}", prefix, rw))
766 // Rewrite closure whose body is block.
767 fn rewrite_closure_block(
770 context: &RewriteContext,
772 ) -> Option<String> {
773 // Start with visual indent, then fall back to block indent if the
775 let block_threshold = context.config.closure_block_indent_threshold();
776 if block_threshold >= 0 {
777 if let Some(block_str) = block.rewrite(&context, shape) {
778 if block_str.matches('\n').count() <= block_threshold as usize &&
779 !need_block_indent(&block_str, shape)
781 if let Some(block_str) = block_str.rewrite(context, shape) {
782 return Some(format!("{} {}", prefix, block_str));
788 // The body of the closure is big enough to be block indented, that
789 // means we must re-format.
790 let block_shape = shape.block();
791 let block_str = try_opt!(block.rewrite(&context, block_shape));
792 Some(format!("{} {}", prefix, block_str))
795 fn and_one_line(x: Option<String>) -> Option<String> {
796 x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
799 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
800 debug!("nop_block_collapse {:?} {}", block_str, budget);
801 block_str.map(|block_str| {
802 if block_str.starts_with('{') && budget >= 2 &&
803 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
812 fn rewrite_empty_block(
813 context: &RewriteContext,
816 ) -> Option<String> {
817 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) &&
820 return Some("{}".to_owned());
823 // If a block contains only a single-line comment, then leave it on one line.
824 let user_str = context.snippet(block.span);
825 let user_str = user_str.trim();
826 if user_str.starts_with('{') && user_str.ends_with('}') {
827 let comment_str = user_str[1..user_str.len() - 1].trim();
828 if block.stmts.is_empty() && !comment_str.contains('\n') &&
829 !comment_str.starts_with("//") && comment_str.len() + 4 <= shape.width
831 return Some(format!("{{ {} }}", comment_str));
838 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
839 Some(match block.rules {
840 ast::BlockCheckMode::Unsafe(..) => {
841 let snippet = context.snippet(block.span);
842 let open_pos = try_opt!(snippet.find_uncommented("{"));
843 // Extract comment between unsafe and block start.
844 let trimmed = &snippet[6..open_pos].trim();
846 if !trimmed.is_empty() {
847 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
848 let budget = try_opt!(shape.width.checked_sub(9));
851 try_opt!(rewrite_comment(
854 Shape::legacy(budget, shape.indent + 7),
862 ast::BlockCheckMode::Default => String::new(),
866 fn rewrite_single_line_block(
867 context: &RewriteContext,
871 ) -> Option<String> {
872 if is_simple_block(block, context.codemap) {
873 let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
874 let expr_str = try_opt!(block.stmts[0].rewrite(context, expr_shape));
875 let result = format!("{}{{ {} }}", prefix, expr_str);
876 if result.len() <= shape.width && !result.contains('\n') {
883 fn rewrite_block_with_visitor(
884 context: &RewriteContext,
888 ) -> Option<String> {
889 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
893 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
894 visitor.block_indent = shape.indent;
895 visitor.is_if_else_block = context.is_if_else_block;
897 ast::BlockCheckMode::Unsafe(..) => {
898 let snippet = context.snippet(block.span);
899 let open_pos = try_opt!(snippet.find_uncommented("{"));
900 visitor.last_pos = block.span.lo + BytePos(open_pos as u32)
902 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo,
905 visitor.visit_block(block);
906 if visitor.failed && shape.indent.alignment != 0 {
909 Shape::indented(shape.indent.block_only(), context.config),
912 Some(format!("{}{}", prefix, visitor.buffer))
916 impl Rewrite for ast::Block {
917 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
918 // shape.width is used only for the single line case: either the empty block `{}`,
919 // or an unsafe expression `unsafe { e }`.
920 if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
924 let prefix = try_opt!(block_prefix(context, self, shape));
925 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
929 rewrite_block_with_visitor(context, &prefix, self, shape)
933 impl Rewrite for ast::Stmt {
934 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
935 let result = match self.node {
936 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
937 ast::StmtKind::Expr(ref ex) |
938 ast::StmtKind::Semi(ref ex) => {
939 let suffix = if semicolon_for_stmt(self) { ";" } else { "" };
944 ast::StmtKind::Expr(_) => ExprType::SubExpression,
945 ast::StmtKind::Semi(_) => ExprType::Statement,
949 try_opt!(shape.sub_width(suffix.len())),
950 ).map(|s| s + suffix)
952 ast::StmtKind::Mac(..) |
953 ast::StmtKind::Item(..) => None,
955 result.and_then(|res| {
956 recover_comment_removed(res, self.span, context, shape)
961 // Rewrite condition if the given expression has one.
962 fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
964 ast::ExprKind::Match(ref cond, _) => {
966 let cond_shape = match context.config.control_style() {
967 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
968 Style::Rfc => try_opt!(shape.offset_left(8)),
970 cond.rewrite(context, cond_shape)
972 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
973 stmt_expr(&block.stmts[0]).and_then(|e| rewrite_cond(context, e, shape))
976 to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
978 String::from("\n") + &shape.indent.block_only().to_string(context.config);
980 .rewrite_cond(context, shape, &alt_block_sep)
981 .and_then(|rw| Some(rw.0))
987 // Abstraction over control flow expressions
989 struct ControlFlow<'a> {
990 cond: Option<&'a ast::Expr>,
991 block: &'a ast::Block,
992 else_block: Option<&'a ast::Expr>,
993 label: Option<ast::SpannedIdent>,
994 pat: Option<&'a ast::Pat>,
998 allow_single_line: bool,
999 // True if this is an `if` expression in an `else if` :-( hacky
1004 fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'a>> {
1006 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
1007 Some(ControlFlow::new_if(
1011 else_block.as_ref().map(|e| &**e),
1012 expr_type == ExprType::SubExpression,
1017 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
1018 Some(ControlFlow::new_if(
1022 else_block.as_ref().map(|e| &**e),
1023 expr_type == ExprType::SubExpression,
1028 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
1029 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
1031 ast::ExprKind::Loop(ref block, label) => Some(
1032 ControlFlow::new_loop(block, label, expr.span),
1034 ast::ExprKind::While(ref cond, ref block, label) => Some(
1035 ControlFlow::new_while(None, cond, block, label, expr.span),
1037 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => {
1038 Some(ControlFlow::new_while(
1050 impl<'a> ControlFlow<'a> {
1052 cond: &'a ast::Expr,
1053 pat: Option<&'a ast::Pat>,
1054 block: &'a ast::Block,
1055 else_block: Option<&'a ast::Expr>,
1056 allow_single_line: bool,
1059 ) -> ControlFlow<'a> {
1063 else_block: else_block,
1067 matcher: match pat {
1072 allow_single_line: allow_single_line,
1073 nested_if: nested_if,
1079 block: &'a ast::Block,
1080 label: Option<ast::SpannedIdent>,
1082 ) -> ControlFlow<'a> {
1092 allow_single_line: false,
1099 pat: Option<&'a ast::Pat>,
1100 cond: &'a ast::Expr,
1101 block: &'a ast::Block,
1102 label: Option<ast::SpannedIdent>,
1104 ) -> ControlFlow<'a> {
1112 matcher: match pat {
1117 allow_single_line: false,
1125 cond: &'a ast::Expr,
1126 block: &'a ast::Block,
1127 label: Option<ast::SpannedIdent>,
1129 ) -> ControlFlow<'a> {
1139 allow_single_line: false,
1145 fn rewrite_single_line(
1148 context: &RewriteContext,
1150 ) -> Option<String> {
1151 assert!(self.allow_single_line);
1152 let else_block = try_opt!(self.else_block);
1153 let fixed_cost = self.keyword.len() + " { } else { }".len();
1155 if let ast::ExprKind::Block(ref else_node) = else_block.node {
1156 if !is_simple_block(self.block, context.codemap) ||
1157 !is_simple_block(else_node, context.codemap) ||
1158 pat_expr_str.contains('\n')
1163 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
1164 let expr = &self.block.stmts[0];
1165 let if_str = try_opt!(expr.rewrite(
1167 Shape::legacy(new_width, Indent::empty()),
1170 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
1171 let else_expr = &else_node.stmts[0];
1173 try_opt!(else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
1175 if if_str.contains('\n') || else_str.contains('\n') {
1179 let result = format!(
1180 "{} {} {{ {} }} else {{ {} }}",
1187 if result.len() <= width {
1188 return Some(result);
1196 impl<'a> ControlFlow<'a> {
1199 context: &RewriteContext,
1201 alt_block_sep: &str,
1202 ) -> Option<(String, usize)> {
1203 let constr_shape = if self.nested_if {
1204 // We are part of an if-elseif-else chain. Our constraints are tightened.
1205 // 7 = "} else " .len()
1206 try_opt!(shape.shrink_left(7))
1211 let label_string = rewrite_label(self.label);
1212 // 1 = space after keyword.
1213 let offset = self.keyword.len() + label_string.len() + 1;
1215 let pat_expr_string = match self.cond {
1217 let mut cond_shape = match context.config.control_style() {
1218 Style::Legacy => try_opt!(constr_shape.shrink_left(offset)),
1219 Style::Rfc => try_opt!(constr_shape.offset_left(offset)),
1221 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1223 cond_shape = try_opt!(cond_shape.sub_width(2));
1226 try_opt!(rewrite_pat_expr(
1236 None => String::new(),
1239 let force_newline_brace = context.config.control_style() == Style::Rfc &&
1240 pat_expr_string.contains('\n') &&
1241 !last_line_extendable(&pat_expr_string);
1243 // Try to format if-else on single line.
1244 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1245 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1247 if let Some(cond_str) = trial {
1248 if cond_str.len() <= context.config.single_line_if_else_max_width() {
1249 return Some((cond_str, 0));
1254 let cond_span = if let Some(cond) = self.cond {
1257 mk_sp(self.block.span.lo, self.block.span.lo)
1260 // for event in event
1261 let between_kwd_cond = mk_sp(
1262 context.codemap.span_after(self.span, self.keyword.trim()),
1265 |p| if self.matcher.is_empty() {
1268 context.codemap.span_before(self.span, self.matcher.trim())
1273 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1275 let after_cond_comment =
1276 extract_comment(mk_sp(cond_span.hi, self.block.span.lo), context, shape);
1278 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1280 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine ||
1288 let used_width = if pat_expr_string.contains('\n') {
1289 last_line_width(&pat_expr_string)
1291 // 2 = spaces after keyword and condition.
1292 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1300 between_kwd_cond_comment.as_ref().map_or(
1301 if pat_expr_string.is_empty() ||
1302 pat_expr_string.starts_with('\n')
1311 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1318 impl<'a> Rewrite for ControlFlow<'a> {
1319 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1320 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1323 String::from("\n") + &shape.indent.block_only().to_string(context.config);
1324 let (cond_str, used_width) = try_opt!(self.rewrite_cond(context, shape, &alt_block_sep));
1325 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1326 if used_width == 0 {
1327 return Some(cond_str);
1330 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1331 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1332 // we should avoid the single line case.
1333 let block_width = if self.else_block.is_some() || self.nested_if {
1338 let block_shape = Shape {
1342 let mut block_context = context.clone();
1343 block_context.is_if_else_block = self.else_block.is_some();
1344 let block_str = try_opt!(rewrite_block_with_visitor(
1351 let mut result = format!("{}{}", cond_str, block_str);
1353 if let Some(else_block) = self.else_block {
1354 let shape = Shape::indented(shape.indent, context.config);
1355 let mut last_in_chain = false;
1356 let rewrite = match else_block.node {
1357 // If the else expression is another if-else expression, prevent it
1358 // from being formatted on a single line.
1359 // Note how we're passing the original shape, as the
1360 // cost of "else" should not cascade.
1361 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1362 ControlFlow::new_if(
1366 next_else_block.as_ref().map(|e| &**e),
1369 mk_sp(else_block.span.lo, self.span.hi),
1370 ).rewrite(context, shape)
1372 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1373 ControlFlow::new_if(
1377 next_else_block.as_ref().map(|e| &**e),
1380 mk_sp(else_block.span.lo, self.span.hi),
1381 ).rewrite(context, shape)
1384 last_in_chain = true;
1385 // When rewriting a block, the width is only used for single line
1386 // blocks, passing 1 lets us avoid that.
1387 let else_shape = Shape {
1388 width: min(1, shape.width),
1391 format_expr(else_block, ExprType::Statement, context, else_shape)
1395 let between_kwd_else_block = mk_sp(
1399 .span_before(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1401 let between_kwd_else_block_comment =
1402 extract_comment(between_kwd_else_block, context, shape);
1404 let after_else = mk_sp(
1407 .span_after(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1410 let after_else_comment = extract_comment(after_else, context, shape);
1412 let between_sep = match context.config.control_brace_style() {
1413 ControlBraceStyle::AlwaysNextLine |
1414 ControlBraceStyle::ClosingNextLine => &*alt_block_sep,
1415 ControlBraceStyle::AlwaysSameLine => " ",
1417 let after_sep = match context.config.control_brace_style() {
1418 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1425 between_kwd_else_block_comment
1427 .map_or(between_sep, |s| &**s),
1428 after_else_comment.as_ref().map_or(after_sep, |s| &**s)
1431 result.push_str(&try_opt!(rewrite));
1438 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
1440 Some(ident) => format!("{}: ", ident.node),
1441 None => "".to_owned(),
1445 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1446 let comment_str = context.snippet(span);
1447 if contains_comment(&comment_str) {
1448 let comment = try_opt!(rewrite_comment(
1455 "\n{indent}{}\n{indent}",
1457 indent = shape.indent.to_string(context.config)
1464 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1465 let snippet = codemap.span_to_snippet(block.span).unwrap();
1466 contains_comment(&snippet)
1469 // Checks that a block contains no statements, an expression and no comments.
1470 // FIXME: incorrectly returns false when comment is contained completely within
1472 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1473 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) &&
1474 !block_contains_comment(block, codemap))
1477 /// Checks whether a block contains at most one statement or expression, and no comments.
1478 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1479 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1482 /// Checks whether a block contains no statements, expressions, or comments.
1483 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1484 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1487 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1489 ast::StmtKind::Expr(..) => true,
1494 fn is_unsafe_block(block: &ast::Block) -> bool {
1495 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1502 // inter-match-arm-comment-rules:
1503 // - all comments following a match arm before the start of the next arm
1504 // are about the second arm
1505 fn rewrite_match_arm_comment(
1506 context: &RewriteContext,
1509 arm_indent_str: &str,
1510 ) -> Option<String> {
1511 // The leading "," is not part of the arm-comment
1512 let missed_str = match missed_str.find_uncommented(",") {
1513 Some(n) => &missed_str[n + 1..],
1514 None => &missed_str[..],
1517 let mut result = String::new();
1518 // any text not preceeded by a newline is pushed unmodified to the block
1519 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
1520 result.push_str(&missed_str[..first_brk]);
1521 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
1523 let first = missed_str
1524 .find(|c: char| !c.is_whitespace())
1525 .unwrap_or(missed_str.len());
1526 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
1527 // Excessive vertical whitespace before comment should be preserved
1528 // FIXME handle vertical whitespace better
1531 let missed_str = missed_str[first..].trim();
1532 if !missed_str.is_empty() {
1533 let comment = try_opt!(rewrite_comment(&missed_str, false, shape, context.config));
1535 result.push_str(arm_indent_str);
1536 result.push_str(&comment);
1543 context: &RewriteContext,
1548 ) -> Option<String> {
1549 if arms.is_empty() {
1554 let cond_shape = match context.config.control_style() {
1555 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
1556 Style::Rfc => try_opt!(shape.offset_left(8)),
1558 let cond_str = try_opt!(cond.rewrite(context, cond_shape));
1559 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1560 let block_sep = match context.config.control_brace_style() {
1561 ControlBraceStyle::AlwaysNextLine => alt_block_sep.as_str(),
1564 let mut result = format!("match {}{}{{", cond_str, block_sep);
1566 let arm_shape = if context.config.indent_match_arms() {
1567 shape.block_indent(context.config.tab_spaces())
1569 shape.block_indent(0)
1572 let arm_indent_str = arm_shape.indent.to_string(context.config);
1574 let open_brace_pos = context
1576 .span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])), "{");
1578 let arm_num = arms.len();
1579 for (i, arm) in arms.iter().enumerate() {
1580 // Make sure we get the stuff between arms.
1581 let missed_str = if i == 0 {
1582 context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
1584 context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
1586 let comment = try_opt!(rewrite_match_arm_comment(
1592 result.push_str(&comment);
1594 result.push_str(&arm_indent_str);
1596 let arm_str = arm.rewrite(&context, arm_shape.with_max_width(context.config));
1597 if let Some(ref arm_str) = arm_str {
1598 // Trim the trailing comma if necessary.
1599 if i == arm_num - 1 && context.config.trailing_comma() == SeparatorTactic::Never &&
1600 arm_str.ends_with(',')
1602 result.push_str(&arm_str[0..arm_str.len() - 1])
1604 result.push_str(arm_str)
1607 // We couldn't format the arm, just reproduce the source.
1608 let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
1609 result.push_str(&snippet);
1610 if context.config.trailing_comma() != SeparatorTactic::Never {
1611 result.push_str(arm_comma(context.config, &arm.body))
1615 // BytePos(1) = closing match brace.
1616 let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
1617 let last_comment = context.snippet(last_span);
1618 let comment = try_opt!(rewrite_match_arm_comment(
1624 result.push_str(&comment);
1626 result.push_str(&shape.indent.to_string(context.config));
1631 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
1637 if !attrs.is_empty() {
1638 return attrs[0].span.lo;
1644 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
1648 fn arm_comma(config: &Config, body: &ast::Expr) -> &'static str {
1649 if config.match_block_trailing_comma() {
1651 } else if let ast::ExprKind::Block(ref block) = body.node {
1652 if let ast::BlockCheckMode::Default = block.rules {
1663 impl Rewrite for ast::Arm {
1664 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1665 debug!("Arm::rewrite {:?} {:?}", self, shape);
1673 let attr_str = if !attrs.is_empty() {
1674 if contains_skip(attrs) {
1679 try_opt!(attrs.rewrite(context, shape)),
1680 shape.indent.to_string(context.config)
1688 let pat_shape = try_opt!(shape.sub_width(5));
1690 let pat_strs = try_opt!(
1692 .map(|p| p.rewrite(context, pat_shape))
1693 .collect::<Option<Vec<_>>>()
1696 let all_simple = pat_strs.iter().all(|p| pat_is_simple(p));
1697 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1698 let fmt = ListFormatting {
1699 tactic: if all_simple {
1700 DefinitiveListTactic::Mixed
1702 DefinitiveListTactic::Vertical
1705 trailing_separator: SeparatorTactic::Never,
1707 ends_with_newline: false,
1708 config: context.config,
1710 let pats_str = try_opt!(write_list(items, &fmt));
1712 let guard_shape = if pats_str.contains('\n') {
1713 shape.with_max_width(context.config)
1718 let guard_str = try_opt!(rewrite_guard(
1722 trimmed_last_line_width(&pats_str),
1725 let pats_str = format!("{}{}", pats_str, guard_str);
1727 let (mut extend, body) = match body.node {
1728 ast::ExprKind::Block(ref block)
1729 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) &&
1730 context.config.wrap_match_arms() => {
1731 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1737 ast::ExprKind::Call(_, ref args) => (args.len() == 1, &**body),
1738 ast::ExprKind::Closure(..) |
1739 ast::ExprKind::Struct(..) |
1740 ast::ExprKind::Tup(..) => (true, &**body),
1741 _ => (false, &**body),
1743 extend &= context.use_block_indent();
1745 let comma = arm_comma(&context.config, body);
1747 String::from("\n") + &shape.indent.block_only().to_string(context.config);
1749 let pat_width = extra_offset(&pats_str, shape);
1750 // Let's try and get the arm body on the same line as the condition.
1752 if shape.width > pat_width + comma.len() + 4 {
1753 let arm_shape = shape
1754 .offset_left(pat_width + 4)
1756 .sub_width(comma.len())
1758 let rewrite = nop_block_collapse(
1759 format_expr(body, ExprType::Statement, context, arm_shape),
1762 let is_block = if let ast::ExprKind::Block(..) = body.node {
1770 if (!body_str.contains('\n') && body_str.len() <= arm_shape.width) ||
1771 !context.config.wrap_match_arms() ||
1772 (extend && first_line_width(body_str) <= arm_shape.width) ||
1774 let block_sep = match context.config.control_brace_style() {
1775 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep.as_str(),
1779 return Some(format!(
1781 attr_str.trim_left(),
1792 // FIXME: we're doing a second rewrite of the expr; This may not be
1794 let body_shape = try_opt!(shape.block_left(context.config.tab_spaces()));
1795 let next_line_body = try_opt!(nop_block_collapse(
1796 format_expr(body, ExprType::Statement, context, body_shape),
1799 let indent_str = shape
1801 .block_indent(context.config)
1802 .to_string(context.config);
1803 let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1804 if context.config.match_block_trailing_comma() {
1814 let block_sep = match context.config.control_brace_style() {
1815 ControlBraceStyle::AlwaysNextLine => alt_block_sep + body_prefix + "\n",
1816 _ if body_prefix.is_empty() => "\n".to_owned(),
1817 _ => " ".to_owned() + body_prefix + "\n",
1820 if context.config.wrap_match_arms() {
1822 "{}{} =>{}{}{}\n{}{}",
1823 attr_str.trim_left(),
1828 shape.indent.to_string(context.config),
1834 attr_str.trim_left(),
1845 // A pattern is simple if it is very short or it is short-ish and just a path.
1846 // E.g. `Foo::Bar` is simple, but `Foo(..)` is not.
1847 fn pat_is_simple(pat_str: &str) -> bool {
1848 pat_str.len() <= 16 ||
1849 (pat_str.len() <= 24 && pat_str.chars().all(|c| c.is_alphabetic() || c == ':'))
1852 // The `if ...` guard on a match arm.
1854 context: &RewriteContext,
1855 guard: &Option<ptr::P<ast::Expr>>,
1857 // The amount of space used up on this line for the pattern in
1858 // the arm (excludes offset).
1859 pattern_width: usize,
1860 ) -> Option<String> {
1861 if let Some(ref guard) = *guard {
1862 // First try to fit the guard string on the same line as the pattern.
1863 // 4 = ` if `, 5 = ` => {`
1864 if let Some(cond_shape) = shape
1865 .shrink_left(pattern_width + 4)
1866 .and_then(|s| s.sub_width(5))
1868 if let Some(cond_str) = guard
1869 .rewrite(context, cond_shape)
1870 .and_then(|s| s.rewrite(context, cond_shape))
1872 if !cond_str.contains('\n') {
1873 return Some(format!(" if {}", cond_str));
1878 // Not enough space to put the guard after the pattern, try a newline.
1880 if let Some(cond_shape) = Shape::indented(
1881 shape.indent.block_indent(context.config) + 3,
1885 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1886 return Some(format!(
1890 .block_indent(context.config)
1891 .to_string(context.config),
1903 fn rewrite_pat_expr(
1904 context: &RewriteContext,
1905 pat: Option<&ast::Pat>,
1908 // Connecting piece between pattern and expression,
1909 // *without* trailing space.
1913 ) -> Option<String> {
1914 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1915 let mut pat_string = String::new();
1916 let mut result = match pat {
1918 let matcher = if matcher.is_empty() {
1921 format!("{} ", matcher)
1924 try_opt!(try_opt!(shape.offset_left(matcher.len())).sub_width(connector.len()));
1925 pat_string = try_opt!(pat.rewrite(context, pat_shape));
1926 format!("{}{}{}", matcher, pat_string, connector)
1928 None => String::new(),
1931 // Consider only the last line of the pat string.
1932 let extra_offset = extra_offset(&result, shape);
1934 // The expression may (partially) fit on the current line.
1935 if shape.width > extra_offset + 1 {
1936 let spacer = if pat.is_some() { " " } else { "" };
1938 let expr_shape = try_opt!(shape.offset_left(extra_offset + spacer.len()));
1939 let expr_rewrite = expr.rewrite(context, expr_shape);
1941 if let Some(expr_string) = expr_rewrite {
1942 if pat.is_none() || pat_is_simple(&pat_string) || !expr_string.contains('\n') {
1943 result.push_str(spacer);
1944 result.push_str(&expr_string);
1945 return Some(result);
1950 if pat.is_none() && keyword == "if" {
1954 let nested_indent = shape.indent.block_only().block_indent(context.config);
1956 // The expression won't fit on the current line, jump to next.
1958 result.push_str(&nested_indent.to_string(context.config));
1960 let expr_rewrite = expr.rewrite(&context, Shape::indented(nested_indent, context.config));
1961 result.push_str(&try_opt!(expr_rewrite));
1966 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1967 let string_lit = context.snippet(span);
1969 if !context.config.format_strings() && !context.config.force_format_strings() {
1974 .all(|line| line.ends_with('\\'))
1976 let new_indent = shape.visual_indent(1).indent;
1977 return Some(String::from(
1981 new_indent.to_string(context.config) + line.trim_left()
1983 .collect::<Vec<_>>()
1988 return Some(string_lit);
1992 if !context.config.force_format_strings() &&
1993 !string_requires_rewrite(context, span, &string_lit, shape)
1995 return Some(string_lit);
1998 let fmt = StringFormat {
2005 config: context.config,
2008 // Remove the quote characters.
2009 let str_lit = &string_lit[1..string_lit.len() - 1];
2011 rewrite_string(str_lit, &fmt)
2014 fn string_requires_rewrite(
2015 context: &RewriteContext,
2020 if context.codemap.lookup_char_pos(span.lo).col.0 != shape.indent.width() {
2024 for (i, line) in string.lines().enumerate() {
2026 if line.len() > shape.width {
2030 if line.len() > shape.width + shape.indent.width() {
2039 pub fn rewrite_call_with_binary_search<R>(
2040 context: &RewriteContext,
2042 args: &[&ast::Expr],
2049 let force_trailing_comma = if context.inside_macro {
2050 span_ends_with_comma(context, span)
2054 let closure = |callee_max_width| {
2055 // FIXME using byte lens instead of char lens (and probably all over the
2057 let callee_shape = Shape {
2058 width: callee_max_width,
2061 let callee_str = callee
2062 .rewrite(context, callee_shape)
2063 .ok_or(Ordering::Greater)?;
2071 context.config.fn_call_width(),
2072 force_trailing_comma,
2076 binary_search(1, shape.width, closure)
2079 pub fn rewrite_call(
2080 context: &RewriteContext,
2082 args: &[ptr::P<ast::Expr>],
2085 ) -> Option<String> {
2086 let force_trailing_comma = if context.inside_macro {
2087 span_ends_with_comma(context, span)
2094 &args.iter().map(|x| &**x).collect::<Vec<_>>(),
2097 context.config.fn_call_width(),
2098 force_trailing_comma,
2102 pub fn rewrite_call_inner<'a, T>(
2103 context: &RewriteContext,
2108 args_max_width: usize,
2109 force_trailing_comma: bool,
2110 ) -> Result<String, Ordering>
2112 T: Rewrite + Spanned + ToExpr + 'a,
2114 // 2 = `( `, 1 = `(`
2115 let paren_overhead = if context.config.spaces_within_parens() {
2120 let used_width = extra_offset(&callee_str, shape);
2121 let one_line_width = shape
2123 .checked_sub(used_width + 2 * paren_overhead)
2124 .ok_or(Ordering::Greater)?;
2126 let nested_shape = shape_from_fn_call_style(
2129 used_width + 2 * paren_overhead,
2130 used_width + paren_overhead,
2131 ).ok_or(Ordering::Greater)?;
2133 let span_lo = context.codemap.span_after(span, "(");
2134 let args_span = mk_sp(span_lo, span.hi);
2136 let (extendable, list_str) = rewrite_call_args(
2143 force_trailing_comma,
2144 ).or_else(|| if context.use_block_indent() {
2150 shape.block().indent.block_indent(context.config),
2155 force_trailing_comma,
2160 .ok_or(Ordering::Less)?;
2162 if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
2163 let mut new_context = context.clone();
2164 new_context.use_block = true;
2165 return rewrite_call_inner(
2172 force_trailing_comma,
2176 let args_shape = shape
2177 .sub_width(last_line_width(&callee_str))
2178 .ok_or(Ordering::Less)?;
2182 wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2186 fn need_block_indent(s: &str, shape: Shape) -> bool {
2187 s.lines().skip(1).any(|s| {
2188 s.find(|c| !char::is_whitespace(c))
2189 .map_or(false, |w| w + 1 < shape.indent.width())
2193 fn rewrite_call_args<'a, T>(
2194 context: &RewriteContext,
2198 one_line_width: usize,
2199 args_max_width: usize,
2200 force_trailing_comma: bool,
2201 ) -> Option<(bool, String)>
2203 T: Rewrite + Spanned + ToExpr + 'a,
2205 let items = itemize_list(
2209 |item| item.span().lo,
2210 |item| item.span().hi,
2211 |item| item.rewrite(context, shape),
2215 let mut item_vec: Vec<_> = items.collect();
2217 // Try letting the last argument overflow to the next line with block
2218 // indentation. If its first line fits on one line with the other arguments,
2219 // we format the function arguments horizontally.
2220 let tactic = try_overflow_last_arg(
2229 let fmt = ListFormatting {
2232 trailing_separator: if force_trailing_comma {
2233 SeparatorTactic::Always
2234 } else if context.inside_macro || !context.use_block_indent() {
2235 SeparatorTactic::Never
2237 context.config.trailing_comma()
2240 ends_with_newline: context.use_block_indent() && tactic == DefinitiveListTactic::Vertical,
2241 config: context.config,
2244 write_list(&item_vec, &fmt).map(|args_str| {
2245 (tactic != DefinitiveListTactic::Vertical, args_str)
2249 fn try_overflow_last_arg<'a, T>(
2250 context: &RewriteContext,
2251 item_vec: &mut Vec<ListItem>,
2254 one_line_width: usize,
2255 args_max_width: usize,
2256 ) -> DefinitiveListTactic
2258 T: Rewrite + Spanned + ToExpr + 'a,
2260 let overflow_last = can_be_overflowed(&context, args);
2262 // Replace the last item with its first line to see if it fits with
2264 let (orig_last, placeholder) = if overflow_last {
2265 let mut context = context.clone();
2266 if let Some(expr) = args[args.len() - 1].to_expr() {
2268 ast::ExprKind::MethodCall(..) => context.force_one_line_chain = true,
2272 last_arg_shape(&context, &item_vec, shape, args_max_width)
2273 .map_or((None, None), |arg_shape| {
2274 rewrite_last_arg_with_overflow(
2277 &mut item_vec[args.len() - 1],
2285 let tactic = definitive_tactic(
2287 ListTactic::LimitedHorizontalVertical(args_max_width),
2291 // Replace the stub with the full overflowing last argument if the rewrite
2292 // succeeded and its first line fits with the other arguments.
2293 match (overflow_last, tactic, placeholder) {
2294 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2295 item_vec[args.len() - 1].item = placeholder;
2298 item_vec[args.len() - 1].item = orig_last;
2307 context: &RewriteContext,
2308 items: &Vec<ListItem>,
2310 args_max_width: usize,
2311 ) -> Option<Shape> {
2312 let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
2313 acc + i.item.as_ref().map_or(0, |s| first_line_width(&s))
2315 let max_width = min(args_max_width, shape.width);
2316 let arg_indent = if context.use_block_indent() {
2317 shape.block().indent.block_unindent(context.config)
2319 shape.block().indent
2322 width: try_opt!(max_width.checked_sub(overhead)),
2328 // Rewriting closure which is placed at the end of the function call's arg.
2329 // Returns `None` if the reformatted closure 'looks bad'.
2330 fn rewrite_last_closure(
2331 context: &RewriteContext,
2334 ) -> Option<String> {
2335 if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
2336 let body = match body.node {
2337 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
2338 stmt_expr(&block.stmts[0]).unwrap_or(body)
2342 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
2350 // If the closure goes multi line before its body, do not overflow the closure.
2351 if prefix.contains('\n') {
2354 let body_shape = try_opt!(shape.offset_left(extra_offset));
2355 // When overflowing the closure which consists of a single control flow expression,
2356 // force to use block if its condition uses multi line.
2357 if rewrite_cond(context, body, body_shape)
2358 .map(|cond| cond.contains('\n'))
2361 return rewrite_closure_with_block(context, body_shape, &prefix, body);
2364 // Seems fine, just format the closure in usual manner.
2365 return expr.rewrite(context, shape);
2370 fn rewrite_last_arg_with_overflow<'a, T>(
2371 context: &RewriteContext,
2373 last_item: &mut ListItem,
2375 ) -> (Option<String>, Option<String>)
2377 T: Rewrite + Spanned + ToExpr + 'a,
2379 let last_arg = args[args.len() - 1];
2380 let rewrite = if let Some(expr) = last_arg.to_expr() {
2382 // When overflowing the closure which consists of a single control flow expression,
2383 // force to use block if its condition uses multi line.
2384 ast::ExprKind::Closure(..) => {
2385 // If the argument consists of multiple closures, we do not overflow
2386 // the last closure.
2387 if args.len() > 1 &&
2391 .filter_map(|arg| arg.to_expr())
2392 .any(|expr| match expr.node {
2393 ast::ExprKind::Closure(..) => true,
2398 rewrite_last_closure(context, expr, shape)
2401 _ => expr.rewrite(context, shape),
2404 last_arg.rewrite(context, shape)
2406 let orig_last = last_item.item.clone();
2408 if let Some(rewrite) = rewrite {
2409 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2410 last_item.item = rewrite_first_line;
2411 (orig_last, Some(rewrite))
2417 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2419 T: Rewrite + Spanned + ToExpr + 'a,
2422 .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2425 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2427 ast::ExprKind::Match(..) => {
2428 (context.use_block_indent() && args_len == 1) ||
2429 (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
2431 ast::ExprKind::If(..) |
2432 ast::ExprKind::IfLet(..) |
2433 ast::ExprKind::ForLoop(..) |
2434 ast::ExprKind::Loop(..) |
2435 ast::ExprKind::While(..) |
2436 ast::ExprKind::WhileLet(..) => {
2437 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2439 ast::ExprKind::Block(..) |
2440 ast::ExprKind::Closure(..) => {
2441 context.use_block_indent() ||
2442 context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
2444 ast::ExprKind::Array(..) |
2445 ast::ExprKind::Call(..) |
2446 ast::ExprKind::Mac(..) |
2447 ast::ExprKind::MethodCall(..) |
2448 ast::ExprKind::Struct(..) |
2449 ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2450 ast::ExprKind::AddrOf(_, ref expr) |
2451 ast::ExprKind::Box(ref expr) |
2452 ast::ExprKind::Try(ref expr) |
2453 ast::ExprKind::Unary(_, ref expr) |
2454 ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2459 pub fn wrap_args_with_parens(
2460 context: &RewriteContext,
2462 is_extendable: bool,
2464 nested_shape: Shape,
2466 if !context.use_block_indent() ||
2467 (context.inside_macro && !args_str.contains('\n') &&
2468 args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2470 if context.config.spaces_within_parens() && args_str.len() > 0 {
2471 format!("( {} )", args_str)
2473 format!("({})", args_str)
2478 nested_shape.indent.to_string(context.config),
2480 shape.block().indent.to_string(context.config)
2485 fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2486 let snippet = context.snippet(span);
2488 .trim_right_matches(|c: char| c == ')' || c.is_whitespace())
2492 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2493 debug!("rewrite_paren, shape: {:?}", shape);
2494 let paren_overhead = paren_overhead(context);
2495 let sub_shape = try_opt!(shape.sub_width(paren_overhead / 2)).visual_indent(paren_overhead / 2);
2497 let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && s.len() > 0 {
2498 format!("( {} )", s)
2503 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2504 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2506 if subexpr_str.contains('\n') {
2507 Some(paren_wrapper(&subexpr_str))
2509 if subexpr_str.len() + paren_overhead <= shape.width {
2510 Some(paren_wrapper(&subexpr_str))
2512 let sub_shape = try_opt!(shape.offset_left(2));
2513 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2514 Some(paren_wrapper(&subexpr_str))
2522 context: &RewriteContext,
2524 ) -> Option<String> {
2525 let expr_str = try_opt!(expr.rewrite(context, shape));
2527 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
2533 let offset = expr_str.len() + lbr.len();
2534 let orig_index_rw = shape
2535 .visual_indent(offset)
2536 .sub_width(offset + rbr.len())
2537 .and_then(|index_shape| index.rewrite(context, index_shape));
2539 // Return if everything fits in a single line.
2540 match orig_index_rw {
2541 Some(ref index_str) if !index_str.contains('\n') => {
2542 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2547 // Try putting index on the next line and see if it fits in a single line.
2548 let indent = shape.indent.block_indent(&context.config);
2549 let rhs_overhead = context
2552 .checked_sub(shape.used_width() + shape.width)
2554 let index_shape = try_opt!(Shape::indented(indent, context.config).offset_left(lbr.len()));
2555 let index_shape = try_opt!(index_shape.sub_width(rbr.len() + rhs_overhead));
2556 let new_index_rw = index.rewrite(context, index_shape);
2557 match (orig_index_rw, new_index_rw) {
2558 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => {
2562 indent.to_string(&context.config),
2568 (None, Some(ref new_index_str)) => {
2572 indent.to_string(&context.config),
2578 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2583 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2588 fields.iter().all(|field| !field.is_shorthand)
2591 fn rewrite_struct_lit<'a>(
2592 context: &RewriteContext,
2594 fields: &'a [ast::Field],
2595 base: Option<&'a ast::Expr>,
2598 ) -> Option<String> {
2599 debug!("rewrite_struct_lit: shape {:?}", shape);
2601 enum StructLitField<'a> {
2602 Regular(&'a ast::Field),
2603 Base(&'a ast::Expr),
2607 let path_shape = try_opt!(shape.sub_width(2));
2608 let path_str = try_opt!(rewrite_path(
2616 if fields.len() == 0 && base.is_none() {
2617 return Some(format!("{} {{}}", path_str));
2620 // Foo { a: Foo } - indent is +3, width is -5.
2621 let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
2623 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2624 let body_lo = context.codemap.span_after(span, "{");
2625 let fields_str = if struct_lit_can_be_aligned(fields, &base) &&
2626 context.config.struct_field_align_threshold() > 0
2628 try_opt!(rewrite_with_alignment(
2632 mk_sp(body_lo, span.hi),
2636 let field_iter = fields
2638 .map(StructLitField::Regular)
2639 .chain(base.into_iter().map(StructLitField::Base));
2641 let span_lo = |item: &StructLitField| match *item {
2642 StructLitField::Regular(field) => field.span().lo,
2643 StructLitField::Base(expr) => {
2644 let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
2645 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
2646 let pos = snippet.find_uncommented("..").unwrap();
2647 last_field_hi + BytePos(pos as u32)
2650 let span_hi = |item: &StructLitField| match *item {
2651 StructLitField::Regular(field) => field.span().hi,
2652 StructLitField::Base(expr) => expr.span.hi,
2654 let rewrite = |item: &StructLitField| match *item {
2655 StructLitField::Regular(field) => {
2656 // The 1 taken from the v_budget is for the comma.
2657 rewrite_field(context, field, try_opt!(v_shape.sub_width(1)), 0)
2659 StructLitField::Base(expr) => {
2661 expr.rewrite(context, try_opt!(v_shape.shrink_left(2)))
2662 .map(|s| format!("..{}", s))
2666 let items = itemize_list(
2676 let item_vec = items.collect::<Vec<_>>();
2678 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2679 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2680 let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2682 try_opt!(write_list(&item_vec, &fmt))
2685 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2686 Some(format!("{} {{{}}}", path_str, fields_str))
2688 // FIXME if context.config.struct_lit_style() == Visual, but we run out
2689 // of space, we should fall back to BlockIndent.
2692 pub fn wrap_struct_field(
2693 context: &RewriteContext,
2696 nested_shape: Shape,
2697 one_line_width: usize,
2699 if context.config.struct_lit_style() == IndentStyle::Block &&
2700 (fields_str.contains('\n') ||
2701 context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti ||
2702 fields_str.len() > one_line_width)
2706 nested_shape.indent.to_string(context.config),
2708 shape.indent.to_string(context.config)
2711 // One liner or visual indent.
2712 format!(" {} ", fields_str)
2716 pub fn struct_lit_field_separator(config: &Config) -> &str {
2718 config.space_before_struct_lit_field_colon(),
2719 config.space_after_struct_lit_field_colon(),
2723 pub fn rewrite_field(
2724 context: &RewriteContext,
2727 prefix_max_width: usize,
2728 ) -> Option<String> {
2729 if contains_skip(&field.attrs) {
2731 context.snippet(field.span()),
2732 context.config.max_width(),
2736 let name = &field.ident.node.to_string();
2737 if field.is_shorthand {
2738 Some(name.to_string())
2740 let mut separator = String::from(struct_lit_field_separator(context.config));
2741 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2742 separator.push(' ');
2744 let overhead = name.len() + separator.len();
2745 let expr_shape = try_opt!(shape.offset_left(overhead));
2746 let expr = field.expr.rewrite(context, expr_shape);
2748 let mut attrs_str = try_opt!(field.attrs.rewrite(context, shape));
2749 if !attrs_str.is_empty() {
2750 attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2754 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2756 let expr_offset = shape.indent.block_indent(context.config);
2759 .rewrite(context, Shape::indented(expr_offset, context.config));
2765 expr_offset.to_string(&context.config),
2774 fn shape_from_fn_call_style(
2775 context: &RewriteContext,
2779 ) -> Option<Shape> {
2780 if context.use_block_indent() {
2784 .block_indent(context.config.tab_spaces())
2785 .with_max_width(context.config)
2788 shape.visual_indent(offset).sub_width(overhead)
2792 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2793 context: &RewriteContext,
2799 T: Rewrite + Spanned + ToExpr + 'a,
2801 let mut items = items.iter();
2802 // In case of length 1, need a trailing comma
2803 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2804 if items.len() == 1 {
2806 let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
2807 return items.next().unwrap().rewrite(context, nested_shape).map(
2808 |s| if context.config.spaces_within_parens() {
2809 format!("( {}, )", s)
2816 let list_lo = context.codemap.span_after(span, "(");
2817 let nested_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
2818 let items = itemize_list(
2822 |item| item.span().lo,
2823 |item| item.span().hi,
2824 |item| item.rewrite(context, nested_shape),
2826 span.hi - BytePos(1),
2828 let item_vec: Vec<_> = items.collect();
2829 let tactic = definitive_tactic(
2831 ListTactic::HorizontalVertical,
2834 let fmt = ListFormatting {
2837 trailing_separator: SeparatorTactic::Never,
2839 ends_with_newline: false,
2840 config: context.config,
2842 let list_str = try_opt!(write_list(&item_vec, &fmt));
2844 if context.config.spaces_within_parens() && list_str.len() > 0 {
2845 Some(format!("( {} )", list_str))
2847 Some(format!("({})", list_str))
2851 pub fn rewrite_tuple<'a, T>(
2852 context: &RewriteContext,
2858 T: Rewrite + Spanned + ToExpr + 'a,
2860 debug!("rewrite_tuple {:?}", shape);
2861 if context.use_block_indent() {
2862 // We use the same rule as funcation call for rewriting tuple.
2863 let force_trailing_comma = if context.inside_macro {
2864 span_ends_with_comma(context, span)
2874 context.config.fn_call_width(),
2875 force_trailing_comma,
2878 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2882 pub fn rewrite_unary_prefix<R: Rewrite>(
2883 context: &RewriteContext,
2887 ) -> Option<String> {
2889 .rewrite(context, try_opt!(shape.offset_left(prefix.len())))
2890 .map(|r| format!("{}{}", prefix, r))
2893 // FIXME: this is probably not correct for multi-line Rewrites. we should
2894 // subtract suffix.len() from the last line budget, not the first!
2895 pub fn rewrite_unary_suffix<R: Rewrite>(
2896 context: &RewriteContext,
2900 ) -> Option<String> {
2902 .rewrite(context, try_opt!(shape.sub_width(suffix.len())))
2909 fn rewrite_unary_op(
2910 context: &RewriteContext,
2914 ) -> Option<String> {
2915 // For some reason, an UnOp is not spanned like BinOp!
2916 let operator_str = match *op {
2917 ast::UnOp::Deref => "*",
2918 ast::UnOp::Not => "!",
2919 ast::UnOp::Neg => "-",
2921 rewrite_unary_prefix(context, operator_str, expr, shape)
2924 fn rewrite_assignment(
2925 context: &RewriteContext,
2928 op: Option<&ast::BinOp>,
2930 ) -> Option<String> {
2931 let operator_str = match op {
2932 Some(op) => context.snippet(op.span),
2933 None => "=".to_owned(),
2936 // 1 = space between lhs and operator.
2937 let lhs_shape = try_opt!(shape.sub_width(operator_str.len() + 1));
2938 let lhs_str = format!(
2940 try_opt!(lhs.rewrite(context, lhs_shape)),
2944 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2947 // The left hand side must contain everything up to, and including, the
2948 // assignment operator.
2949 pub fn rewrite_assign_rhs<S: Into<String>>(
2950 context: &RewriteContext,
2954 ) -> Option<String> {
2955 let mut result = lhs.into();
2956 let last_line_width = last_line_width(&result) -
2957 if result.contains('\n') {
2958 shape.indent.width()
2962 // 1 = space between operator and rhs.
2963 let orig_shape = try_opt!(shape.offset_left(last_line_width + 1));
2964 let rhs = ex.rewrite(context, orig_shape);
2967 Some(ref new_str) if !new_str.contains('\n') => {
2969 result.push_str(new_str);
2972 // Expression did not fit on the same line as the identifier.
2973 // Try splitting the line and see if that works better.
2974 let new_shape = try_opt!(shape.block_left(context.config.tab_spaces()));
2975 let new_rhs = ex.rewrite(context, new_shape);
2978 match (rhs, new_rhs) {
2979 (Some(ref orig_rhs), Some(ref replacement_rhs))
2980 if prefer_next_line(orig_rhs, replacement_rhs) => {
2981 result.push_str(&format!("\n{}", new_shape.indent.to_string(context.config)));
2982 result.push_str(replacement_rhs);
2984 (None, Some(ref final_rhs)) => {
2985 result.push_str(&format!("\n{}", new_shape.indent.to_string(context.config)));
2986 result.push_str(final_rhs);
2988 (None, None) => return None,
2989 (Some(ref orig_rhs), _) => {
2991 result.push_str(orig_rhs);
3000 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {
3002 fn count_line_breaks(src: &str) -> usize {
3003 src.chars().filter(|&x| x == '\n').count()
3006 !next_line_rhs.contains('\n') ||
3007 count_line_breaks(orig_rhs) > count_line_breaks(next_line_rhs) + 1
3010 fn rewrite_expr_addrof(
3011 context: &RewriteContext,
3012 mutability: ast::Mutability,
3015 ) -> Option<String> {
3016 let operator_str = match mutability {
3017 ast::Mutability::Immutable => "&",
3018 ast::Mutability::Mutable => "&mut ",
3020 rewrite_unary_prefix(context, operator_str, expr, shape)
3024 fn to_expr(&self) -> Option<&ast::Expr>;
3025 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
3028 impl ToExpr for ast::Expr {
3029 fn to_expr(&self) -> Option<&ast::Expr> {
3033 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
3034 can_be_overflowed_expr(context, self, len)
3038 impl ToExpr for ast::Ty {
3039 fn to_expr(&self) -> Option<&ast::Expr> {
3043 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
3044 can_be_overflowed_type(context, self, len)
3048 impl<'a> ToExpr for TuplePatField<'a> {
3049 fn to_expr(&self) -> Option<&ast::Expr> {
3053 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
3054 can_be_overflowed_pat(context, self, len)
3058 impl<'a> ToExpr for ast::StructField {
3059 fn to_expr(&self) -> Option<&ast::Expr> {
3063 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {