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, format_item_list, 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};
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};
34 use syntax::{ast, ptr};
35 use syntax::codemap::{CodeMap, Span, BytePos};
36 use syntax::parse::classify;
38 impl Rewrite for ast::Expr {
39 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
40 format_expr(self, ExprType::SubExpression, context, shape)
50 fn combine_attr_and_expr(
51 context: &RewriteContext,
56 let separator = if attr_str.is_empty() {
59 if expr_str.contains('\n') || attr_str.contains('\n') ||
60 attr_str.len() + expr_str.len() > shape.width
62 format!("\n{}", shape.indent.to_string(context.config))
67 format!("{}{}{}", attr_str, separator, expr_str)
73 context: &RewriteContext,
76 let attr_rw = (&*expr.attrs).rewrite(context, shape);
77 if contains_skip(&*expr.attrs) {
78 if let Some(attr_str) = attr_rw {
79 return Some(combine_attr_and_expr(
83 &context.snippet(expr.span),
86 return Some(context.snippet(expr.span));
89 let expr_rw = match expr.node {
90 ast::ExprKind::Array(ref expr_vec) => {
92 expr_vec.iter().map(|e| &**e),
93 mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi),
98 ast::ExprKind::Lit(ref l) => {
100 ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
101 rewrite_string_lit(context, l.span, shape)
105 context.snippet(expr.span),
106 context.config.max_width(),
112 ast::ExprKind::Call(ref callee, ref args) => {
113 let inner_span = mk_sp(callee.span.hi, expr.span.hi);
114 rewrite_call_with_binary_search(
117 &args.iter().map(|x| &**x).collect::<Vec<_>>()[..],
122 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
123 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
124 // FIXME: format comments between operands and operator
129 &format!(" {} ", context.snippet(op.span)),
135 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
136 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
141 base.as_ref().map(|e| &**e),
146 ast::ExprKind::Tup(ref items) => {
149 &items.iter().map(|x| &**x).collect::<Vec<_>>()[..],
154 ast::ExprKind::If(..) |
155 ast::ExprKind::IfLet(..) |
156 ast::ExprKind::ForLoop(..) |
157 ast::ExprKind::Loop(..) |
158 ast::ExprKind::While(..) |
159 ast::ExprKind::WhileLet(..) => {
160 to_control_flow(expr, expr_type)
161 .and_then(|control_flow| control_flow.rewrite(context, shape))
163 ast::ExprKind::Block(ref block) => block.rewrite(context, shape),
164 ast::ExprKind::Match(ref cond, ref arms) => {
165 rewrite_match(context, cond, arms, shape, expr.span)
167 ast::ExprKind::Path(ref qself, ref path) => {
168 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
170 ast::ExprKind::Assign(ref lhs, ref rhs) => {
171 rewrite_assignment(context, lhs, rhs, None, shape)
173 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
174 rewrite_assignment(context, lhs, rhs, Some(op), shape)
176 ast::ExprKind::Continue(ref opt_ident) => {
177 let id_str = match *opt_ident {
178 Some(ident) => format!(" {}", ident.node),
179 None => String::new(),
182 format!("continue{}", id_str),
183 context.config.max_width(),
187 ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
188 let id_str = match *opt_ident {
189 Some(ident) => format!(" {}", ident.node),
190 None => String::new(),
193 if let Some(ref expr) = *opt_expr {
194 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
197 format!("break{}", id_str),
198 context.config.max_width(),
203 ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
204 rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
206 ast::ExprKind::Try(..) |
207 ast::ExprKind::Field(..) |
208 ast::ExprKind::TupField(..) |
209 ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
210 ast::ExprKind::Mac(ref mac) => {
211 // Failure to rewrite a marco should not imply failure to
212 // rewrite the expression.
213 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
215 context.snippet(expr.span),
216 context.config.max_width(),
221 ast::ExprKind::Ret(None) => {
222 wrap_str("return".to_owned(), context.config.max_width(), shape)
224 ast::ExprKind::Ret(Some(ref expr)) => {
225 rewrite_unary_prefix(context, "return ", &**expr, shape)
227 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
228 ast::ExprKind::AddrOf(mutability, ref expr) => {
229 rewrite_expr_addrof(context, mutability, expr, shape)
231 ast::ExprKind::Cast(ref expr, ref ty) => {
232 rewrite_pair(&**expr, &**ty, "", " as ", "", context, shape)
234 ast::ExprKind::Type(ref expr, ref ty) => {
235 rewrite_pair(&**expr, &**ty, "", ": ", "", context, shape)
237 ast::ExprKind::Index(ref expr, ref index) => {
238 rewrite_index(&**expr, &**index, context, shape)
240 ast::ExprKind::Repeat(ref expr, ref repeats) => {
241 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
246 rewrite_pair(&**expr, &**repeats, lbr, "; ", rbr, context, shape)
248 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
249 let delim = match limits {
250 ast::RangeLimits::HalfOpen => "..",
251 ast::RangeLimits::Closed => "...",
254 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
255 (Some(ref lhs), Some(ref rhs)) => {
256 let sp_delim = if context.config.spaces_around_ranges() {
257 format!(" {} ", delim)
261 rewrite_pair(&**lhs, &**rhs, "", &sp_delim, "", context, shape)
263 (None, Some(ref rhs)) => {
264 let sp_delim = if context.config.spaces_around_ranges() {
265 format!("{} ", delim)
269 rewrite_unary_prefix(context, &sp_delim, &**rhs, shape)
271 (Some(ref lhs), None) => {
272 let sp_delim = if context.config.spaces_around_ranges() {
273 format!(" {}", delim)
277 rewrite_unary_suffix(context, &sp_delim, &**lhs, shape)
279 (None, None) => wrap_str(delim.into(), context.config.max_width(), shape),
282 // We do not format these expressions yet, but they should still
283 // satisfy our width restrictions.
284 ast::ExprKind::InPlace(..) |
285 ast::ExprKind::InlineAsm(..) => {
287 context.snippet(expr.span),
288 context.config.max_width(),
292 ast::ExprKind::Catch(ref block) => {
293 if let rewrite @ Some(_) = try_one_line_block(context, shape, "do catch ", block) {
297 let budget = shape.width.checked_sub(9).unwrap_or(0);
301 try_opt!(block.rewrite(&context, Shape::legacy(budget, shape.indent)))
305 match (attr_rw, expr_rw) {
306 (Some(attr_str), Some(expr_str)) => {
307 recover_comment_removed(
308 combine_attr_and_expr(context, shape, &attr_str, &expr_str),
318 fn try_one_line_block(
319 context: &RewriteContext,
323 ) -> Option<String> {
324 if is_simple_block(block, context.codemap) {
325 let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
326 let expr_str = try_opt!(block.stmts[0].rewrite(context, expr_shape));
327 let result = format!("{}{{ {} }}", prefix, expr_str);
328 if result.len() <= shape.width && !result.contains('\n') {
335 pub fn rewrite_pair<LHS, RHS>(
341 context: &RewriteContext,
348 // Get "full width" rhs and see if it fits on the current line. This
349 // usually works fairly well since it tends to place operands of
350 // operations with high precendence close together.
351 // Note that this is non-conservative, but its just to see if it's even
352 // worth trying to put everything on one line.
353 let rhs_shape = try_opt!(shape.sub_width(suffix.len()));
354 let rhs_result = rhs.rewrite(context, rhs_shape);
356 if let Some(rhs_result) = rhs_result {
357 // This is needed in case of line break not caused by a
358 // shortage of space, but by end-of-line comments, for example.
359 if !rhs_result.contains('\n') {
361 try_opt!(try_opt!(shape.offset_left(prefix.len())).sub_width(infix.len()));
362 let lhs_result = lhs.rewrite(context, lhs_shape);
363 if let Some(lhs_result) = lhs_result {
364 let mut result = format!("{}{}{}", prefix, lhs_result, infix);
366 let remaining_width = shape
368 .checked_sub(last_line_width(&result) + suffix.len())
371 if rhs_result.len() <= remaining_width {
372 result.push_str(&rhs_result);
373 result.push_str(suffix);
377 // Try rewriting the rhs into the remaining space.
378 let rhs_shape = shape.shrink_left(last_line_width(&result) + suffix.len());
379 if let Some(rhs_shape) = rhs_shape {
380 if let Some(rhs_result) = rhs.rewrite(context, rhs_shape) {
381 // FIXME this should always hold.
382 if rhs_result.len() <= remaining_width {
383 result.push_str(&rhs_result);
384 result.push_str(suffix);
393 // We have to use multiple lines.
395 // Re-evaluate the rhs because we have more space now:
396 let infix = infix.trim_right();
397 let rhs_shape = match context.config.control_style() {
399 try_opt!(shape.sub_width(suffix.len() + prefix.len())).visual_indent(prefix.len())
402 // Try to calculate the initial constraint on the right hand side.
403 let rhs_overhead = context
406 .checked_sub(shape.used_width() + shape.width)
409 Shape::indented(shape.indent.block_indent(context.config), context.config)
410 .sub_width(rhs_overhead)
414 let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape));
415 let lhs_overhead = shape.used_width() + prefix.len() + infix.len();
416 let lhs_shape = Shape {
417 width: try_opt!(context.config.max_width().checked_sub(lhs_overhead)),
420 let lhs_result = try_opt!(lhs.rewrite(context, lhs_shape));
426 rhs_shape.indent.to_string(context.config),
432 pub fn rewrite_array<'a, I>(
435 context: &RewriteContext,
439 I: Iterator<Item = &'a ast::Expr>,
441 let bracket_size = if context.config.spaces_within_square_brackets() {
447 let nested_shape = match context.config.array_layout() {
448 IndentStyle::Block => shape.block().block_indent(context.config.tab_spaces()),
449 IndentStyle::Visual => {
452 .visual_indent(bracket_size)
453 .sub_width(bracket_size * 2)
458 let items = itemize_list(
464 |item| item.rewrite(context, nested_shape),
467 ).collect::<Vec<_>>();
469 if items.is_empty() {
470 if context.config.spaces_within_square_brackets() {
471 return Some("[ ]".to_string());
473 return Some("[]".to_string());
477 let has_long_item = items
479 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
481 let tactic = match context.config.array_layout() {
482 IndentStyle::Block => {
483 // FIXME wrong shape in one-line case
484 match shape.width.checked_sub(2 * bracket_size) {
487 ListTactic::LimitedHorizontalVertical(context.config.array_width());
488 definitive_tactic(&items, tactic, width)
490 None => DefinitiveListTactic::Vertical,
493 IndentStyle::Visual => {
494 if has_long_item || items.iter().any(ListItem::is_multiline) {
497 ListTactic::LimitedHorizontalVertical(context.config.array_width()),
501 DefinitiveListTactic::Mixed
506 let fmt = ListFormatting {
509 trailing_separator: SeparatorTactic::Never,
511 ends_with_newline: false,
512 config: context.config,
514 let list_str = try_opt!(write_list(&items, &fmt));
516 let result = if context.config.array_layout() == IndentStyle::Visual ||
517 tactic != DefinitiveListTactic::Vertical
519 if context.config.spaces_within_square_brackets() && list_str.len() > 0 {
520 format!("[ {} ]", list_str)
522 format!("[{}]", list_str)
527 nested_shape.indent.to_string(context.config),
529 shape.block().indent.to_string(context.config)
536 // Return type is (prefix, extra_offset)
537 fn rewrite_closure_fn_decl(
538 capture: ast::CaptureBy,
539 fn_decl: &ast::FnDecl,
542 context: &RewriteContext,
544 ) -> Option<(String, usize)> {
545 let mover = if capture == ast::CaptureBy::Value {
550 // 4 = "|| {".len(), which is overconservative when the closure consists of
551 // a single expression.
552 let nested_shape = try_opt!(try_opt!(shape.shrink_left(mover.len())).sub_width(4));
555 let argument_offset = nested_shape.indent + 1;
556 let arg_shape = try_opt!(nested_shape.shrink_left(1)).visual_indent(0);
557 let ret_str = try_opt!(fn_decl.output.rewrite(context, arg_shape));
559 let arg_items = itemize_list(
561 fn_decl.inputs.iter(),
563 |arg| span_lo_for_arg(arg),
564 |arg| span_hi_for_arg(context, arg),
565 |arg| arg.rewrite(context, arg_shape),
566 context.codemap.span_after(span, "|"),
569 let item_vec = arg_items.collect::<Vec<_>>();
570 // 1 = space between arguments and return type.
571 let horizontal_budget = nested_shape
573 .checked_sub(ret_str.len() + 1)
575 let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
576 let arg_shape = match tactic {
577 DefinitiveListTactic::Horizontal => try_opt!(arg_shape.sub_width(ret_str.len() + 1)),
581 let fmt = ListFormatting {
584 trailing_separator: SeparatorTactic::Never,
586 ends_with_newline: false,
587 config: context.config,
589 let list_str = try_opt!(write_list(&item_vec, &fmt));
590 let mut prefix = format!("{}|{}|", mover, list_str);
591 // 1 = space between `|...|` and body.
592 let extra_offset = extra_offset(&prefix, shape) + 1;
594 if !ret_str.is_empty() {
595 if prefix.contains('\n') {
597 prefix.push_str(&argument_offset.to_string(context.config));
601 prefix.push_str(&ret_str);
604 Some((prefix, extra_offset))
607 // This functions is pretty messy because of the rules around closures and blocks:
608 // FIXME - the below is probably no longer true in full.
609 // * if there is a return type, then there must be braces,
610 // * given a closure with braces, whether that is parsed to give an inner block
611 // or not depends on if there is a return type and if there are statements
613 // * if the first expression in the body ends with a block (i.e., is a
614 // statement without needing a semi-colon), then adding or removing braces
615 // can change whether it is treated as an expression or statement.
617 capture: ast::CaptureBy,
618 fn_decl: &ast::FnDecl,
621 context: &RewriteContext,
623 ) -> Option<String> {
624 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
632 // 1 = space between `|...|` and body.
633 let body_shape = try_opt!(shape.offset_left(extra_offset));
635 if let ast::ExprKind::Block(ref block) = body.node {
636 // The body of the closure is an empty block.
637 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
638 return Some(format!("{} {{}}", prefix));
641 // Figure out if the block is necessary.
642 let needs_block = block.rules != ast::BlockCheckMode::Default ||
643 block.stmts.len() > 1 || context.inside_macro ||
644 block_contains_comment(block, context.codemap) ||
645 prefix.contains('\n');
647 let no_return_type = if let ast::FunctionRetTy::Default(_) = fn_decl.output {
652 if no_return_type && !needs_block {
653 // lock.stmts.len() == 1
654 if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
655 if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
662 // We need braces, but we might still prefer a one-liner.
663 let stmt = &block.stmts[0];
664 // 4 = braces and spaces.
665 if let Some(body_shape) = body_shape.sub_width(4) {
666 // Checks if rewrite succeeded and fits on a single line.
667 if let Some(rewrite) = and_one_line(stmt.rewrite(context, body_shape)) {
668 return Some(format!("{} {{ {} }}", prefix, rewrite));
673 // Either we require a block, or tried without and failed.
674 rewrite_closure_block(&block, &prefix, context, body_shape)
676 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
677 // The closure originally had a non-block expression, but we can't fit on
678 // one line, so we'll insert a block.
679 rewrite_closure_with_block(context, body_shape, &prefix, body)
684 // Rewrite closure with a single expression wrapping its body with block.
685 fn rewrite_closure_with_block(
686 context: &RewriteContext,
690 ) -> Option<String> {
691 let block = ast::Block {
694 id: ast::NodeId::new(0),
695 node: ast::StmtKind::Expr(ptr::P(body.clone())),
699 id: ast::NodeId::new(0),
700 rules: ast::BlockCheckMode::Default,
703 rewrite_closure_block(&block, prefix, context, shape)
706 // Rewrite closure with a single expression without wrapping its body with block.
707 fn rewrite_closure_expr(
710 context: &RewriteContext,
712 ) -> Option<String> {
713 let mut rewrite = expr.rewrite(context, shape);
714 if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
715 rewrite = and_one_line(rewrite);
717 rewrite.map(|rw| format!("{} {}", prefix, rw))
720 // Rewrite closure whose body is block.
721 fn rewrite_closure_block(
724 context: &RewriteContext,
726 ) -> Option<String> {
727 // Start with visual indent, then fall back to block indent if the
729 let block_threshold = context.config.closure_block_indent_threshold();
730 if block_threshold >= 0 {
731 if let Some(block_str) = block.rewrite(&context, shape) {
732 if block_str.matches('\n').count() <= block_threshold as usize &&
733 !need_block_indent(&block_str, shape)
735 if let Some(block_str) = block_str.rewrite(context, shape) {
736 return Some(format!("{} {}", prefix, block_str));
742 // The body of the closure is big enough to be block indented, that
743 // means we must re-format.
744 let block_shape = shape.block().with_max_width(context.config);
745 let block_str = try_opt!(block.rewrite(&context, block_shape));
746 Some(format!("{} {}", prefix, block_str))
749 fn and_one_line(x: Option<String>) -> Option<String> {
750 x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
753 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
754 debug!("nop_block_collapse {:?} {}", block_str, budget);
755 block_str.map(|block_str| {
756 if block_str.starts_with('{') && budget >= 2 &&
757 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
766 impl Rewrite for ast::Block {
767 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
768 // shape.width is used only for the single line case: either the empty block `{}`,
769 // or an unsafe expression `unsafe { e }`.
771 if self.stmts.is_empty() && !block_contains_comment(self, context.codemap) &&
774 return Some("{}".to_owned());
777 // If a block contains only a single-line comment, then leave it on one line.
778 let user_str = context.snippet(self.span);
779 let user_str = user_str.trim();
780 if user_str.starts_with('{') && user_str.ends_with('}') {
781 let comment_str = user_str[1..user_str.len() - 1].trim();
782 if self.stmts.is_empty() && !comment_str.contains('\n') &&
783 !comment_str.starts_with("//") &&
784 comment_str.len() + 4 <= shape.width
786 return Some(format!("{{ {} }}", comment_str));
790 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
791 visitor.block_indent = shape.indent;
792 visitor.is_if_else_block = context.is_if_else_block;
794 let prefix = match self.rules {
795 ast::BlockCheckMode::Unsafe(..) => {
796 let snippet = context.snippet(self.span);
797 let open_pos = try_opt!(snippet.find_uncommented("{"));
798 visitor.last_pos = self.span.lo + BytePos(open_pos as u32);
800 // Extract comment between unsafe and block start.
801 let trimmed = &snippet[6..open_pos].trim();
803 let prefix = if !trimmed.is_empty() {
804 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
805 let budget = try_opt!(shape.width.checked_sub(9));
808 try_opt!(rewrite_comment(
811 Shape::legacy(budget, shape.indent + 7),
818 if let result @ Some(_) = try_one_line_block(context, shape, &prefix, self) {
823 ast::BlockCheckMode::Default => {
824 visitor.last_pos = self.span.lo;
829 visitor.visit_block(self);
830 if visitor.failed && shape.indent.alignment != 0 {
833 Shape::indented(shape.indent.block_only(), context.config),
836 Some(format!("{}{}", prefix, visitor.buffer))
841 impl Rewrite for ast::Stmt {
842 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
843 let result = match self.node {
844 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
845 ast::StmtKind::Expr(ref ex) |
846 ast::StmtKind::Semi(ref ex) => {
847 let suffix = if semicolon_for_stmt(self) { ";" } else { "" };
852 ast::StmtKind::Expr(_) => ExprType::SubExpression,
853 ast::StmtKind::Semi(_) => ExprType::Statement,
857 try_opt!(shape.sub_width(suffix.len())),
858 ).map(|s| s + suffix)
860 ast::StmtKind::Mac(..) |
861 ast::StmtKind::Item(..) => None,
863 result.and_then(|res| {
864 recover_comment_removed(res, self.span, context, shape)
869 // Rewrite condition if the given expression has one.
870 fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
872 ast::ExprKind::Match(ref cond, _) => {
874 let cond_shape = match context.config.control_style() {
875 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
876 Style::Rfc => try_opt!(shape.offset_left(8)),
878 cond.rewrite(context, cond_shape)
880 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
881 stmt_expr(&block.stmts[0]).and_then(|e| rewrite_cond(context, e, shape))
884 to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
885 let alt_block_sep = String::from("\n") +
886 &shape.indent.block_only().to_string(context.config);
888 .rewrite_cond(context, shape, &alt_block_sep)
889 .and_then(|rw| Some(rw.0))
895 // Abstraction over control flow expressions
897 struct ControlFlow<'a> {
898 cond: Option<&'a ast::Expr>,
899 block: &'a ast::Block,
900 else_block: Option<&'a ast::Expr>,
901 label: Option<ast::SpannedIdent>,
902 pat: Option<&'a ast::Pat>,
906 allow_single_line: bool,
907 // True if this is an `if` expression in an `else if` :-( hacky
912 fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'a>> {
914 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
915 Some(ControlFlow::new_if(
919 else_block.as_ref().map(|e| &**e),
920 expr_type == ExprType::SubExpression,
925 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
926 Some(ControlFlow::new_if(
930 else_block.as_ref().map(|e| &**e),
931 expr_type == ExprType::SubExpression,
936 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
937 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
939 ast::ExprKind::Loop(ref block, label) => Some(
940 ControlFlow::new_loop(block, label, expr.span),
942 ast::ExprKind::While(ref cond, ref block, label) => Some(
943 ControlFlow::new_while(None, cond, block, label, expr.span),
945 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => {
946 Some(ControlFlow::new_while(
958 impl<'a> ControlFlow<'a> {
961 pat: Option<&'a ast::Pat>,
962 block: &'a ast::Block,
963 else_block: Option<&'a ast::Expr>,
964 allow_single_line: bool,
967 ) -> ControlFlow<'a> {
971 else_block: else_block,
980 allow_single_line: allow_single_line,
981 nested_if: nested_if,
987 block: &'a ast::Block,
988 label: Option<ast::SpannedIdent>,
990 ) -> ControlFlow<'a> {
1000 allow_single_line: false,
1007 pat: Option<&'a ast::Pat>,
1008 cond: &'a ast::Expr,
1009 block: &'a ast::Block,
1010 label: Option<ast::SpannedIdent>,
1012 ) -> ControlFlow<'a> {
1020 matcher: match pat {
1025 allow_single_line: false,
1033 cond: &'a ast::Expr,
1034 block: &'a ast::Block,
1035 label: Option<ast::SpannedIdent>,
1037 ) -> ControlFlow<'a> {
1047 allow_single_line: false,
1053 fn rewrite_single_line(
1056 context: &RewriteContext,
1058 ) -> Option<String> {
1059 assert!(self.allow_single_line);
1060 let else_block = try_opt!(self.else_block);
1061 let fixed_cost = self.keyword.len() + " { } else { }".len();
1063 if let ast::ExprKind::Block(ref else_node) = else_block.node {
1064 if !is_simple_block(self.block, context.codemap) ||
1065 !is_simple_block(else_node, context.codemap) ||
1066 pat_expr_str.contains('\n')
1071 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
1072 let expr = &self.block.stmts[0];
1073 let if_str = try_opt!(expr.rewrite(
1075 Shape::legacy(new_width, Indent::empty()),
1078 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
1079 let else_expr = &else_node.stmts[0];
1080 let else_str = try_opt!(else_expr.rewrite(
1082 Shape::legacy(new_width, Indent::empty()),
1085 if if_str.contains('\n') || else_str.contains('\n') {
1089 let result = format!(
1090 "{} {} {{ {} }} else {{ {} }}",
1097 if result.len() <= width {
1098 return Some(result);
1106 impl<'a> ControlFlow<'a> {
1109 context: &RewriteContext,
1111 alt_block_sep: &str,
1112 ) -> Option<(String, usize)> {
1113 let constr_shape = if self.nested_if {
1114 // We are part of an if-elseif-else chain. Our constraints are tightened.
1115 // 7 = "} else " .len()
1116 try_opt!(shape.shrink_left(7))
1121 let label_string = rewrite_label(self.label);
1122 // 1 = space after keyword.
1123 let offset = self.keyword.len() + label_string.len() + 1;
1125 let pat_expr_string = match self.cond {
1127 let mut cond_shape = match context.config.control_style() {
1128 Style::Legacy => try_opt!(constr_shape.shrink_left(offset)),
1129 Style::Rfc => try_opt!(constr_shape.offset_left(offset)),
1131 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1133 cond_shape = try_opt!(cond_shape.sub_width(2));
1136 try_opt!(rewrite_pat_expr(
1146 None => String::new(),
1149 let force_newline_brace = context.config.control_style() == Style::Rfc &&
1150 pat_expr_string.contains('\n');
1152 // Try to format if-else on single line.
1153 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1154 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1156 if let Some(cond_str) = trial {
1157 if cond_str.len() <= context.config.single_line_if_else_max_width() {
1158 return Some((cond_str, 0));
1163 let cond_span = if let Some(cond) = self.cond {
1166 mk_sp(self.block.span.lo, self.block.span.lo)
1169 // for event in event
1170 let between_kwd_cond = mk_sp(
1171 context.codemap.span_after(self.span, self.keyword.trim()),
1174 |p| if self.matcher.is_empty() {
1177 context.codemap.span_before(self.span, self.matcher.trim())
1182 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1184 let after_cond_comment =
1185 extract_comment(mk_sp(cond_span.hi, self.block.span.lo), context, shape);
1187 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1189 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine ||
1197 let used_width = if pat_expr_string.contains('\n') {
1198 last_line_width(&pat_expr_string)
1200 // 2 = spaces after keyword and condition.
1201 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1209 between_kwd_cond_comment.as_ref().map_or(
1210 if pat_expr_string.is_empty() ||
1211 pat_expr_string.starts_with('\n')
1220 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1227 impl<'a> Rewrite for ControlFlow<'a> {
1228 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1229 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1231 let alt_block_sep = String::from("\n") +
1232 &shape.indent.block_only().to_string(context.config);
1233 let (cond_str, used_width) = try_opt!(self.rewrite_cond(context, shape, &alt_block_sep));
1234 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1235 if used_width == 0 {
1236 return Some(cond_str);
1239 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1240 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1241 // we should avoid the single line case.
1242 let block_width = if self.else_block.is_some() || self.nested_if {
1247 let block_shape = Shape {
1251 let mut block_context = context.clone();
1252 block_context.is_if_else_block = self.else_block.is_some();
1253 let block_str = try_opt!(self.block.rewrite(&block_context, block_shape));
1255 let mut result = format!("{}{}", cond_str, block_str);
1257 if let Some(else_block) = self.else_block {
1258 let shape = Shape::indented(shape.indent, context.config);
1259 let mut last_in_chain = false;
1260 let rewrite = match else_block.node {
1261 // If the else expression is another if-else expression, prevent it
1262 // from being formatted on a single line.
1263 // Note how we're passing the original shape, as the
1264 // cost of "else" should not cascade.
1265 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1266 ControlFlow::new_if(
1270 next_else_block.as_ref().map(|e| &**e),
1273 mk_sp(else_block.span.lo, self.span.hi),
1274 ).rewrite(context, shape)
1276 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1277 ControlFlow::new_if(
1281 next_else_block.as_ref().map(|e| &**e),
1284 mk_sp(else_block.span.lo, self.span.hi),
1285 ).rewrite(context, shape)
1288 last_in_chain = true;
1289 // When rewriting a block, the width is only used for single line
1290 // blocks, passing 1 lets us avoid that.
1291 let else_shape = Shape {
1292 width: min(1, shape.width),
1295 else_block.rewrite(context, else_shape)
1299 let between_kwd_else_block = mk_sp(
1301 context.codemap.span_before(
1302 mk_sp(self.block.span.hi, else_block.span.lo),
1306 let between_kwd_else_block_comment =
1307 extract_comment(between_kwd_else_block, context, shape);
1309 let after_else = mk_sp(
1310 context.codemap.span_after(
1311 mk_sp(self.block.span.hi, else_block.span.lo),
1316 let after_else_comment = extract_comment(after_else, context, shape);
1318 let between_sep = match context.config.control_brace_style() {
1319 ControlBraceStyle::AlwaysNextLine |
1320 ControlBraceStyle::ClosingNextLine => &*alt_block_sep,
1321 ControlBraceStyle::AlwaysSameLine => " ",
1323 let after_sep = match context.config.control_brace_style() {
1324 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1331 between_kwd_else_block_comment.as_ref().map_or(
1335 after_else_comment.as_ref().map_or(after_sep, |s| &**s)
1338 result.push_str(&try_opt!(rewrite));
1345 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
1347 Some(ident) => format!("{}: ", ident.node),
1348 None => "".to_owned(),
1352 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1353 let comment_str = context.snippet(span);
1354 if contains_comment(&comment_str) {
1355 let comment = try_opt!(rewrite_comment(
1362 "\n{indent}{}\n{indent}",
1364 indent = shape.indent.to_string(context.config)
1371 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1372 let snippet = codemap.span_to_snippet(block.span).unwrap();
1373 contains_comment(&snippet)
1376 // Checks that a block contains no statements, an expression and no comments.
1377 // FIXME: incorrectly returns false when comment is contained completely within
1379 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1380 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) &&
1381 !block_contains_comment(block, codemap))
1384 /// Checks whether a block contains at most one statement or expression, and no comments.
1385 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1386 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1389 /// Checks whether a block contains no statements, expressions, or comments.
1390 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1391 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1394 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1396 ast::StmtKind::Expr(..) => true,
1401 fn is_unsafe_block(block: &ast::Block) -> bool {
1402 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1409 // inter-match-arm-comment-rules:
1410 // - all comments following a match arm before the start of the next arm
1411 // are about the second arm
1412 fn rewrite_match_arm_comment(
1413 context: &RewriteContext,
1416 arm_indent_str: &str,
1417 ) -> Option<String> {
1418 // The leading "," is not part of the arm-comment
1419 let missed_str = match missed_str.find_uncommented(",") {
1420 Some(n) => &missed_str[n + 1..],
1421 None => &missed_str[..],
1424 let mut result = String::new();
1425 // any text not preceeded by a newline is pushed unmodified to the block
1426 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
1427 result.push_str(&missed_str[..first_brk]);
1428 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
1430 let first = missed_str
1431 .find(|c: char| !c.is_whitespace())
1432 .unwrap_or(missed_str.len());
1433 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
1434 // Excessive vertical whitespace before comment should be preserved
1435 // FIXME handle vertical whitespace better
1438 let missed_str = missed_str[first..].trim();
1439 if !missed_str.is_empty() {
1440 let comment = try_opt!(rewrite_comment(&missed_str, false, shape, context.config));
1442 result.push_str(arm_indent_str);
1443 result.push_str(&comment);
1450 context: &RewriteContext,
1455 ) -> Option<String> {
1456 if arms.is_empty() {
1461 let cond_shape = match context.config.control_style() {
1462 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
1463 Style::Rfc => try_opt!(shape.offset_left(8)),
1465 let cond_str = try_opt!(cond.rewrite(context, cond_shape));
1466 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1467 let block_sep = match context.config.control_brace_style() {
1468 ControlBraceStyle::AlwaysSameLine => " ",
1469 _ => alt_block_sep.as_str(),
1471 let mut result = format!("match {}{}{{", cond_str, block_sep);
1473 let arm_shape = if context.config.indent_match_arms() {
1474 shape.block_indent(context.config.tab_spaces())
1476 shape.block_indent(0)
1479 let arm_indent_str = arm_shape.indent.to_string(context.config);
1481 let open_brace_pos = context.codemap.span_after(
1482 mk_sp(cond.span.hi, arm_start_pos(&arms[0])),
1486 for (i, arm) in arms.iter().enumerate() {
1487 // Make sure we get the stuff between arms.
1488 let missed_str = if i == 0 {
1489 context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
1491 context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
1493 let comment = try_opt!(rewrite_match_arm_comment(
1499 result.push_str(&comment);
1501 result.push_str(&arm_indent_str);
1503 let arm_str = arm.rewrite(&context, arm_shape.with_max_width(context.config));
1504 if let Some(ref arm_str) = arm_str {
1505 result.push_str(arm_str);
1507 // We couldn't format the arm, just reproduce the source.
1508 let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
1509 result.push_str(&snippet);
1510 result.push_str(arm_comma(context.config, &arm.body));
1513 // BytePos(1) = closing match brace.
1514 let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
1515 let last_comment = context.snippet(last_span);
1516 let comment = try_opt!(rewrite_match_arm_comment(
1522 result.push_str(&comment);
1524 result.push_str(&shape.indent.to_string(context.config));
1529 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
1535 if !attrs.is_empty() {
1536 return attrs[0].span.lo;
1542 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
1546 fn arm_comma(config: &Config, body: &ast::Expr) -> &'static str {
1547 if config.match_block_trailing_comma() {
1549 } else if let ast::ExprKind::Block(ref block) = body.node {
1550 if let ast::BlockCheckMode::Default = block.rules {
1561 impl Rewrite for ast::Arm {
1562 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1563 debug!("Arm::rewrite {:?} {:?}", self, shape);
1571 let attr_str = if !attrs.is_empty() {
1572 if contains_skip(attrs) {
1577 try_opt!(attrs.rewrite(context, shape)),
1578 shape.indent.to_string(context.config)
1586 let pat_shape = try_opt!(shape.sub_width(5));
1588 let pat_strs = try_opt!(
1590 .map(|p| p.rewrite(context, pat_shape))
1591 .collect::<Option<Vec<_>>>()
1594 let all_simple = pat_strs.iter().all(|p| pat_is_simple(p));
1595 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1596 let fmt = ListFormatting {
1597 tactic: if all_simple {
1598 DefinitiveListTactic::Mixed
1600 DefinitiveListTactic::Vertical
1603 trailing_separator: SeparatorTactic::Never,
1605 ends_with_newline: false,
1606 config: context.config,
1608 let pats_str = try_opt!(write_list(items, &fmt));
1610 let guard_shape = if pats_str.contains('\n') {
1611 shape.with_max_width(context.config)
1616 let guard_str = try_opt!(rewrite_guard(
1620 trimmed_last_line_width(&pats_str),
1623 let pats_str = format!("{}{}", pats_str, guard_str);
1625 let (mut extend, body) = match body.node {
1626 ast::ExprKind::Block(ref block)
1627 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) &&
1628 context.config.wrap_match_arms() => {
1629 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1635 ast::ExprKind::Call(_, ref args) => (args.len() == 1, &**body),
1636 ast::ExprKind::Closure(..) |
1637 ast::ExprKind::Struct(..) |
1638 ast::ExprKind::Tup(..) => (true, &**body),
1639 _ => (false, &**body),
1641 extend &= context.use_block_indent();
1643 let comma = arm_comma(&context.config, body);
1644 let alt_block_sep = String::from("\n") +
1645 &shape.indent.block_only().to_string(context.config);
1647 let pat_width = extra_offset(&pats_str, shape);
1648 // Let's try and get the arm body on the same line as the condition.
1650 if shape.width > pat_width + comma.len() + 4 {
1651 let arm_shape = shape
1652 .offset_left(pat_width + 4)
1654 .sub_width(comma.len())
1656 let rewrite = nop_block_collapse(body.rewrite(context, arm_shape), arm_shape.width);
1657 let is_block = if let ast::ExprKind::Block(..) = body.node {
1665 if (!body_str.contains('\n') && body_str.len() <= arm_shape.width) ||
1666 !context.config.wrap_match_arms() ||
1667 (extend && first_line_width(body_str) <= arm_shape.width) ||
1669 let block_sep = match context.config.control_brace_style() {
1670 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep.as_str(),
1674 return Some(format!(
1676 attr_str.trim_left(),
1687 // FIXME: we're doing a second rewrite of the expr; This may not be
1689 let body_shape = try_opt!(shape.block_left(context.config.tab_spaces()));
1690 let next_line_body = try_opt!(nop_block_collapse(
1691 body.rewrite(context, body_shape),
1694 let indent_str = shape
1696 .block_indent(context.config)
1697 .to_string(context.config);
1698 let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1699 if context.config.match_block_trailing_comma() {
1709 let block_sep = match context.config.control_brace_style() {
1710 ControlBraceStyle::AlwaysNextLine => alt_block_sep + body_prefix + "\n",
1711 _ if body_prefix.is_empty() => "\n".to_owned(),
1712 _ => " ".to_owned() + body_prefix + "\n",
1715 if context.config.wrap_match_arms() {
1717 "{}{} =>{}{}{}\n{}{}",
1718 attr_str.trim_left(),
1723 shape.indent.to_string(context.config),
1729 attr_str.trim_left(),
1740 // A pattern is simple if it is very short or it is short-ish and just a path.
1741 // E.g. `Foo::Bar` is simple, but `Foo(..)` is not.
1742 fn pat_is_simple(pat_str: &str) -> bool {
1743 pat_str.len() <= 16 ||
1744 (pat_str.len() <= 24 && pat_str.chars().all(|c| c.is_alphabetic() || c == ':'))
1747 // The `if ...` guard on a match arm.
1749 context: &RewriteContext,
1750 guard: &Option<ptr::P<ast::Expr>>,
1752 // The amount of space used up on this line for the pattern in
1753 // the arm (excludes offset).
1754 pattern_width: usize,
1755 ) -> Option<String> {
1756 if let Some(ref guard) = *guard {
1757 // First try to fit the guard string on the same line as the pattern.
1758 // 4 = ` if `, 5 = ` => {`
1759 if let Some(cond_shape) = shape
1760 .shrink_left(pattern_width + 4)
1761 .and_then(|s| s.sub_width(5))
1763 if let Some(cond_str) = guard
1764 .rewrite(context, cond_shape)
1765 .and_then(|s| s.rewrite(context, cond_shape))
1767 if !cond_str.contains('\n') {
1768 return Some(format!(" if {}", cond_str));
1773 // Not enough space to put the guard after the pattern, try a newline.
1775 if let Some(cond_shape) = Shape::indented(
1776 shape.indent.block_indent(context.config) + 3,
1780 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1781 return Some(format!(
1785 .block_indent(context.config)
1786 .to_string(context.config),
1798 fn rewrite_pat_expr(
1799 context: &RewriteContext,
1800 pat: Option<&ast::Pat>,
1803 // Connecting piece between pattern and expression,
1804 // *without* trailing space.
1808 ) -> Option<String> {
1809 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1810 let mut pat_string = String::new();
1811 let mut result = match pat {
1813 let matcher = if matcher.is_empty() {
1816 format!("{} ", matcher)
1819 try_opt!(try_opt!(shape.offset_left(matcher.len())).sub_width(connector.len()));
1820 pat_string = try_opt!(pat.rewrite(context, pat_shape));
1821 format!("{}{}{}", matcher, pat_string, connector)
1823 None => String::new(),
1826 // Consider only the last line of the pat string.
1827 let extra_offset = extra_offset(&result, shape);
1829 // The expression may (partially) fit on the current line.
1830 if shape.width > extra_offset + 1 {
1831 let spacer = if pat.is_some() { " " } else { "" };
1833 let expr_shape = try_opt!(shape.offset_left(extra_offset + spacer.len()));
1834 let expr_rewrite = expr.rewrite(context, expr_shape);
1836 if let Some(expr_string) = expr_rewrite {
1837 if pat.is_none() || pat_is_simple(&pat_string) || !expr_string.contains('\n') {
1838 result.push_str(spacer);
1839 result.push_str(&expr_string);
1840 return Some(result);
1845 if pat.is_none() && keyword == "if" {
1849 let nested_indent = shape.indent.block_only().block_indent(context.config);
1851 // The expression won't fit on the current line, jump to next.
1853 result.push_str(&nested_indent.to_string(context.config));
1855 let expr_rewrite = expr.rewrite(&context, Shape::indented(nested_indent, context.config));
1856 result.push_str(&try_opt!(expr_rewrite));
1861 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1862 let string_lit = context.snippet(span);
1864 if !context.config.format_strings() && !context.config.force_format_strings() {
1865 return Some(string_lit);
1868 if !context.config.force_format_strings() &&
1869 !string_requires_rewrite(context, span, &string_lit, shape)
1871 return Some(string_lit);
1874 let fmt = StringFormat {
1881 config: context.config,
1884 // Remove the quote characters.
1885 let str_lit = &string_lit[1..string_lit.len() - 1];
1887 rewrite_string(str_lit, &fmt)
1890 fn string_requires_rewrite(
1891 context: &RewriteContext,
1896 if context.codemap.lookup_char_pos(span.lo).col.0 != shape.indent.width() {
1900 for (i, line) in string.lines().enumerate() {
1902 if line.len() > shape.width {
1906 if line.len() > shape.width + shape.indent.width() {
1915 pub fn rewrite_call_with_binary_search<R>(
1916 context: &RewriteContext,
1918 args: &[&ast::Expr],
1925 let closure = |callee_max_width| {
1926 // FIXME using byte lens instead of char lens (and probably all over the
1928 let callee_shape = Shape {
1929 width: callee_max_width,
1932 let callee_str = callee
1933 .rewrite(context, callee_shape)
1934 .ok_or(Ordering::Greater)?;
1942 context.config.fn_call_width(),
1947 binary_search(1, shape.width, closure)
1950 pub fn rewrite_call(
1951 context: &RewriteContext,
1953 args: &[ptr::P<ast::Expr>],
1956 ) -> Option<String> {
1960 &args.iter().map(|x| &**x).collect::<Vec<_>>(),
1963 context.config.fn_call_width(),
1968 pub fn rewrite_call_inner<'a, T>(
1969 context: &RewriteContext,
1974 args_max_width: usize,
1975 force_trailing_comma: bool,
1976 ) -> Result<String, Ordering>
1978 T: Rewrite + Spanned + ToExpr + 'a,
1980 // 2 = `( `, 1 = `(`
1981 let paren_overhead = if context.config.spaces_within_parens() {
1986 let used_width = extra_offset(&callee_str, shape);
1987 let one_line_width = shape
1989 .checked_sub(used_width + 2 * paren_overhead)
1990 .ok_or(Ordering::Greater)?;
1992 let nested_shape = shape_from_fn_call_style(
1995 used_width + 2 * paren_overhead,
1996 used_width + paren_overhead,
1997 ).ok_or(Ordering::Greater)?;
1999 let span_lo = context.codemap.span_after(span, "(");
2000 let args_span = mk_sp(span_lo, span.hi);
2002 let (extendable, list_str) = rewrite_call_args(
2009 force_trailing_comma,
2010 ).or_else(|| if context.use_block_indent() {
2016 shape.block().indent.block_indent(context.config),
2021 force_trailing_comma,
2026 .ok_or(Ordering::Less)?;
2028 if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
2029 let mut new_context = context.clone();
2030 new_context.use_block = true;
2031 return rewrite_call_inner(
2038 force_trailing_comma,
2042 let args_shape = shape
2043 .sub_width(last_line_width(&callee_str))
2044 .ok_or(Ordering::Less)?;
2048 wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2052 fn need_block_indent(s: &str, shape: Shape) -> bool {
2053 s.lines().skip(1).any(|s| {
2054 s.find(|c| !char::is_whitespace(c)).map_or(
2056 |w| w + 1 < shape.indent.width(),
2061 fn rewrite_call_args<'a, T>(
2062 context: &RewriteContext,
2066 one_line_width: usize,
2067 args_max_width: usize,
2068 force_trailing_comma: bool,
2069 ) -> Option<(bool, String)>
2071 T: Rewrite + Spanned + ToExpr + 'a,
2073 let mut item_context = context.clone();
2074 item_context.inside_macro = false;
2075 let items = itemize_list(
2079 |item| item.span().lo,
2080 |item| item.span().hi,
2081 |item| item.rewrite(&item_context, shape),
2085 let mut item_vec: Vec<_> = items.collect();
2087 // Try letting the last argument overflow to the next line with block
2088 // indentation. If its first line fits on one line with the other arguments,
2089 // we format the function arguments horizontally.
2090 let tactic = try_overflow_last_arg(
2099 let fmt = ListFormatting {
2102 trailing_separator: if force_trailing_comma {
2103 SeparatorTactic::Always
2104 } else if context.inside_macro || !context.use_block_indent() {
2105 SeparatorTactic::Never
2107 context.config.trailing_comma()
2110 ends_with_newline: false,
2111 config: context.config,
2114 write_list(&item_vec, &fmt).map(|args_str| {
2115 (tactic != DefinitiveListTactic::Vertical, args_str)
2119 fn try_overflow_last_arg<'a, T>(
2120 context: &RewriteContext,
2121 item_vec: &mut Vec<ListItem>,
2124 one_line_width: usize,
2125 args_max_width: usize,
2126 ) -> DefinitiveListTactic
2128 T: Rewrite + Spanned + ToExpr + 'a,
2130 let overflow_last = can_be_overflowed(&context, args);
2132 // Replace the last item with its first line to see if it fits with
2134 let (orig_last, placeholder) = if overflow_last {
2135 let mut context = context.clone();
2136 if let Some(expr) = args[args.len() - 1].to_expr() {
2138 ast::ExprKind::MethodCall(..) => context.force_one_line_chain = true,
2142 last_arg_shape(&context, &item_vec, shape, args_max_width)
2143 .map_or((None, None), |arg_shape| {
2144 rewrite_last_arg_with_overflow(
2146 args[args.len() - 1],
2147 &mut item_vec[args.len() - 1],
2155 let tactic = definitive_tactic(
2157 ListTactic::LimitedHorizontalVertical(args_max_width),
2161 // Replace the stub with the full overflowing last argument if the rewrite
2162 // succeeded and its first line fits with the other arguments.
2163 match (overflow_last, tactic, placeholder) {
2164 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2165 item_vec[args.len() - 1].item = placeholder;
2168 item_vec[args.len() - 1].item = orig_last;
2177 context: &RewriteContext,
2178 items: &Vec<ListItem>,
2180 args_max_width: usize,
2181 ) -> Option<Shape> {
2182 let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
2183 acc + i.item.as_ref().map_or(0, |s| first_line_width(&s))
2185 let max_width = min(args_max_width, shape.width);
2186 let arg_indent = if context.use_block_indent() {
2187 shape.block().indent.block_unindent(context.config)
2189 shape.block().indent
2192 width: try_opt!(max_width.checked_sub(overhead)),
2198 // Rewriting closure which is placed at the end of the function call's arg.
2199 // Returns `None` if the reformatted closure 'looks bad'.
2200 fn rewrite_last_closure(
2201 context: &RewriteContext,
2204 ) -> Option<String> {
2205 if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
2206 let body = match body.node {
2207 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
2208 stmt_expr(&block.stmts[0]).unwrap_or(body)
2212 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
2220 // If the closure goes multi line before its body, do not overflow the closure.
2221 if prefix.contains('\n') {
2224 let body_shape = try_opt!(shape.offset_left(extra_offset));
2225 // When overflowing the closure which consists of a single control flow expression,
2226 // force to use block if its condition uses multi line.
2227 if rewrite_cond(context, body, body_shape)
2228 .map(|cond| cond.contains('\n'))
2231 return rewrite_closure_with_block(context, body_shape, &prefix, body);
2234 // Seems fine, just format the closure in usual manner.
2235 return expr.rewrite(context, shape);
2240 fn rewrite_last_arg_with_overflow<'a, T>(
2241 context: &RewriteContext,
2243 last_item: &mut ListItem,
2245 ) -> (Option<String>, Option<String>)
2247 T: Rewrite + Spanned + ToExpr + 'a,
2249 let rewrite = if let Some(expr) = last_arg.to_expr() {
2251 // When overflowing the closure which consists of a single control flow expression,
2252 // force to use block if its condition uses multi line.
2253 ast::ExprKind::Closure(..) => rewrite_last_closure(context, expr, shape),
2254 _ => expr.rewrite(context, shape),
2257 last_arg.rewrite(context, shape)
2259 let orig_last = last_item.item.clone();
2261 if let Some(rewrite) = rewrite {
2262 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2263 last_item.item = rewrite_first_line;
2264 (orig_last, Some(rewrite))
2270 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2272 T: Rewrite + Spanned + ToExpr + 'a,
2276 |x| x.can_be_overflowed(context, args.len()),
2280 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2282 ast::ExprKind::Match(..) => {
2283 (context.use_block_indent() && args_len == 1) ||
2284 (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
2286 ast::ExprKind::If(..) |
2287 ast::ExprKind::IfLet(..) |
2288 ast::ExprKind::ForLoop(..) |
2289 ast::ExprKind::Loop(..) |
2290 ast::ExprKind::While(..) |
2291 ast::ExprKind::WhileLet(..) => {
2292 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2294 ast::ExprKind::Block(..) |
2295 ast::ExprKind::Closure(..) => {
2296 context.use_block_indent() ||
2297 context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
2299 ast::ExprKind::Call(..) |
2300 ast::ExprKind::MethodCall(..) |
2301 ast::ExprKind::Mac(..) |
2302 ast::ExprKind::Struct(..) => context.use_block_indent() && args_len == 1,
2303 ast::ExprKind::Tup(..) => context.use_block_indent(),
2304 ast::ExprKind::AddrOf(_, ref expr) |
2305 ast::ExprKind::Box(ref expr) |
2306 ast::ExprKind::Try(ref expr) |
2307 ast::ExprKind::Unary(_, ref expr) |
2308 ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2313 fn paren_overhead(context: &RewriteContext) -> usize {
2314 if context.config.spaces_within_parens() {
2321 pub fn wrap_args_with_parens(
2322 context: &RewriteContext,
2324 is_extendable: bool,
2326 nested_shape: Shape,
2328 if !context.use_block_indent() ||
2329 (context.inside_macro && !args_str.contains('\n') &&
2330 args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2332 if context.config.spaces_within_parens() && args_str.len() > 0 {
2333 format!("( {} )", args_str)
2335 format!("({})", args_str)
2340 nested_shape.indent.to_string(context.config),
2342 shape.block().indent.to_string(context.config)
2347 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2348 debug!("rewrite_paren, shape: {:?}", shape);
2349 let paren_overhead = paren_overhead(context);
2350 let sub_shape = try_opt!(shape.sub_width(paren_overhead / 2)).visual_indent(paren_overhead / 2);
2352 let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && s.len() > 0 {
2353 format!("( {} )", s)
2358 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2359 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2361 if subexpr_str.contains('\n') {
2362 Some(paren_wrapper(&subexpr_str))
2364 if subexpr_str.len() + paren_overhead <= shape.width {
2365 Some(paren_wrapper(&subexpr_str))
2367 let sub_shape = try_opt!(shape.offset_left(2));
2368 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2369 Some(paren_wrapper(&subexpr_str))
2377 context: &RewriteContext,
2379 ) -> Option<String> {
2380 let expr_str = try_opt!(expr.rewrite(context, shape));
2382 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
2388 let offset = expr_str.len() + lbr.len();
2389 if let Some(index_shape) = shape.visual_indent(offset).sub_width(offset + rbr.len()) {
2390 if let Some(index_str) = index.rewrite(context, index_shape) {
2391 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2395 let indent = shape.indent.block_indent(&context.config);
2396 let indent = indent.to_string(&context.config);
2397 // FIXME this is not right, since we don't take into account that shape.width
2398 // might be reduced from max_width by something on the right.
2399 let budget = try_opt!(
2403 .checked_sub(indent.len() + lbr.len() + rbr.len())
2405 let index_str = try_opt!(index.rewrite(context, Shape::legacy(budget, shape.indent)));
2416 fn rewrite_struct_lit<'a>(
2417 context: &RewriteContext,
2419 fields: &'a [ast::Field],
2420 base: Option<&'a ast::Expr>,
2423 ) -> Option<String> {
2424 debug!("rewrite_struct_lit: shape {:?}", shape);
2426 enum StructLitField<'a> {
2427 Regular(&'a ast::Field),
2428 Base(&'a ast::Expr),
2432 let path_shape = try_opt!(shape.sub_width(2));
2433 let path_str = try_opt!(rewrite_path(
2441 if fields.len() == 0 && base.is_none() {
2442 return Some(format!("{} {{}}", path_str));
2445 let field_iter = fields
2447 .map(StructLitField::Regular)
2448 .chain(base.into_iter().map(StructLitField::Base));
2450 // Foo { a: Foo } - indent is +3, width is -5.
2451 let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
2453 let span_lo = |item: &StructLitField| match *item {
2454 StructLitField::Regular(field) => field.span.lo,
2455 StructLitField::Base(expr) => {
2456 let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
2457 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
2458 let pos = snippet.find_uncommented("..").unwrap();
2459 last_field_hi + BytePos(pos as u32)
2462 let span_hi = |item: &StructLitField| match *item {
2463 StructLitField::Regular(field) => field.span.hi,
2464 StructLitField::Base(expr) => expr.span.hi,
2466 let rewrite = |item: &StructLitField| match *item {
2467 StructLitField::Regular(field) => {
2468 // The 1 taken from the v_budget is for the comma.
2469 rewrite_field(context, field, try_opt!(v_shape.sub_width(1)))
2471 StructLitField::Base(expr) => {
2473 expr.rewrite(context, try_opt!(v_shape.shrink_left(2)))
2474 .map(|s| format!("..{}", s))
2478 let items = itemize_list(
2485 context.codemap.span_after(span, "{"),
2488 let item_vec = items.collect::<Vec<_>>();
2490 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2491 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2492 let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2494 let fields_str = try_opt!(write_list(&item_vec, &fmt));
2495 let fields_str = if context.config.struct_lit_style() == IndentStyle::Block &&
2496 (fields_str.contains('\n') ||
2497 context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti ||
2498 fields_str.len() > h_shape.map(|s| s.width).unwrap_or(0))
2502 v_shape.indent.to_string(context.config),
2504 shape.indent.to_string(context.config)
2507 // One liner or visual indent.
2508 format!(" {} ", fields_str)
2511 Some(format!("{} {{{}}}", path_str, fields_str))
2513 // FIXME if context.config.struct_lit_style() == Visual, but we run out
2514 // of space, we should fall back to BlockIndent.
2517 pub fn struct_lit_field_separator(config: &Config) -> &str {
2519 config.space_before_struct_lit_field_colon(),
2520 config.space_after_struct_lit_field_colon(),
2524 fn rewrite_field(context: &RewriteContext, field: &ast::Field, shape: Shape) -> Option<String> {
2525 let name = &field.ident.node.to_string();
2526 if field.is_shorthand {
2527 Some(name.to_string())
2529 let separator = struct_lit_field_separator(context.config);
2530 let overhead = name.len() + separator.len();
2531 let mut expr_shape = try_opt!(shape.sub_width(overhead));
2532 expr_shape.offset += overhead;
2533 let expr = field.expr.rewrite(context, expr_shape);
2535 let mut attrs_str = try_opt!((*field.attrs).rewrite(context, shape));
2536 if !attrs_str.is_empty() {
2537 attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2541 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2543 let expr_offset = shape.indent.block_indent(context.config);
2544 let expr = field.expr.rewrite(
2546 Shape::indented(expr_offset, context.config),
2553 expr_offset.to_string(&context.config),
2562 fn shape_from_fn_call_style(
2563 context: &RewriteContext,
2567 ) -> Option<Shape> {
2568 if context.use_block_indent() {
2572 .block_indent(context.config.tab_spaces())
2573 .with_max_width(context.config)
2576 shape.visual_indent(offset).sub_width(overhead)
2580 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2581 context: &RewriteContext,
2587 T: Rewrite + Spanned + ToExpr + 'a,
2589 let mut items = items.iter();
2590 // In case of length 1, need a trailing comma
2591 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2592 if items.len() == 1 {
2594 let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
2595 return items.next().unwrap().rewrite(context, nested_shape).map(
2596 |s| if context.config.spaces_within_parens() {
2597 format!("( {}, )", s)
2604 let list_lo = context.codemap.span_after(span, "(");
2605 let nested_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
2606 let items = itemize_list(
2610 |item| item.span().lo,
2611 |item| item.span().hi,
2612 |item| item.rewrite(context, nested_shape),
2614 span.hi - BytePos(1),
2616 let list_str = try_opt!(format_item_list(items, nested_shape, context.config));
2618 if context.config.spaces_within_parens() && list_str.len() > 0 {
2619 Some(format!("( {} )", list_str))
2621 Some(format!("({})", list_str))
2625 pub fn rewrite_tuple<'a, T>(
2626 context: &RewriteContext,
2632 T: Rewrite + Spanned + ToExpr + 'a,
2634 debug!("rewrite_tuple {:?}", shape);
2635 if context.use_block_indent() {
2636 // We use the same rule as funcation call for rewriting tuple.
2643 context.config.fn_call_width(),
2647 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2651 pub fn rewrite_unary_prefix<R: Rewrite>(
2652 context: &RewriteContext,
2656 ) -> Option<String> {
2658 .rewrite(context, try_opt!(shape.offset_left(prefix.len())))
2659 .map(|r| format!("{}{}", prefix, r))
2662 // FIXME: this is probably not correct for multi-line Rewrites. we should
2663 // subtract suffix.len() from the last line budget, not the first!
2664 pub fn rewrite_unary_suffix<R: Rewrite>(
2665 context: &RewriteContext,
2669 ) -> Option<String> {
2671 .rewrite(context, try_opt!(shape.sub_width(suffix.len())))
2678 fn rewrite_unary_op(
2679 context: &RewriteContext,
2683 ) -> Option<String> {
2684 // For some reason, an UnOp is not spanned like BinOp!
2685 let operator_str = match *op {
2686 ast::UnOp::Deref => "*",
2687 ast::UnOp::Not => "!",
2688 ast::UnOp::Neg => "-",
2690 rewrite_unary_prefix(context, operator_str, expr, shape)
2693 fn rewrite_assignment(
2694 context: &RewriteContext,
2697 op: Option<&ast::BinOp>,
2699 ) -> Option<String> {
2700 let operator_str = match op {
2701 Some(op) => context.snippet(op.span),
2702 None => "=".to_owned(),
2705 // 1 = space between lhs and operator.
2706 let lhs_shape = try_opt!(shape.sub_width(operator_str.len() + 1));
2707 let lhs_str = format!(
2709 try_opt!(lhs.rewrite(context, lhs_shape)),
2713 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2716 // The left hand side must contain everything up to, and including, the
2717 // assignment operator.
2718 pub fn rewrite_assign_rhs<S: Into<String>>(
2719 context: &RewriteContext,
2723 ) -> Option<String> {
2724 let mut result = lhs.into();
2725 let last_line_width = last_line_width(&result) -
2726 if result.contains('\n') {
2727 shape.indent.width()
2731 // 1 = space between operator and rhs.
2732 let orig_shape = try_opt!(shape.block_indent(0).offset_left(last_line_width + 1));
2733 let rhs = match ex.node {
2734 ast::ExprKind::Mac(ref mac) => {
2735 match rewrite_macro(mac, None, context, orig_shape, MacroPosition::Expression) {
2736 None if !context.snippet(ex.span).contains("\n") => {
2737 context.snippet(ex.span).rewrite(context, orig_shape)
2742 _ => ex.rewrite(context, orig_shape),
2745 fn count_line_breaks(src: &str) -> usize {
2746 src.chars().filter(|&x| x == '\n').count()
2750 Some(ref new_str) if count_line_breaks(new_str) < 2 => {
2752 result.push_str(new_str);
2755 // Expression did not fit on the same line as the identifier or is
2756 // at least three lines big. Try splitting the line and see
2757 // if that works better.
2758 let new_shape = try_opt!(shape.block_left(context.config.tab_spaces()));
2759 let new_rhs = ex.rewrite(context, new_shape);
2762 match (rhs, new_rhs) {
2763 (Some(ref orig_rhs), Some(ref replacement_rhs))
2764 if count_line_breaks(orig_rhs) > count_line_breaks(replacement_rhs) + 1 => {
2765 result.push_str(&format!("\n{}", new_shape.indent.to_string(context.config)));
2766 result.push_str(replacement_rhs);
2768 (None, Some(ref final_rhs)) => {
2769 result.push_str(&format!("\n{}", new_shape.indent.to_string(context.config)));
2770 result.push_str(final_rhs);
2772 (None, None) => return None,
2773 (Some(ref orig_rhs), _) => {
2775 result.push_str(orig_rhs);
2784 fn rewrite_expr_addrof(
2785 context: &RewriteContext,
2786 mutability: ast::Mutability,
2789 ) -> Option<String> {
2790 let operator_str = match mutability {
2791 ast::Mutability::Immutable => "&",
2792 ast::Mutability::Mutable => "&mut ",
2794 rewrite_unary_prefix(context, operator_str, expr, shape)
2798 fn to_expr(&self) -> Option<&ast::Expr>;
2799 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2802 impl ToExpr for ast::Expr {
2803 fn to_expr(&self) -> Option<&ast::Expr> {
2807 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2808 can_be_overflowed_expr(context, self, len)
2812 impl ToExpr for ast::Ty {
2813 fn to_expr(&self) -> Option<&ast::Expr> {
2817 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2818 can_be_overflowed_type(context, self, len)
2822 impl<'a> ToExpr for TuplePatField<'a> {
2823 fn to_expr(&self) -> Option<&ast::Expr> {
2827 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2828 can_be_overflowed_pat(context, self, len)