1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use std::cmp::{min, Ordering};
13 use std::iter::ExactSizeIterator;
15 use syntax::{ast, ptr};
16 use syntax::codemap::{BytePos, CodeMap, Span};
17 use syntax::parse::classify;
19 use {Indent, Shape, Spanned};
20 use chains::rewrite_chain;
21 use codemap::{LineRangeUtils, SpanUtils};
22 use comment::{contains_comment, recover_comment_removed, rewrite_comment, FindUncommented};
23 use config::{Config, ControlBraceStyle, IndentStyle, MultilineStyle, Style};
24 use items::{span_hi_for_arg, span_lo_for_arg};
25 use lists::{definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting,
26 struct_lit_shape, struct_lit_tactic, write_list, DefinitiveListTactic, ListFormatting,
27 ListItem, ListTactic, Separator, SeparatorTactic};
28 use macros::{rewrite_macro, MacroPosition};
29 use patterns::{can_be_overflowed_pat, TuplePatField};
30 use rewrite::{Rewrite, RewriteContext};
31 use string::{rewrite_string, StringFormat};
32 use types::{can_be_overflowed_type, rewrite_path, PathContext};
33 use utils::{binary_search, colon_spaces, contains_skip, extra_offset, first_line_width,
34 inner_attributes, last_line_extendable, last_line_width, left_most_sub_expr, mk_sp,
35 outer_attributes, paren_overhead, semicolon_for_stmt, stmt_expr,
36 trimmed_last_line_width, wrap_str};
37 use vertical::rewrite_with_alignment;
38 use visitor::FmtVisitor;
40 impl Rewrite for ast::Expr {
41 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
42 format_expr(self, ExprType::SubExpression, context, shape)
52 fn combine_attr_and_expr(
53 context: &RewriteContext,
58 let attrs = outer_attributes(&expr.attrs);
59 let attr_str = try_opt!(attrs.rewrite(context, shape));
60 let separator = if attr_str.is_empty() {
63 // Try to recover comments between the attributes and the expression if available.
64 let missing_snippet = context.snippet(mk_sp(attrs[attrs.len() - 1].span.hi, expr.span.lo));
65 let comment_opening_pos = missing_snippet.chars().position(|c| c == '/');
66 let prefer_same_line = if let Some(pos) = comment_opening_pos {
67 !missing_snippet[..pos].contains('\n')
69 !missing_snippet.contains('\n')
72 let trimmed = missing_snippet.trim();
73 let missing_comment = if trimmed.is_empty() {
76 try_opt!(rewrite_comment(&trimmed, false, shape, context.config))
81 attr_str.len() + missing_comment.len() + 2 + first_line_width(expr_str);
82 let attr_expr_separator = if prefer_same_line && !missing_comment.starts_with("//") &&
83 one_line_width <= shape.width
87 format!("\n{}", shape.indent.to_string(context.config))
90 if missing_comment.is_empty() {
95 last_line_width(&attr_str) + 1 + first_line_width(&missing_comment);
96 let attr_comment_separator = if prefer_same_line && one_line_width <= shape.width {
99 format!("\n{}", shape.indent.to_string(context.config))
101 attr_comment_separator + &missing_comment + &attr_expr_separator
104 Some(format!("{}{}{}", attr_str, separator, expr_str))
110 context: &RewriteContext,
112 ) -> Option<String> {
113 skip_out_of_file_lines_range!(context, expr.span);
115 if contains_skip(&*expr.attrs) {
116 return Some(context.snippet(expr.span()));
119 let expr_rw = match expr.node {
120 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
121 expr_vec.iter().map(|e| &**e),
122 mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi),
127 ast::ExprKind::Lit(ref l) => match l.node {
128 ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
129 rewrite_string_lit(context, l.span, shape)
132 context.snippet(expr.span),
133 context.config.max_width(),
137 ast::ExprKind::Call(ref callee, ref args) => {
138 let inner_span = mk_sp(callee.span.hi, expr.span.hi);
139 rewrite_call_with_binary_search(
142 &args.iter().map(|x| &**x).collect::<Vec<_>>()[..],
147 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
148 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
149 // FIXME: format comments between operands and operator
154 &format!(" {} ", context.snippet(op.span)),
160 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
161 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
165 base.as_ref().map(|e| &**e),
169 ast::ExprKind::Tup(ref items) => rewrite_tuple(
171 &items.iter().map(|x| &**x).collect::<Vec<_>>()[..],
175 ast::ExprKind::If(..) |
176 ast::ExprKind::IfLet(..) |
177 ast::ExprKind::ForLoop(..) |
178 ast::ExprKind::Loop(..) |
179 ast::ExprKind::While(..) |
180 ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
181 .and_then(|control_flow| control_flow.rewrite(context, shape)),
182 ast::ExprKind::Block(ref block) => {
184 ExprType::Statement => {
185 if is_unsafe_block(block) {
186 block.rewrite(context, shape)
188 // Rewrite block without trying to put it in a single line.
189 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
192 let prefix = try_opt!(block_prefix(context, block, shape));
193 rewrite_block_with_visitor(context, &prefix, block, shape)
196 ExprType::SubExpression => block.rewrite(context, shape),
199 ast::ExprKind::Match(ref cond, ref arms) => {
200 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
202 ast::ExprKind::Path(ref qself, ref path) => {
203 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
205 ast::ExprKind::Assign(ref lhs, ref rhs) => {
206 rewrite_assignment(context, lhs, rhs, None, shape)
208 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
209 rewrite_assignment(context, lhs, rhs, Some(op), shape)
211 ast::ExprKind::Continue(ref opt_ident) => {
212 let id_str = match *opt_ident {
213 Some(ident) => format!(" {}", ident.node),
214 None => String::new(),
217 format!("continue{}", id_str),
218 context.config.max_width(),
222 ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
223 let id_str = match *opt_ident {
224 Some(ident) => format!(" {}", ident.node),
225 None => String::new(),
228 if let Some(ref expr) = *opt_expr {
229 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
232 format!("break{}", id_str),
233 context.config.max_width(),
238 ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
239 rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
241 ast::ExprKind::Try(..) |
242 ast::ExprKind::Field(..) |
243 ast::ExprKind::TupField(..) |
244 ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
245 ast::ExprKind::Mac(ref mac) => {
246 // Failure to rewrite a marco should not imply failure to
247 // rewrite the expression.
248 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
250 context.snippet(expr.span),
251 context.config.max_width(),
256 ast::ExprKind::Ret(None) => {
257 wrap_str("return".to_owned(), context.config.max_width(), shape)
259 ast::ExprKind::Ret(Some(ref expr)) => {
260 rewrite_unary_prefix(context, "return ", &**expr, shape)
262 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
263 ast::ExprKind::AddrOf(mutability, ref expr) => {
264 rewrite_expr_addrof(context, mutability, expr, shape)
266 ast::ExprKind::Cast(ref expr, ref ty) => {
267 rewrite_pair(&**expr, &**ty, "", " as ", "", context, shape)
269 ast::ExprKind::Type(ref expr, ref ty) => {
270 rewrite_pair(&**expr, &**ty, "", ": ", "", context, shape)
272 ast::ExprKind::Index(ref expr, ref index) => {
273 rewrite_index(&**expr, &**index, context, shape)
275 ast::ExprKind::Repeat(ref expr, ref repeats) => {
276 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
281 rewrite_pair(&**expr, &**repeats, lbr, "; ", rbr, context, shape)
283 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
284 let delim = match limits {
285 ast::RangeLimits::HalfOpen => "..",
286 ast::RangeLimits::Closed => "...",
289 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
291 ast::ExprKind::Lit(ref lit) => match lit.node {
292 ast::LitKind::FloatUnsuffixed(..) => {
293 context.snippet(lit.span).ends_with('.')
301 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
302 (Some(ref lhs), Some(ref rhs)) => {
303 let sp_delim = if context.config.spaces_around_ranges() {
304 format!(" {} ", delim)
305 } else if needs_space_before_range(context, lhs) {
306 format!(" {}", delim)
310 rewrite_pair(&**lhs, &**rhs, "", &sp_delim, "", context, shape)
312 (None, Some(ref rhs)) => {
313 let sp_delim = if context.config.spaces_around_ranges() {
314 format!("{} ", delim)
318 rewrite_unary_prefix(context, &sp_delim, &**rhs, shape)
320 (Some(ref lhs), None) => {
321 let sp_delim = if context.config.spaces_around_ranges() {
322 format!(" {}", delim)
326 rewrite_unary_suffix(context, &sp_delim, &**lhs, shape)
328 (None, None) => wrap_str(delim.into(), context.config.max_width(), shape),
331 // We do not format these expressions yet, but they should still
332 // satisfy our width restrictions.
333 ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => wrap_str(
334 context.snippet(expr.span),
335 context.config.max_width(),
338 ast::ExprKind::Catch(ref block) => {
339 if let rewrite @ Some(_) = rewrite_single_line_block(context, "do catch ", block, shape)
344 let budget = shape.width.checked_sub(9).unwrap_or(0);
348 try_opt!(block.rewrite(&context, Shape::legacy(budget, shape.indent)))
354 .and_then(|expr_str| {
355 recover_comment_removed(expr_str, expr.span, context, shape)
357 .and_then(|expr_str| {
358 combine_attr_and_expr(context, shape, expr, &expr_str)
362 pub fn rewrite_pair<LHS, RHS>(
368 context: &RewriteContext,
375 let sep = if infix.ends_with(' ') { " " } else { "" };
376 let infix = infix.trim_right();
377 let lhs_overhead = shape.used_width() + prefix.len() + infix.len();
378 let lhs_shape = Shape {
379 width: try_opt!(context.config.max_width().checked_sub(lhs_overhead)),
382 let lhs_result = try_opt!(
383 lhs.rewrite(context, lhs_shape)
384 .map(|lhs_str| format!("{}{}{}", prefix, lhs_str, infix))
387 // Try to the both lhs and rhs on the same line.
388 let rhs_orig_result = shape
389 .offset_left(last_line_width(&lhs_result) + suffix.len() + sep.len())
390 .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
391 if let Some(ref rhs_result) = rhs_orig_result {
392 // If the rhs looks like block expression, we allow it to stay on the same line
393 // with the lhs even if it is multi-lined.
394 let allow_same_line = rhs_result
397 .map(|first_line| first_line.ends_with('{'))
399 if !rhs_result.contains('\n') || allow_same_line {
400 return Some(format!("{}{}{}{}", lhs_result, sep, rhs_result, suffix));
404 // We have to use multiple lines.
405 // Re-evaluate the rhs because we have more space now:
406 let rhs_shape = match context.config.control_style() {
408 try_opt!(shape.sub_width(suffix.len() + prefix.len())).visual_indent(prefix.len())
411 // Try to calculate the initial constraint on the right hand side.
412 let rhs_overhead = shape.rhs_overhead(context.config);
414 Shape::indented(shape.indent.block_indent(context.config), context.config)
415 .sub_width(rhs_overhead)
419 let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape));
423 rhs_shape.indent.to_string(context.config),
429 pub fn rewrite_array<'a, I>(
432 context: &RewriteContext,
434 trailing_comma: bool,
437 I: Iterator<Item = &'a ast::Expr>,
439 let bracket_size = if context.config.spaces_within_square_brackets() {
445 let mut nested_shape = match context.config.array_layout() {
446 IndentStyle::Block => try_opt!(
449 .block_indent(context.config.tab_spaces())
450 .with_max_width(context.config)
453 IndentStyle::Visual => try_opt!(
455 .visual_indent(bracket_size)
456 .sub_width(bracket_size * 2)
460 let items = itemize_list(
466 |item| item.rewrite(context, nested_shape),
469 ).collect::<Vec<_>>();
471 if items.is_empty() {
472 if context.config.spaces_within_square_brackets() {
473 return Some("[ ]".to_string());
475 return Some("[]".to_string());
479 let has_long_item = items
481 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
483 let mut tactic = match context.config.array_layout() {
484 IndentStyle::Block => {
485 // FIXME wrong shape in one-line case
486 match shape.width.checked_sub(2 * bracket_size) {
489 ListTactic::LimitedHorizontalVertical(context.config.array_width());
490 definitive_tactic(&items, tactic, Separator::Comma, width)
492 None => DefinitiveListTactic::Vertical,
495 IndentStyle::Visual => if has_long_item || items.iter().any(ListItem::is_multiline) {
498 ListTactic::LimitedHorizontalVertical(context.config.array_width()),
503 DefinitiveListTactic::Mixed
506 let mut ends_with_newline = tactic.ends_with_newline(context.config.array_layout());
507 if context.config.array_horizontal_layout_threshold() > 0 &&
508 items.len() > context.config.array_horizontal_layout_threshold()
510 tactic = DefinitiveListTactic::Mixed;
511 ends_with_newline = false;
512 if context.config.array_layout() == IndentStyle::Block {
513 nested_shape = try_opt!(
515 .visual_indent(bracket_size)
516 .sub_width(bracket_size * 2)
521 let fmt = ListFormatting {
524 trailing_separator: if trailing_comma {
525 SeparatorTactic::Always
526 } else if context.inside_macro || context.config.array_layout() == IndentStyle::Visual {
527 SeparatorTactic::Never
529 SeparatorTactic::Vertical
532 ends_with_newline: ends_with_newline,
533 preserve_newline: false,
534 config: context.config,
536 let list_str = try_opt!(write_list(&items, &fmt));
538 let result = if context.config.array_layout() == IndentStyle::Visual ||
539 tactic != DefinitiveListTactic::Vertical
541 if context.config.spaces_within_square_brackets() && list_str.len() > 0 {
542 format!("[ {} ]", list_str)
544 format!("[{}]", list_str)
549 nested_shape.indent.to_string(context.config),
551 shape.block().indent.to_string(context.config)
558 // Return type is (prefix, extra_offset)
559 fn rewrite_closure_fn_decl(
560 capture: ast::CaptureBy,
561 fn_decl: &ast::FnDecl,
564 context: &RewriteContext,
566 ) -> Option<(String, usize)> {
567 let mover = if capture == ast::CaptureBy::Value {
572 // 4 = "|| {".len(), which is overconservative when the closure consists of
573 // a single expression.
574 let nested_shape = try_opt!(try_opt!(shape.shrink_left(mover.len())).sub_width(4));
577 let argument_offset = nested_shape.indent + 1;
578 let arg_shape = try_opt!(nested_shape.offset_left(1)).visual_indent(0);
579 let ret_str = try_opt!(fn_decl.output.rewrite(context, arg_shape));
581 let arg_items = itemize_list(
583 fn_decl.inputs.iter(),
585 |arg| span_lo_for_arg(arg),
586 |arg| span_hi_for_arg(context, arg),
587 |arg| arg.rewrite(context, arg_shape),
588 context.codemap.span_after(span, "|"),
591 let item_vec = arg_items.collect::<Vec<_>>();
592 // 1 = space between arguments and return type.
593 let horizontal_budget = nested_shape
595 .checked_sub(ret_str.len() + 1)
597 let tactic = definitive_tactic(
599 ListTactic::HorizontalVertical,
603 let arg_shape = match tactic {
604 DefinitiveListTactic::Horizontal => try_opt!(arg_shape.sub_width(ret_str.len() + 1)),
608 let fmt = ListFormatting {
611 trailing_separator: SeparatorTactic::Never,
613 ends_with_newline: false,
614 preserve_newline: true,
615 config: context.config,
617 let list_str = try_opt!(write_list(&item_vec, &fmt));
618 let mut prefix = format!("{}|{}|", mover, list_str);
619 // 1 = space between `|...|` and body.
620 let extra_offset = extra_offset(&prefix, shape) + 1;
622 if !ret_str.is_empty() {
623 if prefix.contains('\n') {
625 prefix.push_str(&argument_offset.to_string(context.config));
629 prefix.push_str(&ret_str);
632 Some((prefix, extra_offset))
635 // This functions is pretty messy because of the rules around closures and blocks:
636 // FIXME - the below is probably no longer true in full.
637 // * if there is a return type, then there must be braces,
638 // * given a closure with braces, whether that is parsed to give an inner block
639 // or not depends on if there is a return type and if there are statements
641 // * if the first expression in the body ends with a block (i.e., is a
642 // statement without needing a semi-colon), then adding or removing braces
643 // can change whether it is treated as an expression or statement.
645 capture: ast::CaptureBy,
646 fn_decl: &ast::FnDecl,
649 context: &RewriteContext,
651 ) -> Option<String> {
652 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
660 // 1 = space between `|...|` and body.
661 let body_shape = try_opt!(shape.offset_left(extra_offset));
663 if let ast::ExprKind::Block(ref block) = body.node {
664 // The body of the closure is an empty block.
665 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
666 return Some(format!("{} {{}}", prefix));
669 // Figure out if the block is necessary.
670 let needs_block = block.rules != ast::BlockCheckMode::Default || block.stmts.len() > 1 ||
671 context.inside_macro ||
672 block_contains_comment(block, context.codemap) ||
673 prefix.contains('\n');
675 let no_return_type = if let ast::FunctionRetTy::Default(_) = fn_decl.output {
680 if no_return_type && !needs_block {
681 // lock.stmts.len() == 1
682 if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
683 if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
690 // We need braces, but we might still prefer a one-liner.
691 let stmt = &block.stmts[0];
692 // 4 = braces and spaces.
693 if let Some(body_shape) = body_shape.sub_width(4) {
694 // Checks if rewrite succeeded and fits on a single line.
695 if let Some(rewrite) = and_one_line(stmt.rewrite(context, body_shape)) {
696 return Some(format!("{} {{ {} }}", prefix, rewrite));
701 // Either we require a block, or tried without and failed.
702 rewrite_closure_block(&block, &prefix, context, body_shape)
704 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
705 // The closure originally had a non-block expression, but we can't fit on
706 // one line, so we'll insert a block.
707 rewrite_closure_with_block(context, body_shape, &prefix, body)
712 // Rewrite closure with a single expression wrapping its body with block.
713 fn rewrite_closure_with_block(
714 context: &RewriteContext,
718 ) -> Option<String> {
719 let block = ast::Block {
722 id: ast::NodeId::new(0),
723 node: ast::StmtKind::Expr(ptr::P(body.clone())),
727 id: ast::NodeId::new(0),
728 rules: ast::BlockCheckMode::Default,
731 rewrite_closure_block(&block, prefix, context, shape)
734 // Rewrite closure with a single expression without wrapping its body with block.
735 fn rewrite_closure_expr(
738 context: &RewriteContext,
740 ) -> Option<String> {
741 let mut rewrite = expr.rewrite(context, shape);
742 if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
743 rewrite = and_one_line(rewrite);
745 rewrite.map(|rw| format!("{} {}", prefix, rw))
748 // Rewrite closure whose body is block.
749 fn rewrite_closure_block(
752 context: &RewriteContext,
754 ) -> Option<String> {
755 // Start with visual indent, then fall back to block indent if the
757 let block_threshold = context.config.closure_block_indent_threshold();
758 if block_threshold >= 0 {
759 if let Some(block_str) = block.rewrite(&context, shape) {
760 if block_str.matches('\n').count() <= block_threshold as usize &&
761 !need_block_indent(&block_str, shape)
763 if let Some(block_str) = block_str.rewrite(context, shape) {
764 return Some(format!("{} {}", prefix, block_str));
770 // The body of the closure is big enough to be block indented, that
771 // means we must re-format.
772 let block_shape = shape.block();
773 let block_str = try_opt!(block.rewrite(&context, block_shape));
774 Some(format!("{} {}", prefix, block_str))
777 fn and_one_line(x: Option<String>) -> Option<String> {
778 x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
781 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
782 debug!("nop_block_collapse {:?} {}", block_str, budget);
783 block_str.map(|block_str| {
784 if block_str.starts_with('{') && budget >= 2 &&
785 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
794 fn rewrite_empty_block(
795 context: &RewriteContext,
798 ) -> Option<String> {
799 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
801 return Some("{}".to_owned());
804 // If a block contains only a single-line comment, then leave it on one line.
805 let user_str = context.snippet(block.span);
806 let user_str = user_str.trim();
807 if user_str.starts_with('{') && user_str.ends_with('}') {
808 let comment_str = user_str[1..user_str.len() - 1].trim();
809 if block.stmts.is_empty() && !comment_str.contains('\n') &&
810 !comment_str.starts_with("//") && comment_str.len() + 4 <= shape.width
812 return Some(format!("{{ {} }}", comment_str));
819 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
820 Some(match block.rules {
821 ast::BlockCheckMode::Unsafe(..) => {
822 let snippet = context.snippet(block.span);
823 let open_pos = try_opt!(snippet.find_uncommented("{"));
824 // Extract comment between unsafe and block start.
825 let trimmed = &snippet[6..open_pos].trim();
827 if !trimmed.is_empty() {
828 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
829 let budget = try_opt!(shape.width.checked_sub(9));
832 try_opt!(rewrite_comment(
835 Shape::legacy(budget, shape.indent + 7),
843 ast::BlockCheckMode::Default => String::new(),
847 fn rewrite_single_line_block(
848 context: &RewriteContext,
852 ) -> Option<String> {
853 if is_simple_block(block, context.codemap) {
854 let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
855 let expr_str = try_opt!(block.stmts[0].rewrite(context, expr_shape));
856 let result = format!("{}{{ {} }}", prefix, expr_str);
857 if result.len() <= shape.width && !result.contains('\n') {
864 fn rewrite_block_with_visitor(
865 context: &RewriteContext,
869 ) -> Option<String> {
870 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
874 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
875 visitor.block_indent = shape.indent;
876 visitor.is_if_else_block = context.is_if_else_block;
878 ast::BlockCheckMode::Unsafe(..) => {
879 let snippet = context.snippet(block.span);
880 let open_pos = try_opt!(snippet.find_uncommented("{"));
881 visitor.last_pos = block.span.lo + BytePos(open_pos as u32)
883 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo,
886 visitor.visit_block(block, None);
887 Some(format!("{}{}", prefix, visitor.buffer))
890 impl Rewrite for ast::Block {
891 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
892 // shape.width is used only for the single line case: either the empty block `{}`,
893 // or an unsafe expression `unsafe { e }`.
894 if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
898 let prefix = try_opt!(block_prefix(context, self, shape));
899 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
903 rewrite_block_with_visitor(context, &prefix, self, shape)
907 impl Rewrite for ast::Stmt {
908 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
909 skip_out_of_file_lines_range!(context, self.span());
911 let result = match self.node {
912 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
913 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
914 let suffix = if semicolon_for_stmt(context, self) {
923 ast::StmtKind::Expr(_) => ExprType::SubExpression,
924 ast::StmtKind::Semi(_) => ExprType::Statement,
928 try_opt!(shape.sub_width(suffix.len())),
929 ).map(|s| s + suffix)
931 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
933 result.and_then(|res| {
934 recover_comment_removed(res, self.span(), context, shape)
939 // Rewrite condition if the given expression has one.
940 fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
942 ast::ExprKind::Match(ref cond, _) => {
944 let cond_shape = match context.config.control_style() {
945 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
946 Style::Rfc => try_opt!(shape.offset_left(8)),
948 cond.rewrite(context, cond_shape)
950 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
951 stmt_expr(&block.stmts[0]).and_then(|e| rewrite_cond(context, e, shape))
953 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
955 String::from("\n") + &shape.indent.block_only().to_string(context.config);
957 .rewrite_cond(context, shape, &alt_block_sep)
958 .and_then(|rw| Some(rw.0))
963 // Abstraction over control flow expressions
965 struct ControlFlow<'a> {
966 cond: Option<&'a ast::Expr>,
967 block: &'a ast::Block,
968 else_block: Option<&'a ast::Expr>,
969 label: Option<ast::SpannedIdent>,
970 pat: Option<&'a ast::Pat>,
974 allow_single_line: bool,
975 // True if this is an `if` expression in an `else if` :-( hacky
980 fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'a>> {
982 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
986 else_block.as_ref().map(|e| &**e),
987 expr_type == ExprType::SubExpression,
991 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
992 Some(ControlFlow::new_if(
996 else_block.as_ref().map(|e| &**e),
997 expr_type == ExprType::SubExpression,
1002 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
1003 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
1005 ast::ExprKind::Loop(ref block, label) => {
1006 Some(ControlFlow::new_loop(block, label, expr.span))
1008 ast::ExprKind::While(ref cond, ref block, label) => {
1009 Some(ControlFlow::new_while(None, cond, block, label, expr.span))
1011 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
1012 ControlFlow::new_while(Some(pat), cond, block, label, expr.span),
1018 impl<'a> ControlFlow<'a> {
1020 cond: &'a ast::Expr,
1021 pat: Option<&'a ast::Pat>,
1022 block: &'a ast::Block,
1023 else_block: Option<&'a ast::Expr>,
1024 allow_single_line: bool,
1027 ) -> ControlFlow<'a> {
1031 else_block: else_block,
1035 matcher: match pat {
1040 allow_single_line: allow_single_line,
1041 nested_if: nested_if,
1047 block: &'a ast::Block,
1048 label: Option<ast::SpannedIdent>,
1050 ) -> ControlFlow<'a> {
1060 allow_single_line: false,
1067 pat: Option<&'a ast::Pat>,
1068 cond: &'a ast::Expr,
1069 block: &'a ast::Block,
1070 label: Option<ast::SpannedIdent>,
1072 ) -> ControlFlow<'a> {
1080 matcher: match pat {
1085 allow_single_line: false,
1093 cond: &'a ast::Expr,
1094 block: &'a ast::Block,
1095 label: Option<ast::SpannedIdent>,
1097 ) -> ControlFlow<'a> {
1107 allow_single_line: false,
1113 fn rewrite_single_line(
1116 context: &RewriteContext,
1118 ) -> Option<String> {
1119 assert!(self.allow_single_line);
1120 let else_block = try_opt!(self.else_block);
1121 let fixed_cost = self.keyword.len() + " { } else { }".len();
1123 if let ast::ExprKind::Block(ref else_node) = else_block.node {
1124 if !is_simple_block(self.block, context.codemap) ||
1125 !is_simple_block(else_node, context.codemap) ||
1126 pat_expr_str.contains('\n')
1131 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
1132 let expr = &self.block.stmts[0];
1133 let if_str = try_opt!(expr.rewrite(
1135 Shape::legacy(new_width, Indent::empty()),
1138 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
1139 let else_expr = &else_node.stmts[0];
1141 try_opt!(else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
1143 if if_str.contains('\n') || else_str.contains('\n') {
1147 let result = format!(
1148 "{} {} {{ {} }} else {{ {} }}",
1155 if result.len() <= width {
1156 return Some(result);
1164 impl<'a> ControlFlow<'a> {
1167 context: &RewriteContext,
1169 alt_block_sep: &str,
1170 ) -> Option<(String, usize)> {
1171 // Do not take the rhs overhead from the upper expressions into account
1172 // when rewriting pattern.
1173 let new_width = context
1176 .checked_sub(shape.used_width())
1178 let fresh_shape = Shape {
1182 let constr_shape = if self.nested_if {
1183 // We are part of an if-elseif-else chain. Our constraints are tightened.
1184 // 7 = "} else " .len()
1185 try_opt!(fresh_shape.offset_left(7))
1190 let label_string = rewrite_label(self.label);
1191 // 1 = space after keyword.
1192 let offset = self.keyword.len() + label_string.len() + 1;
1194 let pat_expr_string = match self.cond {
1196 let cond_shape = match context.config.control_style() {
1197 Style::Legacy => try_opt!(constr_shape.shrink_left(offset)),
1198 Style::Rfc => try_opt!(constr_shape.offset_left(offset)),
1200 try_opt!(rewrite_pat_expr(
1210 None => String::new(),
1213 let brace_overhead =
1214 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1220 let one_line_budget = context
1223 .checked_sub(constr_shape.used_width() + offset + brace_overhead)
1225 let force_newline_brace = context.config.control_style() == Style::Rfc &&
1226 (pat_expr_string.contains('\n') || pat_expr_string.len() > one_line_budget) &&
1227 !last_line_extendable(&pat_expr_string);
1229 // Try to format if-else on single line.
1230 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1231 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1233 if let Some(cond_str) = trial {
1234 if cond_str.len() <= context.config.single_line_if_else_max_width() {
1235 return Some((cond_str, 0));
1240 let cond_span = if let Some(cond) = self.cond {
1243 mk_sp(self.block.span.lo, self.block.span.lo)
1246 // for event in event
1247 let between_kwd_cond = mk_sp(
1248 context.codemap.span_after(self.span, self.keyword.trim()),
1251 |p| if self.matcher.is_empty() {
1254 context.codemap.span_before(self.span, self.matcher.trim())
1259 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1261 let after_cond_comment =
1262 extract_comment(mk_sp(cond_span.hi, self.block.span.lo), context, shape);
1264 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1266 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine ||
1274 let used_width = if pat_expr_string.contains('\n') {
1275 last_line_width(&pat_expr_string)
1277 // 2 = spaces after keyword and condition.
1278 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1286 between_kwd_cond_comment.as_ref().map_or(
1287 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1295 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1302 impl<'a> Rewrite for ControlFlow<'a> {
1303 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1304 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1307 String::from("\n") + &shape.indent.block_only().to_string(context.config);
1308 let (cond_str, used_width) = try_opt!(self.rewrite_cond(context, shape, &alt_block_sep));
1309 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1310 if used_width == 0 {
1311 return Some(cond_str);
1314 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1315 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1316 // we should avoid the single line case.
1317 let block_width = if self.else_block.is_some() || self.nested_if {
1322 let block_shape = Shape {
1326 let mut block_context = context.clone();
1327 block_context.is_if_else_block = self.else_block.is_some();
1328 let block_str = try_opt!(rewrite_block_with_visitor(
1335 let mut result = format!("{}{}", cond_str, block_str);
1337 if let Some(else_block) = self.else_block {
1338 let shape = Shape::indented(shape.indent, context.config);
1339 let mut last_in_chain = false;
1340 let rewrite = match else_block.node {
1341 // If the else expression is another if-else expression, prevent it
1342 // from being formatted on a single line.
1343 // Note how we're passing the original shape, as the
1344 // cost of "else" should not cascade.
1345 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1346 ControlFlow::new_if(
1350 next_else_block.as_ref().map(|e| &**e),
1353 mk_sp(else_block.span.lo, self.span.hi),
1354 ).rewrite(context, shape)
1356 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1357 ControlFlow::new_if(
1361 next_else_block.as_ref().map(|e| &**e),
1364 mk_sp(else_block.span.lo, self.span.hi),
1365 ).rewrite(context, shape)
1368 last_in_chain = true;
1369 // When rewriting a block, the width is only used for single line
1370 // blocks, passing 1 lets us avoid that.
1371 let else_shape = Shape {
1372 width: min(1, shape.width),
1375 format_expr(else_block, ExprType::Statement, context, else_shape)
1379 let between_kwd_else_block = mk_sp(
1383 .span_before(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1385 let between_kwd_else_block_comment =
1386 extract_comment(between_kwd_else_block, context, shape);
1388 let after_else = mk_sp(
1391 .span_after(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1394 let after_else_comment = extract_comment(after_else, context, shape);
1396 let between_sep = match context.config.control_brace_style() {
1397 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1400 ControlBraceStyle::AlwaysSameLine => " ",
1402 let after_sep = match context.config.control_brace_style() {
1403 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1410 between_kwd_else_block_comment
1412 .map_or(between_sep, |s| &**s),
1413 after_else_comment.as_ref().map_or(after_sep, |s| &**s)
1416 result.push_str(&try_opt!(rewrite));
1423 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
1425 Some(ident) => format!("{}: ", ident.node),
1426 None => "".to_owned(),
1430 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1431 let comment_str = context.snippet(span);
1432 if contains_comment(&comment_str) {
1433 let comment = try_opt!(rewrite_comment(
1440 "\n{indent}{}\n{indent}",
1442 indent = shape.indent.to_string(context.config)
1449 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1450 let snippet = codemap.span_to_snippet(block.span).unwrap();
1451 contains_comment(&snippet)
1454 // Checks that a block contains no statements, an expression and no comments.
1455 // FIXME: incorrectly returns false when comment is contained completely within
1457 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1458 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) &&
1459 !block_contains_comment(block, codemap))
1462 /// Checks whether a block contains at most one statement or expression, and no comments.
1463 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1464 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1467 /// Checks whether a block contains no statements, expressions, or comments.
1468 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1469 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1472 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1474 ast::StmtKind::Expr(..) => true,
1479 fn is_unsafe_block(block: &ast::Block) -> bool {
1480 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1487 // inter-match-arm-comment-rules:
1488 // - all comments following a match arm before the start of the next arm
1489 // are about the second arm
1490 fn rewrite_match_arm_comment(
1491 context: &RewriteContext,
1494 arm_indent_str: &str,
1495 ) -> Option<String> {
1496 // The leading "," is not part of the arm-comment
1497 let missed_str = match missed_str.find_uncommented(",") {
1498 Some(n) => &missed_str[n + 1..],
1499 None => &missed_str[..],
1502 let mut result = String::new();
1503 // any text not preceeded by a newline is pushed unmodified to the block
1504 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
1505 result.push_str(&missed_str[..first_brk]);
1506 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
1508 let first = missed_str
1509 .find(|c: char| !c.is_whitespace())
1510 .unwrap_or(missed_str.len());
1511 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
1512 // Excessive vertical whitespace before comment should be preserved
1513 // FIXME handle vertical whitespace better
1516 let missed_str = missed_str[first..].trim();
1517 if !missed_str.is_empty() {
1518 let comment = try_opt!(rewrite_comment(&missed_str, false, shape, context.config));
1520 result.push_str(arm_indent_str);
1521 result.push_str(&comment);
1528 context: &RewriteContext,
1533 attrs: &[ast::Attribute],
1534 ) -> Option<String> {
1535 if arms.is_empty() {
1539 // Do not take the rhs overhead from the upper expressions into account
1540 // when rewriting match condition.
1541 let new_width = try_opt!(context.config.max_width().checked_sub(shape.used_width()));
1542 let cond_shape = Shape {
1547 let cond_shape = match context.config.control_style() {
1548 Style::Legacy => try_opt!(cond_shape.shrink_left(6)),
1549 Style::Rfc => try_opt!(cond_shape.offset_left(6)),
1551 let cond_str = try_opt!(cond.rewrite(context, cond_shape));
1552 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1553 let block_sep = match context.config.control_brace_style() {
1554 ControlBraceStyle::AlwaysNextLine => &alt_block_sep,
1555 _ if last_line_extendable(&cond_str) => " ",
1557 _ if cond_str.contains('\n') || cond_str.len() + 2 > cond_shape.width => &alt_block_sep,
1561 let nested_indent_str = shape
1563 .block_indent(context.config)
1564 .to_string(context.config);
1565 // Inner attributes.
1566 let inner_attrs = &inner_attributes(attrs);
1567 let inner_attrs_str = if inner_attrs.is_empty() {
1572 .rewrite(context, shape)
1573 .map(|s| format!("\n{}{}", nested_indent_str, s))
1577 let open_brace_pos = if inner_attrs.is_empty() {
1580 .span_after(mk_sp(cond.span.hi, arms[0].span().lo), "{")
1582 inner_attrs[inner_attrs.len() - 1].span().hi
1586 "match {}{}{{{}{}\n{}}}",
1590 try_opt!(rewrite_match_arms(
1597 shape.indent.to_string(context.config),
1601 fn arm_comma(config: &Config, body: &ast::Expr) -> &'static str {
1602 if config.match_block_trailing_comma() {
1604 } else if let ast::ExprKind::Block(ref block) = body.node {
1605 if let ast::BlockCheckMode::Default = block.rules {
1615 fn rewrite_match_arms(
1616 context: &RewriteContext,
1620 open_brace_pos: BytePos,
1621 ) -> Option<String> {
1622 let mut result = String::new();
1624 let arm_shape = if context.config.indent_match_arms() {
1625 shape.block_indent(context.config.tab_spaces())
1627 shape.block_indent(0)
1628 }.with_max_width(context.config);
1629 let arm_indent_str = arm_shape.indent.to_string(context.config);
1631 let arm_num = arms.len();
1632 for (i, arm) in arms.iter().enumerate() {
1633 // Make sure we get the stuff between arms.
1634 let missed_str = if i == 0 {
1635 context.snippet(mk_sp(open_brace_pos, arm.span().lo))
1637 context.snippet(mk_sp(arms[i - 1].span().hi, arm.span().lo))
1639 let comment = try_opt!(rewrite_match_arm_comment(
1645 if !comment.chars().all(|c| c == ' ') {
1646 result.push_str(&comment);
1649 result.push_str(&arm_indent_str);
1651 let arm_str = rewrite_match_arm(context, arm, arm_shape);
1652 if let Some(ref arm_str) = arm_str {
1653 // Trim the trailing comma if necessary.
1654 if i == arm_num - 1 && context.config.trailing_comma() == SeparatorTactic::Never &&
1655 arm_str.ends_with(',')
1657 result.push_str(&arm_str[0..arm_str.len() - 1])
1659 result.push_str(arm_str)
1662 // We couldn't format the arm, just reproduce the source.
1663 let snippet = context.snippet(arm.span());
1664 result.push_str(&snippet);
1665 if context.config.trailing_comma() != SeparatorTactic::Never {
1666 result.push_str(arm_comma(context.config, &arm.body))
1670 // BytePos(1) = closing match brace.
1671 let last_span = mk_sp(arms[arms.len() - 1].span().hi, span.hi - BytePos(1));
1672 let last_comment = context.snippet(last_span);
1673 let comment = try_opt!(rewrite_match_arm_comment(
1679 result.push_str(&comment);
1684 fn rewrite_match_arm(context: &RewriteContext, arm: &ast::Arm, shape: Shape) -> Option<String> {
1685 let attr_str = if !arm.attrs.is_empty() {
1686 if contains_skip(&arm.attrs) {
1691 try_opt!(arm.attrs.rewrite(context, shape)),
1692 shape.indent.to_string(context.config)
1697 let pats_str = try_opt!(rewrite_match_pattern(context, &arm.pats, &arm.guard, shape));
1698 let pats_str = attr_str + &pats_str;
1699 rewrite_match_body(context, &arm.body, &pats_str, shape, arm.guard.is_some())
1702 fn rewrite_match_pattern(
1703 context: &RewriteContext,
1704 pats: &Vec<ptr::P<ast::Pat>>,
1705 guard: &Option<ptr::P<ast::Expr>>,
1707 ) -> Option<String> {
1710 let pat_shape = try_opt!(shape.sub_width(5));
1712 let pat_strs = try_opt!(
1714 .map(|p| p.rewrite(context, pat_shape))
1715 .collect::<Option<Vec<_>>>()
1718 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1719 let tactic = definitive_tactic(
1721 ListTactic::HorizontalVertical,
1722 Separator::VerticalBar,
1725 let fmt = ListFormatting {
1728 trailing_separator: SeparatorTactic::Never,
1730 ends_with_newline: false,
1731 preserve_newline: false,
1732 config: context.config,
1734 let pats_str = try_opt!(write_list(&items, &fmt));
1737 let guard_str = try_opt!(rewrite_guard(
1741 trimmed_last_line_width(&pats_str),
1744 Some(format!("{}{}", pats_str, guard_str))
1747 fn rewrite_match_body(
1748 context: &RewriteContext,
1749 body: &ptr::P<ast::Expr>,
1753 ) -> Option<String> {
1754 let (extend, body) = match body.node {
1755 ast::ExprKind::Block(ref block)
1756 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) =>
1758 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1759 (expr.can_be_overflowed(context, 1), &**expr)
1764 _ => (body.can_be_overflowed(context, 1), &**body),
1767 let comma = arm_comma(&context.config, body);
1768 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1769 let alt_block_sep = alt_block_sep.as_str();
1770 let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
1771 (true, is_empty_block(block, context.codemap))
1776 let combine_orig_body = |body_str: &str| {
1777 let block_sep = match context.config.control_brace_style() {
1778 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
1782 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
1785 let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
1786 let next_line_indent = if is_block {
1789 shape.indent.block_indent(context.config)
1791 let combine_next_line_body = |body_str: &str| {
1793 return Some(format!(
1796 next_line_indent.to_string(context.config),
1801 let indent_str = shape.indent.to_string(context.config);
1802 let nested_indent_str = next_line_indent.to_string(context.config);
1803 let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1804 let comma = if context.config.match_block_trailing_comma() {
1809 ("{", format!("\n{}}}{}", indent_str, comma))
1811 ("", String::from(","))
1814 let block_sep = match context.config.control_brace_style() {
1815 ControlBraceStyle::AlwaysNextLine => format!("{}{}\n", alt_block_sep, body_prefix),
1816 _ if body_prefix.is_empty() => "\n".to_owned(),
1817 _ if forbid_same_line => format!("{}{}\n", alt_block_sep, body_prefix),
1818 _ => format!(" {}\n", body_prefix),
1819 } + &nested_indent_str;
1830 // Let's try and get the arm body on the same line as the condition.
1832 let orig_body_shape = shape
1833 .offset_left(extra_offset(&pats_str, shape) + 4)
1834 .and_then(|shape| shape.sub_width(comma.len()));
1835 let orig_body = if let Some(body_shape) = orig_body_shape {
1836 let rewrite = nop_block_collapse(
1837 format_expr(body, ExprType::Statement, context, body_shape),
1843 if !forbid_same_line &&
1845 (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
1847 return combine_orig_body(body_str);
1854 let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
1856 // Try putting body on the next line and see if it looks better.
1857 let next_line_body_shape = Shape::indented(next_line_indent, context.config);
1858 let next_line_body = nop_block_collapse(
1859 format_expr(body, ExprType::Statement, context, next_line_body_shape),
1860 next_line_body_shape.width,
1862 match (orig_body, next_line_body) {
1863 (Some(ref orig_str), Some(ref next_line_str))
1864 if forbid_same_line || prefer_next_line(orig_str, next_line_str) =>
1866 combine_next_line_body(next_line_str)
1868 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
1869 combine_orig_body(orig_str)
1871 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
1872 combine_next_line_body(next_line_str)
1874 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
1875 (None, None) => None,
1876 (Some(ref orig_str), _) => combine_orig_body(orig_str),
1880 // The `if ...` guard on a match arm.
1882 context: &RewriteContext,
1883 guard: &Option<ptr::P<ast::Expr>>,
1885 // The amount of space used up on this line for the pattern in
1886 // the arm (excludes offset).
1887 pattern_width: usize,
1888 ) -> Option<String> {
1889 if let Some(ref guard) = *guard {
1890 // First try to fit the guard string on the same line as the pattern.
1891 // 4 = ` if `, 5 = ` => {`
1892 let cond_shape = shape
1893 .offset_left(pattern_width + 4)
1894 .and_then(|s| s.sub_width(5));
1895 if let Some(cond_shape) = cond_shape {
1896 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1897 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
1898 return Some(format!(" if {}", cond_str));
1903 // Not enough space to put the guard after the pattern, try a newline.
1904 // 3 = `if `, 5 = ` => {`
1905 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
1907 .and_then(|s| s.sub_width(5));
1908 if let Some(cond_shape) = cond_shape {
1909 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1910 return Some(format!(
1912 cond_shape.indent.to_string(context.config),
1924 fn rewrite_pat_expr(
1925 context: &RewriteContext,
1926 pat: Option<&ast::Pat>,
1929 // Connecting piece between pattern and expression,
1930 // *without* trailing space.
1934 ) -> Option<String> {
1935 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1936 if let Some(pat) = pat {
1937 let matcher = if matcher.is_empty() {
1940 format!("{} ", matcher)
1943 try_opt!(try_opt!(shape.offset_left(matcher.len())).sub_width(connector.len()));
1944 let pat_string = try_opt!(pat.rewrite(context, pat_shape));
1945 let result = format!("{}{}{}", matcher, pat_string, connector);
1946 return rewrite_assign_rhs(context, result, expr, shape);
1949 let expr_rw = expr.rewrite(context, shape);
1950 // The expression may (partially) fit on the current line.
1951 // We do not allow splitting between `if` and condition.
1952 if keyword == "if" || expr_rw.is_some() {
1956 // The expression won't fit on the current line, jump to next.
1957 let nested_shape = shape
1958 .block_indent(context.config.tab_spaces())
1959 .with_max_width(context.config);
1960 let nested_indent_str = nested_shape.indent.to_string(context.config);
1961 expr.rewrite(context, nested_shape)
1962 .map(|expr_rw| format!("\n{}{}", nested_indent_str, expr_rw))
1965 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1966 let string_lit = context.snippet(span);
1968 if !context.config.format_strings() && !context.config.force_format_strings() {
1973 .all(|line| line.ends_with('\\'))
1975 let new_indent = shape.visual_indent(1).indent;
1976 return Some(String::from(
1980 new_indent.to_string(context.config) + line.trim_left()
1982 .collect::<Vec<_>>()
1987 return Some(string_lit);
1991 if !context.config.force_format_strings() &&
1992 !string_requires_rewrite(context, span, &string_lit, shape)
1994 return Some(string_lit);
1997 let fmt = StringFormat {
2004 config: context.config,
2007 // Remove the quote characters.
2008 let str_lit = &string_lit[1..string_lit.len() - 1];
2010 rewrite_string(str_lit, &fmt)
2013 fn string_requires_rewrite(
2014 context: &RewriteContext,
2019 if context.codemap.lookup_char_pos(span.lo).col.0 != shape.indent.width() {
2023 for (i, line) in string.lines().enumerate() {
2025 if line.len() > shape.width {
2029 if line.len() > shape.width + shape.indent.width() {
2038 pub fn rewrite_call_with_binary_search<R>(
2039 context: &RewriteContext,
2041 args: &[&ast::Expr],
2048 let force_trailing_comma = if context.inside_macro {
2049 span_ends_with_comma(context, span)
2053 let closure = |callee_max_width| {
2054 // FIXME using byte lens instead of char lens (and probably all over the
2056 let callee_shape = Shape {
2057 width: callee_max_width,
2060 let callee_str = callee
2061 .rewrite(context, callee_shape)
2062 .ok_or(Ordering::Greater)?;
2070 context.config.fn_call_width(),
2071 force_trailing_comma,
2075 binary_search(1, shape.width, closure)
2078 pub fn rewrite_call(
2079 context: &RewriteContext,
2081 args: &[ptr::P<ast::Expr>],
2084 ) -> Option<String> {
2085 let force_trailing_comma = if context.inside_macro {
2086 span_ends_with_comma(context, span)
2093 &args.iter().map(|x| &**x).collect::<Vec<_>>(),
2096 context.config.fn_call_width(),
2097 force_trailing_comma,
2101 pub fn rewrite_call_inner<'a, T>(
2102 context: &RewriteContext,
2107 args_max_width: usize,
2108 force_trailing_comma: bool,
2109 ) -> Result<String, Ordering>
2111 T: Rewrite + Spanned + ToExpr + 'a,
2113 // 2 = `( `, 1 = `(`
2114 let paren_overhead = if context.config.spaces_within_parens() {
2119 let used_width = extra_offset(&callee_str, shape);
2120 let one_line_width = shape
2122 .checked_sub(used_width + 2 * paren_overhead)
2123 .ok_or(Ordering::Greater)?;
2125 let nested_shape = shape_from_fn_call_style(
2128 used_width + 2 * paren_overhead,
2129 used_width + paren_overhead,
2130 ).ok_or(Ordering::Greater)?;
2132 let span_lo = context.codemap.span_after(span, "(");
2133 let args_span = mk_sp(span_lo, span.hi);
2135 let (extendable, list_str) = rewrite_call_args(
2142 force_trailing_comma,
2143 ).ok_or(Ordering::Less)?;
2145 if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
2146 let mut new_context = context.clone();
2147 new_context.use_block = true;
2148 return rewrite_call_inner(
2155 force_trailing_comma,
2159 let args_shape = shape
2160 .sub_width(last_line_width(&callee_str))
2161 .ok_or(Ordering::Less)?;
2165 wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2169 fn need_block_indent(s: &str, shape: Shape) -> bool {
2170 s.lines().skip(1).any(|s| {
2171 s.find(|c| !char::is_whitespace(c))
2172 .map_or(false, |w| w + 1 < shape.indent.width())
2176 fn rewrite_call_args<'a, T>(
2177 context: &RewriteContext,
2181 one_line_width: usize,
2182 args_max_width: usize,
2183 force_trailing_comma: bool,
2184 ) -> Option<(bool, String)>
2186 T: Rewrite + Spanned + ToExpr + 'a,
2188 let items = itemize_list(
2192 |item| item.span().lo,
2193 |item| item.span().hi,
2194 |item| item.rewrite(context, shape),
2198 let mut item_vec: Vec<_> = items.collect();
2200 // Try letting the last argument overflow to the next line with block
2201 // indentation. If its first line fits on one line with the other arguments,
2202 // we format the function arguments horizontally.
2203 let tactic = try_overflow_last_arg(
2212 let fmt = ListFormatting {
2215 trailing_separator: if force_trailing_comma {
2216 SeparatorTactic::Always
2217 } else if context.inside_macro || !context.use_block_indent() {
2218 SeparatorTactic::Never
2220 context.config.trailing_comma()
2223 ends_with_newline: context.use_block_indent() && tactic == DefinitiveListTactic::Vertical,
2224 preserve_newline: false,
2225 config: context.config,
2228 write_list(&item_vec, &fmt).map(|args_str| {
2229 (tactic != DefinitiveListTactic::Vertical, args_str)
2233 fn try_overflow_last_arg<'a, T>(
2234 context: &RewriteContext,
2235 item_vec: &mut Vec<ListItem>,
2238 one_line_width: usize,
2239 args_max_width: usize,
2240 ) -> DefinitiveListTactic
2242 T: Rewrite + Spanned + ToExpr + 'a,
2244 let overflow_last = can_be_overflowed(&context, args);
2246 // Replace the last item with its first line to see if it fits with
2248 let (orig_last, placeholder) = if overflow_last {
2249 let mut context = context.clone();
2250 if let Some(expr) = args[args.len() - 1].to_expr() {
2252 ast::ExprKind::MethodCall(..) => context.force_one_line_chain = true,
2256 last_arg_shape(&context, &item_vec, shape, args_max_width)
2257 .map_or((None, None), |arg_shape| {
2258 rewrite_last_arg_with_overflow(
2261 &mut item_vec[args.len() - 1],
2269 let tactic = definitive_tactic(
2271 ListTactic::LimitedHorizontalVertical(args_max_width),
2276 // Replace the stub with the full overflowing last argument if the rewrite
2277 // succeeded and its first line fits with the other arguments.
2278 match (overflow_last, tactic, placeholder) {
2279 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2280 item_vec[args.len() - 1].item = placeholder;
2283 item_vec[args.len() - 1].item = orig_last;
2292 context: &RewriteContext,
2293 items: &Vec<ListItem>,
2295 args_max_width: usize,
2296 ) -> Option<Shape> {
2297 let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
2298 acc + i.item.as_ref().map_or(0, |s| first_line_width(&s))
2300 let max_width = min(args_max_width, shape.width);
2301 let arg_indent = if context.use_block_indent() {
2302 shape.block().indent.block_unindent(context.config)
2304 shape.block().indent
2307 width: try_opt!(max_width.checked_sub(overhead)),
2313 // Rewriting closure which is placed at the end of the function call's arg.
2314 // Returns `None` if the reformatted closure 'looks bad'.
2315 fn rewrite_last_closure(
2316 context: &RewriteContext,
2319 ) -> Option<String> {
2320 if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
2321 let body = match body.node {
2322 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
2323 stmt_expr(&block.stmts[0]).unwrap_or(body)
2327 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
2335 // If the closure goes multi line before its body, do not overflow the closure.
2336 if prefix.contains('\n') {
2339 let body_shape = try_opt!(shape.offset_left(extra_offset));
2340 // When overflowing the closure which consists of a single control flow expression,
2341 // force to use block if its condition uses multi line.
2342 let is_multi_lined_cond = rewrite_cond(context, body, body_shape)
2343 .map(|cond| cond.contains('\n') || cond.len() > body_shape.width)
2345 if is_multi_lined_cond {
2346 return rewrite_closure_with_block(context, body_shape, &prefix, body);
2349 // Seems fine, just format the closure in usual manner.
2350 return expr.rewrite(context, shape);
2355 fn rewrite_last_arg_with_overflow<'a, T>(
2356 context: &RewriteContext,
2358 last_item: &mut ListItem,
2360 ) -> (Option<String>, Option<String>)
2362 T: Rewrite + Spanned + ToExpr + 'a,
2364 let last_arg = args[args.len() - 1];
2365 let rewrite = if let Some(expr) = last_arg.to_expr() {
2367 // When overflowing the closure which consists of a single control flow expression,
2368 // force to use block if its condition uses multi line.
2369 ast::ExprKind::Closure(..) => {
2370 // If the argument consists of multiple closures, we do not overflow
2371 // the last closure.
2372 if args.len() > 1 &&
2376 .filter_map(|arg| arg.to_expr())
2377 .any(|expr| match expr.node {
2378 ast::ExprKind::Closure(..) => true,
2383 rewrite_last_closure(context, expr, shape)
2386 _ => expr.rewrite(context, shape),
2389 last_arg.rewrite(context, shape)
2391 let orig_last = last_item.item.clone();
2393 if let Some(rewrite) = rewrite {
2394 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2395 last_item.item = rewrite_first_line;
2396 (orig_last, Some(rewrite))
2402 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2404 T: Rewrite + Spanned + ToExpr + 'a,
2407 .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2410 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2412 ast::ExprKind::Match(..) => {
2413 (context.use_block_indent() && args_len == 1) ||
2414 (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
2416 ast::ExprKind::If(..) |
2417 ast::ExprKind::IfLet(..) |
2418 ast::ExprKind::ForLoop(..) |
2419 ast::ExprKind::Loop(..) |
2420 ast::ExprKind::While(..) |
2421 ast::ExprKind::WhileLet(..) => {
2422 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2424 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
2425 context.use_block_indent() ||
2426 context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
2428 ast::ExprKind::Array(..) |
2429 ast::ExprKind::Call(..) |
2430 ast::ExprKind::Mac(..) |
2431 ast::ExprKind::MethodCall(..) |
2432 ast::ExprKind::Struct(..) |
2433 ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2434 ast::ExprKind::AddrOf(_, ref expr) |
2435 ast::ExprKind::Box(ref expr) |
2436 ast::ExprKind::Try(ref expr) |
2437 ast::ExprKind::Unary(_, ref expr) |
2438 ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2443 pub fn wrap_args_with_parens(
2444 context: &RewriteContext,
2446 is_extendable: bool,
2448 nested_shape: Shape,
2450 if !context.use_block_indent() ||
2451 (context.inside_macro && !args_str.contains('\n') &&
2452 args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2454 if context.config.spaces_within_parens() && args_str.len() > 0 {
2455 format!("( {} )", args_str)
2457 format!("({})", args_str)
2462 nested_shape.indent.to_string(context.config),
2464 shape.block().indent.to_string(context.config)
2469 fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2470 let snippet = context.snippet(span);
2472 .trim_right_matches(|c: char| c == ')' || c.is_whitespace())
2476 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2477 debug!("rewrite_paren, shape: {:?}", shape);
2478 let total_paren_overhead = paren_overhead(context);
2479 let paren_overhead = total_paren_overhead / 2;
2480 let sub_shape = try_opt!(
2482 .offset_left(paren_overhead)
2483 .and_then(|s| s.sub_width(paren_overhead))
2486 let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && s.len() > 0 {
2487 format!("( {} )", s)
2492 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2493 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2495 if subexpr_str.contains('\n') ||
2496 first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
2498 Some(paren_wrapper(&subexpr_str))
2507 context: &RewriteContext,
2509 ) -> Option<String> {
2510 let expr_str = try_opt!(expr.rewrite(context, shape));
2512 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
2518 let offset = last_line_width(&expr_str) + lbr.len();
2519 let rhs_overhead = shape.rhs_overhead(context.config);
2520 let index_shape = if expr_str.contains('\n') {
2521 Shape::legacy(context.config.max_width(), shape.indent)
2522 .offset_left(offset)
2523 .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
2525 shape.visual_indent(offset).sub_width(offset + rbr.len())
2527 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
2529 // Return if index fits in a single line.
2530 match orig_index_rw {
2531 Some(ref index_str) if !index_str.contains('\n') => {
2532 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2537 // Try putting index on the next line and see if it fits in a single line.
2538 let indent = shape.indent.block_indent(context.config);
2539 let index_shape = try_opt!(Shape::indented(indent, context.config).offset_left(lbr.len()));
2540 let index_shape = try_opt!(index_shape.sub_width(rbr.len() + rhs_overhead));
2541 let new_index_rw = index.rewrite(context, index_shape);
2542 match (orig_index_rw, new_index_rw) {
2543 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
2546 indent.to_string(&context.config),
2551 (None, Some(ref new_index_str)) => Some(format!(
2554 indent.to_string(&context.config),
2559 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2564 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2569 fields.iter().all(|field| !field.is_shorthand)
2572 fn rewrite_struct_lit<'a>(
2573 context: &RewriteContext,
2575 fields: &'a [ast::Field],
2576 base: Option<&'a ast::Expr>,
2579 ) -> Option<String> {
2580 debug!("rewrite_struct_lit: shape {:?}", shape);
2582 enum StructLitField<'a> {
2583 Regular(&'a ast::Field),
2584 Base(&'a ast::Expr),
2588 let path_shape = try_opt!(shape.sub_width(2));
2589 let path_str = try_opt!(rewrite_path(
2597 if fields.len() == 0 && base.is_none() {
2598 return Some(format!("{} {{}}", path_str));
2601 // Foo { a: Foo } - indent is +3, width is -5.
2602 let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
2604 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2605 let body_lo = context.codemap.span_after(span, "{");
2606 let fields_str = if struct_lit_can_be_aligned(fields, &base) &&
2607 context.config.struct_field_align_threshold() > 0
2609 try_opt!(rewrite_with_alignment(
2613 mk_sp(body_lo, span.hi),
2617 let field_iter = fields
2619 .map(StructLitField::Regular)
2620 .chain(base.into_iter().map(StructLitField::Base));
2622 let span_lo = |item: &StructLitField| match *item {
2623 StructLitField::Regular(field) => field.span().lo,
2624 StructLitField::Base(expr) => {
2625 let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
2626 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
2627 let pos = snippet.find_uncommented("..").unwrap();
2628 last_field_hi + BytePos(pos as u32)
2631 let span_hi = |item: &StructLitField| match *item {
2632 StructLitField::Regular(field) => field.span().hi,
2633 StructLitField::Base(expr) => expr.span.hi,
2635 let rewrite = |item: &StructLitField| match *item {
2636 StructLitField::Regular(field) => {
2637 // The 1 taken from the v_budget is for the comma.
2638 rewrite_field(context, field, try_opt!(v_shape.sub_width(1)), 0)
2640 StructLitField::Base(expr) => {
2642 expr.rewrite(context, try_opt!(v_shape.offset_left(2)))
2643 .map(|s| format!("..{}", s))
2647 let items = itemize_list(
2657 let item_vec = items.collect::<Vec<_>>();
2659 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2660 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2661 let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2663 try_opt!(write_list(&item_vec, &fmt))
2666 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2667 Some(format!("{} {{{}}}", path_str, fields_str))
2669 // FIXME if context.config.struct_lit_style() == Visual, but we run out
2670 // of space, we should fall back to BlockIndent.
2673 pub fn wrap_struct_field(
2674 context: &RewriteContext,
2677 nested_shape: Shape,
2678 one_line_width: usize,
2680 if context.config.struct_lit_style() == IndentStyle::Block &&
2681 (fields_str.contains('\n') ||
2682 context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti ||
2683 fields_str.len() > one_line_width)
2687 nested_shape.indent.to_string(context.config),
2689 shape.indent.to_string(context.config)
2692 // One liner or visual indent.
2693 format!(" {} ", fields_str)
2697 pub fn struct_lit_field_separator(config: &Config) -> &str {
2699 config.space_before_struct_lit_field_colon(),
2700 config.space_after_struct_lit_field_colon(),
2704 pub fn rewrite_field(
2705 context: &RewriteContext,
2708 prefix_max_width: usize,
2709 ) -> Option<String> {
2710 if contains_skip(&field.attrs) {
2712 context.snippet(field.span()),
2713 context.config.max_width(),
2717 let name = &field.ident.node.to_string();
2718 if field.is_shorthand {
2719 Some(name.to_string())
2721 let mut separator = String::from(struct_lit_field_separator(context.config));
2722 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2723 separator.push(' ');
2725 let overhead = name.len() + separator.len();
2726 let expr_shape = try_opt!(shape.offset_left(overhead));
2727 let expr = field.expr.rewrite(context, expr_shape);
2729 let mut attrs_str = try_opt!(field.attrs.rewrite(context, shape));
2730 if !attrs_str.is_empty() {
2731 attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2735 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2737 let expr_offset = shape.indent.block_indent(context.config);
2740 .rewrite(context, Shape::indented(expr_offset, context.config));
2746 expr_offset.to_string(&context.config),
2755 fn shape_from_fn_call_style(
2756 context: &RewriteContext,
2760 ) -> Option<Shape> {
2761 if context.use_block_indent() {
2765 .block_indent(context.config.tab_spaces())
2766 .with_max_width(context.config)
2769 shape.visual_indent(offset).sub_width(overhead)
2773 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2774 context: &RewriteContext,
2780 T: Rewrite + Spanned + ToExpr + 'a,
2782 let mut items = items.iter();
2783 // In case of length 1, need a trailing comma
2784 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2785 if items.len() == 1 {
2787 let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
2788 return items.next().unwrap().rewrite(context, nested_shape).map(
2789 |s| if context.config.spaces_within_parens() {
2790 format!("( {}, )", s)
2797 let list_lo = context.codemap.span_after(span, "(");
2798 let nested_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
2799 let items = itemize_list(
2803 |item| item.span().lo,
2804 |item| item.span().hi,
2805 |item| item.rewrite(context, nested_shape),
2807 span.hi - BytePos(1),
2809 let item_vec: Vec<_> = items.collect();
2810 let tactic = definitive_tactic(
2812 ListTactic::HorizontalVertical,
2816 let fmt = ListFormatting {
2819 trailing_separator: SeparatorTactic::Never,
2821 ends_with_newline: false,
2822 preserve_newline: false,
2823 config: context.config,
2825 let list_str = try_opt!(write_list(&item_vec, &fmt));
2827 if context.config.spaces_within_parens() && list_str.len() > 0 {
2828 Some(format!("( {} )", list_str))
2830 Some(format!("({})", list_str))
2834 pub fn rewrite_tuple<'a, T>(
2835 context: &RewriteContext,
2841 T: Rewrite + Spanned + ToExpr + 'a,
2843 debug!("rewrite_tuple {:?}", shape);
2844 if context.use_block_indent() {
2845 // We use the same rule as funcation call for rewriting tuple.
2846 let force_trailing_comma = if context.inside_macro {
2847 span_ends_with_comma(context, span)
2857 context.config.fn_call_width(),
2858 force_trailing_comma,
2861 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2865 pub fn rewrite_unary_prefix<R: Rewrite>(
2866 context: &RewriteContext,
2870 ) -> Option<String> {
2872 .rewrite(context, try_opt!(shape.offset_left(prefix.len())))
2873 .map(|r| format!("{}{}", prefix, r))
2876 // FIXME: this is probably not correct for multi-line Rewrites. we should
2877 // subtract suffix.len() from the last line budget, not the first!
2878 pub fn rewrite_unary_suffix<R: Rewrite>(
2879 context: &RewriteContext,
2883 ) -> Option<String> {
2885 .rewrite(context, try_opt!(shape.sub_width(suffix.len())))
2892 fn rewrite_unary_op(
2893 context: &RewriteContext,
2897 ) -> Option<String> {
2898 // For some reason, an UnOp is not spanned like BinOp!
2899 let operator_str = match *op {
2900 ast::UnOp::Deref => "*",
2901 ast::UnOp::Not => "!",
2902 ast::UnOp::Neg => "-",
2904 rewrite_unary_prefix(context, operator_str, expr, shape)
2907 fn rewrite_assignment(
2908 context: &RewriteContext,
2911 op: Option<&ast::BinOp>,
2913 ) -> Option<String> {
2914 let operator_str = match op {
2915 Some(op) => context.snippet(op.span),
2916 None => "=".to_owned(),
2919 // 1 = space between lhs and operator.
2920 let lhs_shape = try_opt!(shape.sub_width(operator_str.len() + 1));
2921 let lhs_str = format!(
2923 try_opt!(lhs.rewrite(context, lhs_shape)),
2927 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2930 // The left hand side must contain everything up to, and including, the
2931 // assignment operator.
2932 pub fn rewrite_assign_rhs<S: Into<String>>(
2933 context: &RewriteContext,
2937 ) -> Option<String> {
2938 let lhs = lhs.into();
2939 let last_line_width = last_line_width(&lhs) - if lhs.contains('\n') {
2940 shape.indent.width()
2944 // 1 = space between operator and rhs.
2945 let orig_shape = try_opt!(shape.offset_left(last_line_width + 1));
2946 let rhs = try_opt!(choose_rhs(
2950 ex.rewrite(context, orig_shape)
2956 context: &RewriteContext,
2959 orig_rhs: Option<String>,
2960 ) -> Option<String> {
2962 Some(ref new_str) if !new_str.contains('\n') => Some(format!(" {}", new_str)),
2964 // Expression did not fit on the same line as the identifier.
2965 // Try splitting the line and see if that works better.
2966 let new_shape = try_opt!(
2968 shape.block().indent.block_indent(context.config),
2970 ).sub_width(shape.rhs_overhead(context.config))
2972 let new_rhs = expr.rewrite(context, new_shape);
2973 let new_indent_str = &new_shape.indent.to_string(context.config);
2975 match (orig_rhs, new_rhs) {
2976 (Some(ref orig_rhs), Some(ref new_rhs)) if prefer_next_line(orig_rhs, new_rhs) => {
2977 Some(format!("\n{}{}", new_indent_str, new_rhs))
2979 (None, Some(ref new_rhs)) => Some(format!("\n{}{}", new_indent_str, new_rhs)),
2980 (None, None) => None,
2981 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2987 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {
2989 fn count_line_breaks(src: &str) -> usize {
2990 src.chars().filter(|&x| x == '\n').count()
2993 !next_line_rhs.contains('\n') ||
2994 count_line_breaks(orig_rhs) > count_line_breaks(next_line_rhs) + 1
2997 fn rewrite_expr_addrof(
2998 context: &RewriteContext,
2999 mutability: ast::Mutability,
3002 ) -> Option<String> {
3003 let operator_str = match mutability {
3004 ast::Mutability::Immutable => "&",
3005 ast::Mutability::Mutable => "&mut ",
3007 rewrite_unary_prefix(context, operator_str, expr, shape)
3011 fn to_expr(&self) -> Option<&ast::Expr>;
3012 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
3015 impl ToExpr for ast::Expr {
3016 fn to_expr(&self) -> Option<&ast::Expr> {
3020 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
3021 can_be_overflowed_expr(context, self, len)
3025 impl ToExpr for ast::Ty {
3026 fn to_expr(&self) -> Option<&ast::Expr> {
3030 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
3031 can_be_overflowed_type(context, self, len)
3035 impl<'a> ToExpr for TuplePatField<'a> {
3036 fn to_expr(&self) -> Option<&ast::Expr> {
3040 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
3041 can_be_overflowed_pat(context, self, len)
3045 impl<'a> ToExpr for ast::StructField {
3046 fn to_expr(&self) -> Option<&ast::Expr> {
3050 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {