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, last_line_extendable};
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];
1081 try_opt!(else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
1083 if if_str.contains('\n') || else_str.contains('\n') {
1087 let result = format!(
1088 "{} {} {{ {} }} else {{ {} }}",
1095 if result.len() <= width {
1096 return Some(result);
1104 impl<'a> ControlFlow<'a> {
1107 context: &RewriteContext,
1109 alt_block_sep: &str,
1110 ) -> Option<(String, usize)> {
1111 let constr_shape = if self.nested_if {
1112 // We are part of an if-elseif-else chain. Our constraints are tightened.
1113 // 7 = "} else " .len()
1114 try_opt!(shape.shrink_left(7))
1119 let label_string = rewrite_label(self.label);
1120 // 1 = space after keyword.
1121 let offset = self.keyword.len() + label_string.len() + 1;
1123 let pat_expr_string = match self.cond {
1125 let mut cond_shape = match context.config.control_style() {
1126 Style::Legacy => try_opt!(constr_shape.shrink_left(offset)),
1127 Style::Rfc => try_opt!(constr_shape.offset_left(offset)),
1129 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1131 cond_shape = try_opt!(cond_shape.sub_width(2));
1134 try_opt!(rewrite_pat_expr(
1144 None => String::new(),
1147 let force_newline_brace = context.config.control_style() == Style::Rfc &&
1148 pat_expr_string.contains('\n') &&
1149 !last_line_extendable(&pat_expr_string);
1151 // Try to format if-else on single line.
1152 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1153 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1155 if let Some(cond_str) = trial {
1156 if cond_str.len() <= context.config.single_line_if_else_max_width() {
1157 return Some((cond_str, 0));
1162 let cond_span = if let Some(cond) = self.cond {
1165 mk_sp(self.block.span.lo, self.block.span.lo)
1168 // for event in event
1169 let between_kwd_cond = mk_sp(
1170 context.codemap.span_after(self.span, self.keyword.trim()),
1173 |p| if self.matcher.is_empty() {
1176 context.codemap.span_before(self.span, self.matcher.trim())
1181 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1183 let after_cond_comment =
1184 extract_comment(mk_sp(cond_span.hi, self.block.span.lo), context, shape);
1186 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1188 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine ||
1196 let used_width = if pat_expr_string.contains('\n') {
1197 last_line_width(&pat_expr_string)
1199 // 2 = spaces after keyword and condition.
1200 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1208 between_kwd_cond_comment.as_ref().map_or(
1209 if pat_expr_string.is_empty() ||
1210 pat_expr_string.starts_with('\n')
1219 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1226 impl<'a> Rewrite for ControlFlow<'a> {
1227 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1228 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1230 let alt_block_sep = String::from("\n") +
1231 &shape.indent.block_only().to_string(context.config);
1232 let (cond_str, used_width) = try_opt!(self.rewrite_cond(context, shape, &alt_block_sep));
1233 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1234 if used_width == 0 {
1235 return Some(cond_str);
1238 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1239 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1240 // we should avoid the single line case.
1241 let block_width = if self.else_block.is_some() || self.nested_if {
1246 let block_shape = Shape {
1250 let mut block_context = context.clone();
1251 block_context.is_if_else_block = self.else_block.is_some();
1252 let block_str = try_opt!(self.block.rewrite(&block_context, block_shape));
1254 let mut result = format!("{}{}", cond_str, block_str);
1256 if let Some(else_block) = self.else_block {
1257 let shape = Shape::indented(shape.indent, context.config);
1258 let mut last_in_chain = false;
1259 let rewrite = match else_block.node {
1260 // If the else expression is another if-else expression, prevent it
1261 // from being formatted on a single line.
1262 // Note how we're passing the original shape, as the
1263 // cost of "else" should not cascade.
1264 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1265 ControlFlow::new_if(
1269 next_else_block.as_ref().map(|e| &**e),
1272 mk_sp(else_block.span.lo, self.span.hi),
1273 ).rewrite(context, shape)
1275 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1276 ControlFlow::new_if(
1280 next_else_block.as_ref().map(|e| &**e),
1283 mk_sp(else_block.span.lo, self.span.hi),
1284 ).rewrite(context, shape)
1287 last_in_chain = true;
1288 // When rewriting a block, the width is only used for single line
1289 // blocks, passing 1 lets us avoid that.
1290 let else_shape = Shape {
1291 width: min(1, shape.width),
1294 else_block.rewrite(context, else_shape)
1298 let between_kwd_else_block = mk_sp(
1302 .span_before(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1304 let between_kwd_else_block_comment =
1305 extract_comment(between_kwd_else_block, context, shape);
1307 let after_else = mk_sp(
1310 .span_after(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1313 let after_else_comment = extract_comment(after_else, context, shape);
1315 let between_sep = match context.config.control_brace_style() {
1316 ControlBraceStyle::AlwaysNextLine |
1317 ControlBraceStyle::ClosingNextLine => &*alt_block_sep,
1318 ControlBraceStyle::AlwaysSameLine => " ",
1320 let after_sep = match context.config.control_brace_style() {
1321 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1328 between_kwd_else_block_comment
1330 .map_or(between_sep, |s| &**s),
1331 after_else_comment.as_ref().map_or(after_sep, |s| &**s)
1334 result.push_str(&try_opt!(rewrite));
1341 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
1343 Some(ident) => format!("{}: ", ident.node),
1344 None => "".to_owned(),
1348 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1349 let comment_str = context.snippet(span);
1350 if contains_comment(&comment_str) {
1351 let comment = try_opt!(rewrite_comment(
1358 "\n{indent}{}\n{indent}",
1360 indent = shape.indent.to_string(context.config)
1367 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1368 let snippet = codemap.span_to_snippet(block.span).unwrap();
1369 contains_comment(&snippet)
1372 // Checks that a block contains no statements, an expression and no comments.
1373 // FIXME: incorrectly returns false when comment is contained completely within
1375 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1376 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) &&
1377 !block_contains_comment(block, codemap))
1380 /// Checks whether a block contains at most one statement or expression, and no comments.
1381 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1382 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1385 /// Checks whether a block contains no statements, expressions, or comments.
1386 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1387 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1390 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1392 ast::StmtKind::Expr(..) => true,
1397 fn is_unsafe_block(block: &ast::Block) -> bool {
1398 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1405 // inter-match-arm-comment-rules:
1406 // - all comments following a match arm before the start of the next arm
1407 // are about the second arm
1408 fn rewrite_match_arm_comment(
1409 context: &RewriteContext,
1412 arm_indent_str: &str,
1413 ) -> Option<String> {
1414 // The leading "," is not part of the arm-comment
1415 let missed_str = match missed_str.find_uncommented(",") {
1416 Some(n) => &missed_str[n + 1..],
1417 None => &missed_str[..],
1420 let mut result = String::new();
1421 // any text not preceeded by a newline is pushed unmodified to the block
1422 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
1423 result.push_str(&missed_str[..first_brk]);
1424 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
1426 let first = missed_str
1427 .find(|c: char| !c.is_whitespace())
1428 .unwrap_or(missed_str.len());
1429 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
1430 // Excessive vertical whitespace before comment should be preserved
1431 // FIXME handle vertical whitespace better
1434 let missed_str = missed_str[first..].trim();
1435 if !missed_str.is_empty() {
1436 let comment = try_opt!(rewrite_comment(&missed_str, false, shape, context.config));
1438 result.push_str(arm_indent_str);
1439 result.push_str(&comment);
1446 context: &RewriteContext,
1451 ) -> Option<String> {
1452 if arms.is_empty() {
1457 let cond_shape = match context.config.control_style() {
1458 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
1459 Style::Rfc => try_opt!(shape.offset_left(8)),
1461 let cond_str = try_opt!(cond.rewrite(context, cond_shape));
1462 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1463 let block_sep = match context.config.control_brace_style() {
1464 ControlBraceStyle::AlwaysSameLine => " ",
1465 _ => alt_block_sep.as_str(),
1467 let mut result = format!("match {}{}{{", cond_str, block_sep);
1469 let arm_shape = if context.config.indent_match_arms() {
1470 shape.block_indent(context.config.tab_spaces())
1472 shape.block_indent(0)
1475 let arm_indent_str = arm_shape.indent.to_string(context.config);
1477 let open_brace_pos = context
1479 .span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])), "{");
1481 let arm_num = arms.len();
1482 for (i, arm) in arms.iter().enumerate() {
1483 // Make sure we get the stuff between arms.
1484 let missed_str = if i == 0 {
1485 context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
1487 context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
1489 let comment = try_opt!(rewrite_match_arm_comment(
1495 result.push_str(&comment);
1497 result.push_str(&arm_indent_str);
1499 let arm_str = arm.rewrite(&context, arm_shape.with_max_width(context.config));
1500 if let Some(ref arm_str) = arm_str {
1501 // Trim the trailing comma if necessary.
1502 if i == arm_num - 1 && context.config.trailing_comma() == SeparatorTactic::Never &&
1503 arm_str.ends_with(',')
1505 result.push_str(&arm_str[0..arm_str.len() - 1])
1507 result.push_str(arm_str)
1510 // We couldn't format the arm, just reproduce the source.
1511 let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
1512 result.push_str(&snippet);
1513 if context.config.trailing_comma() != SeparatorTactic::Never {
1514 result.push_str(arm_comma(context.config, &arm.body))
1518 // BytePos(1) = closing match brace.
1519 let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
1520 let last_comment = context.snippet(last_span);
1521 let comment = try_opt!(rewrite_match_arm_comment(
1527 result.push_str(&comment);
1529 result.push_str(&shape.indent.to_string(context.config));
1534 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
1540 if !attrs.is_empty() {
1541 return attrs[0].span.lo;
1547 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
1551 fn arm_comma(config: &Config, body: &ast::Expr) -> &'static str {
1552 if config.match_block_trailing_comma() {
1554 } else if let ast::ExprKind::Block(ref block) = body.node {
1555 if let ast::BlockCheckMode::Default = block.rules {
1566 impl Rewrite for ast::Arm {
1567 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1568 debug!("Arm::rewrite {:?} {:?}", self, shape);
1576 let attr_str = if !attrs.is_empty() {
1577 if contains_skip(attrs) {
1582 try_opt!(attrs.rewrite(context, shape)),
1583 shape.indent.to_string(context.config)
1591 let pat_shape = try_opt!(shape.sub_width(5));
1593 let pat_strs = try_opt!(
1595 .map(|p| p.rewrite(context, pat_shape))
1596 .collect::<Option<Vec<_>>>()
1599 let all_simple = pat_strs.iter().all(|p| pat_is_simple(p));
1600 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1601 let fmt = ListFormatting {
1602 tactic: if all_simple {
1603 DefinitiveListTactic::Mixed
1605 DefinitiveListTactic::Vertical
1608 trailing_separator: SeparatorTactic::Never,
1610 ends_with_newline: false,
1611 config: context.config,
1613 let pats_str = try_opt!(write_list(items, &fmt));
1615 let guard_shape = if pats_str.contains('\n') {
1616 shape.with_max_width(context.config)
1621 let guard_str = try_opt!(rewrite_guard(
1625 trimmed_last_line_width(&pats_str),
1628 let pats_str = format!("{}{}", pats_str, guard_str);
1630 let (mut extend, body) = match body.node {
1631 ast::ExprKind::Block(ref block)
1632 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) &&
1633 context.config.wrap_match_arms() => {
1634 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1640 ast::ExprKind::Call(_, ref args) => (args.len() == 1, &**body),
1641 ast::ExprKind::Closure(..) |
1642 ast::ExprKind::Struct(..) |
1643 ast::ExprKind::Tup(..) => (true, &**body),
1644 _ => (false, &**body),
1646 extend &= context.use_block_indent();
1648 let comma = arm_comma(&context.config, body);
1649 let alt_block_sep = String::from("\n") +
1650 &shape.indent.block_only().to_string(context.config);
1652 let pat_width = extra_offset(&pats_str, shape);
1653 // Let's try and get the arm body on the same line as the condition.
1655 if shape.width > pat_width + comma.len() + 4 {
1656 let arm_shape = shape
1657 .offset_left(pat_width + 4)
1659 .sub_width(comma.len())
1661 let rewrite = nop_block_collapse(body.rewrite(context, arm_shape), arm_shape.width);
1662 let is_block = if let ast::ExprKind::Block(..) = body.node {
1670 if (!body_str.contains('\n') && body_str.len() <= arm_shape.width) ||
1671 !context.config.wrap_match_arms() ||
1672 (extend && first_line_width(body_str) <= arm_shape.width) ||
1674 let block_sep = match context.config.control_brace_style() {
1675 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep.as_str(),
1679 return Some(format!(
1681 attr_str.trim_left(),
1692 // FIXME: we're doing a second rewrite of the expr; This may not be
1694 let body_shape = try_opt!(shape.block_left(context.config.tab_spaces()));
1695 let next_line_body = try_opt!(nop_block_collapse(
1696 body.rewrite(context, body_shape),
1699 let indent_str = shape
1701 .block_indent(context.config)
1702 .to_string(context.config);
1703 let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1704 if context.config.match_block_trailing_comma() {
1714 let block_sep = match context.config.control_brace_style() {
1715 ControlBraceStyle::AlwaysNextLine => alt_block_sep + body_prefix + "\n",
1716 _ if body_prefix.is_empty() => "\n".to_owned(),
1717 _ => " ".to_owned() + body_prefix + "\n",
1720 if context.config.wrap_match_arms() {
1722 "{}{} =>{}{}{}\n{}{}",
1723 attr_str.trim_left(),
1728 shape.indent.to_string(context.config),
1734 attr_str.trim_left(),
1745 // A pattern is simple if it is very short or it is short-ish and just a path.
1746 // E.g. `Foo::Bar` is simple, but `Foo(..)` is not.
1747 fn pat_is_simple(pat_str: &str) -> bool {
1748 pat_str.len() <= 16 ||
1749 (pat_str.len() <= 24 && pat_str.chars().all(|c| c.is_alphabetic() || c == ':'))
1752 // The `if ...` guard on a match arm.
1754 context: &RewriteContext,
1755 guard: &Option<ptr::P<ast::Expr>>,
1757 // The amount of space used up on this line for the pattern in
1758 // the arm (excludes offset).
1759 pattern_width: usize,
1760 ) -> Option<String> {
1761 if let Some(ref guard) = *guard {
1762 // First try to fit the guard string on the same line as the pattern.
1763 // 4 = ` if `, 5 = ` => {`
1764 if let Some(cond_shape) = shape
1765 .shrink_left(pattern_width + 4)
1766 .and_then(|s| s.sub_width(5))
1768 if let Some(cond_str) = guard
1769 .rewrite(context, cond_shape)
1770 .and_then(|s| s.rewrite(context, cond_shape))
1772 if !cond_str.contains('\n') {
1773 return Some(format!(" if {}", cond_str));
1778 // Not enough space to put the guard after the pattern, try a newline.
1780 if let Some(cond_shape) = Shape::indented(
1781 shape.indent.block_indent(context.config) + 3,
1785 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1786 return Some(format!(
1790 .block_indent(context.config)
1791 .to_string(context.config),
1803 fn rewrite_pat_expr(
1804 context: &RewriteContext,
1805 pat: Option<&ast::Pat>,
1808 // Connecting piece between pattern and expression,
1809 // *without* trailing space.
1813 ) -> Option<String> {
1814 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1815 let mut pat_string = String::new();
1816 let mut result = match pat {
1818 let matcher = if matcher.is_empty() {
1821 format!("{} ", matcher)
1824 try_opt!(try_opt!(shape.offset_left(matcher.len())).sub_width(connector.len()));
1825 pat_string = try_opt!(pat.rewrite(context, pat_shape));
1826 format!("{}{}{}", matcher, pat_string, connector)
1828 None => String::new(),
1831 // Consider only the last line of the pat string.
1832 let extra_offset = extra_offset(&result, shape);
1834 // The expression may (partially) fit on the current line.
1835 if shape.width > extra_offset + 1 {
1836 let spacer = if pat.is_some() { " " } else { "" };
1838 let expr_shape = try_opt!(shape.offset_left(extra_offset + spacer.len()));
1839 let expr_rewrite = expr.rewrite(context, expr_shape);
1841 if let Some(expr_string) = expr_rewrite {
1842 if pat.is_none() || pat_is_simple(&pat_string) || !expr_string.contains('\n') {
1843 result.push_str(spacer);
1844 result.push_str(&expr_string);
1845 return Some(result);
1850 if pat.is_none() && keyword == "if" {
1854 let nested_indent = shape.indent.block_only().block_indent(context.config);
1856 // The expression won't fit on the current line, jump to next.
1858 result.push_str(&nested_indent.to_string(context.config));
1860 let expr_rewrite = expr.rewrite(&context, Shape::indented(nested_indent, context.config));
1861 result.push_str(&try_opt!(expr_rewrite));
1866 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1867 let string_lit = context.snippet(span);
1869 if !context.config.format_strings() && !context.config.force_format_strings() {
1874 .all(|line| line.ends_with('\\'))
1876 let new_indent = shape.visual_indent(1).indent;
1877 return Some(String::from(
1881 new_indent.to_string(context.config) + line.trim_left()
1883 .collect::<Vec<_>>()
1888 return Some(string_lit);
1892 if !context.config.force_format_strings() &&
1893 !string_requires_rewrite(context, span, &string_lit, shape)
1895 return Some(string_lit);
1898 let fmt = StringFormat {
1905 config: context.config,
1908 // Remove the quote characters.
1909 let str_lit = &string_lit[1..string_lit.len() - 1];
1911 rewrite_string(str_lit, &fmt)
1914 fn string_requires_rewrite(
1915 context: &RewriteContext,
1920 if context.codemap.lookup_char_pos(span.lo).col.0 != shape.indent.width() {
1924 for (i, line) in string.lines().enumerate() {
1926 if line.len() > shape.width {
1930 if line.len() > shape.width + shape.indent.width() {
1939 pub fn rewrite_call_with_binary_search<R>(
1940 context: &RewriteContext,
1942 args: &[&ast::Expr],
1949 let closure = |callee_max_width| {
1950 // FIXME using byte lens instead of char lens (and probably all over the
1952 let callee_shape = Shape {
1953 width: callee_max_width,
1956 let callee_str = callee
1957 .rewrite(context, callee_shape)
1958 .ok_or(Ordering::Greater)?;
1966 context.config.fn_call_width(),
1971 binary_search(1, shape.width, closure)
1974 pub fn rewrite_call(
1975 context: &RewriteContext,
1977 args: &[ptr::P<ast::Expr>],
1980 ) -> Option<String> {
1984 &args.iter().map(|x| &**x).collect::<Vec<_>>(),
1987 context.config.fn_call_width(),
1992 pub fn rewrite_call_inner<'a, T>(
1993 context: &RewriteContext,
1998 args_max_width: usize,
1999 force_trailing_comma: bool,
2000 ) -> Result<String, Ordering>
2002 T: Rewrite + Spanned + ToExpr + 'a,
2004 // 2 = `( `, 1 = `(`
2005 let paren_overhead = if context.config.spaces_within_parens() {
2010 let used_width = extra_offset(&callee_str, shape);
2011 let one_line_width = shape
2013 .checked_sub(used_width + 2 * paren_overhead)
2014 .ok_or(Ordering::Greater)?;
2016 let nested_shape = shape_from_fn_call_style(
2019 used_width + 2 * paren_overhead,
2020 used_width + paren_overhead,
2021 ).ok_or(Ordering::Greater)?;
2023 let span_lo = context.codemap.span_after(span, "(");
2024 let args_span = mk_sp(span_lo, span.hi);
2026 let (extendable, list_str) = rewrite_call_args(
2033 force_trailing_comma,
2034 ).or_else(|| if context.use_block_indent() {
2040 shape.block().indent.block_indent(context.config),
2045 force_trailing_comma,
2050 .ok_or(Ordering::Less)?;
2052 if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
2053 let mut new_context = context.clone();
2054 new_context.use_block = true;
2055 return rewrite_call_inner(
2062 force_trailing_comma,
2066 let args_shape = shape
2067 .sub_width(last_line_width(&callee_str))
2068 .ok_or(Ordering::Less)?;
2072 wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2076 fn need_block_indent(s: &str, shape: Shape) -> bool {
2077 s.lines().skip(1).any(|s| {
2078 s.find(|c| !char::is_whitespace(c))
2079 .map_or(false, |w| w + 1 < shape.indent.width())
2083 fn rewrite_call_args<'a, T>(
2084 context: &RewriteContext,
2088 one_line_width: usize,
2089 args_max_width: usize,
2090 force_trailing_comma: bool,
2091 ) -> Option<(bool, String)>
2093 T: Rewrite + Spanned + ToExpr + 'a,
2095 let mut item_context = context.clone();
2096 item_context.inside_macro = false;
2097 let items = itemize_list(
2101 |item| item.span().lo,
2102 |item| item.span().hi,
2103 |item| item.rewrite(&item_context, shape),
2107 let mut item_vec: Vec<_> = items.collect();
2109 // Try letting the last argument overflow to the next line with block
2110 // indentation. If its first line fits on one line with the other arguments,
2111 // we format the function arguments horizontally.
2112 let tactic = try_overflow_last_arg(
2121 let fmt = ListFormatting {
2124 trailing_separator: if force_trailing_comma {
2125 SeparatorTactic::Always
2126 } else if context.inside_macro || !context.use_block_indent() {
2127 SeparatorTactic::Never
2129 context.config.trailing_comma()
2132 ends_with_newline: false,
2133 config: context.config,
2136 write_list(&item_vec, &fmt).map(|args_str| {
2137 (tactic != DefinitiveListTactic::Vertical, args_str)
2141 fn try_overflow_last_arg<'a, T>(
2142 context: &RewriteContext,
2143 item_vec: &mut Vec<ListItem>,
2146 one_line_width: usize,
2147 args_max_width: usize,
2148 ) -> DefinitiveListTactic
2150 T: Rewrite + Spanned + ToExpr + 'a,
2152 let overflow_last = can_be_overflowed(&context, args);
2154 // Replace the last item with its first line to see if it fits with
2156 let (orig_last, placeholder) = if overflow_last {
2157 let mut context = context.clone();
2158 if let Some(expr) = args[args.len() - 1].to_expr() {
2160 ast::ExprKind::MethodCall(..) => context.force_one_line_chain = true,
2164 last_arg_shape(&context, &item_vec, shape, args_max_width)
2165 .map_or((None, None), |arg_shape| {
2166 rewrite_last_arg_with_overflow(
2169 &mut item_vec[args.len() - 1],
2177 let tactic = definitive_tactic(
2179 ListTactic::LimitedHorizontalVertical(args_max_width),
2183 // Replace the stub with the full overflowing last argument if the rewrite
2184 // succeeded and its first line fits with the other arguments.
2185 match (overflow_last, tactic, placeholder) {
2186 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2187 item_vec[args.len() - 1].item = placeholder;
2190 item_vec[args.len() - 1].item = orig_last;
2199 context: &RewriteContext,
2200 items: &Vec<ListItem>,
2202 args_max_width: usize,
2203 ) -> Option<Shape> {
2204 let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
2205 acc + i.item.as_ref().map_or(0, |s| first_line_width(&s))
2207 let max_width = min(args_max_width, shape.width);
2208 let arg_indent = if context.use_block_indent() {
2209 shape.block().indent.block_unindent(context.config)
2211 shape.block().indent
2214 width: try_opt!(max_width.checked_sub(overhead)),
2220 // Rewriting closure which is placed at the end of the function call's arg.
2221 // Returns `None` if the reformatted closure 'looks bad'.
2222 fn rewrite_last_closure(
2223 context: &RewriteContext,
2226 ) -> Option<String> {
2227 if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
2228 let body = match body.node {
2229 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
2230 stmt_expr(&block.stmts[0]).unwrap_or(body)
2234 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
2242 // If the closure goes multi line before its body, do not overflow the closure.
2243 if prefix.contains('\n') {
2246 let body_shape = try_opt!(shape.offset_left(extra_offset));
2247 // When overflowing the closure which consists of a single control flow expression,
2248 // force to use block if its condition uses multi line.
2249 if rewrite_cond(context, body, body_shape)
2250 .map(|cond| cond.contains('\n'))
2253 return rewrite_closure_with_block(context, body_shape, &prefix, body);
2256 // Seems fine, just format the closure in usual manner.
2257 return expr.rewrite(context, shape);
2262 fn rewrite_last_arg_with_overflow<'a, T>(
2263 context: &RewriteContext,
2265 last_item: &mut ListItem,
2267 ) -> (Option<String>, Option<String>)
2269 T: Rewrite + Spanned + ToExpr + 'a,
2271 let last_arg = args[args.len() - 1];
2272 let rewrite = if let Some(expr) = last_arg.to_expr() {
2274 // When overflowing the closure which consists of a single control flow expression,
2275 // force to use block if its condition uses multi line.
2276 ast::ExprKind::Closure(..) => {
2277 // If the argument consists of multiple closures, we do not overflow
2278 // the last closure.
2279 if args.len() > 1 &&
2283 .filter_map(|arg| arg.to_expr())
2284 .any(|expr| match expr.node {
2285 ast::ExprKind::Closure(..) => true,
2290 rewrite_last_closure(context, expr, shape)
2293 _ => expr.rewrite(context, shape),
2296 last_arg.rewrite(context, shape)
2298 let orig_last = last_item.item.clone();
2300 if let Some(rewrite) = rewrite {
2301 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2302 last_item.item = rewrite_first_line;
2303 (orig_last, Some(rewrite))
2309 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2311 T: Rewrite + Spanned + ToExpr + 'a,
2314 .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2317 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2319 ast::ExprKind::Match(..) => {
2320 (context.use_block_indent() && args_len == 1) ||
2321 (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
2323 ast::ExprKind::If(..) |
2324 ast::ExprKind::IfLet(..) |
2325 ast::ExprKind::ForLoop(..) |
2326 ast::ExprKind::Loop(..) |
2327 ast::ExprKind::While(..) |
2328 ast::ExprKind::WhileLet(..) => {
2329 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2331 ast::ExprKind::Block(..) |
2332 ast::ExprKind::Closure(..) => {
2333 context.use_block_indent() ||
2334 context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
2336 ast::ExprKind::Call(..) |
2337 ast::ExprKind::MethodCall(..) |
2338 ast::ExprKind::Mac(..) |
2339 ast::ExprKind::Struct(..) |
2340 ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2341 ast::ExprKind::AddrOf(_, ref expr) |
2342 ast::ExprKind::Box(ref expr) |
2343 ast::ExprKind::Try(ref expr) |
2344 ast::ExprKind::Unary(_, ref expr) |
2345 ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2350 fn paren_overhead(context: &RewriteContext) -> usize {
2351 if context.config.spaces_within_parens() {
2358 pub fn wrap_args_with_parens(
2359 context: &RewriteContext,
2361 is_extendable: bool,
2363 nested_shape: Shape,
2365 if !context.use_block_indent() ||
2366 (context.inside_macro && !args_str.contains('\n') &&
2367 args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2369 if context.config.spaces_within_parens() && args_str.len() > 0 {
2370 format!("( {} )", args_str)
2372 format!("({})", args_str)
2377 nested_shape.indent.to_string(context.config),
2379 shape.block().indent.to_string(context.config)
2384 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2385 debug!("rewrite_paren, shape: {:?}", shape);
2386 let paren_overhead = paren_overhead(context);
2387 let sub_shape = try_opt!(shape.sub_width(paren_overhead / 2)).visual_indent(paren_overhead / 2);
2389 let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && s.len() > 0 {
2390 format!("( {} )", s)
2395 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2396 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2398 if subexpr_str.contains('\n') {
2399 Some(paren_wrapper(&subexpr_str))
2401 if subexpr_str.len() + paren_overhead <= shape.width {
2402 Some(paren_wrapper(&subexpr_str))
2404 let sub_shape = try_opt!(shape.offset_left(2));
2405 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2406 Some(paren_wrapper(&subexpr_str))
2414 context: &RewriteContext,
2416 ) -> Option<String> {
2417 let expr_str = try_opt!(expr.rewrite(context, shape));
2419 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
2425 let offset = expr_str.len() + lbr.len();
2426 if let Some(index_shape) = shape.visual_indent(offset).sub_width(offset + rbr.len()) {
2427 if let Some(index_str) = index.rewrite(context, index_shape) {
2428 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2432 let indent = shape.indent.block_indent(&context.config);
2433 let indent = indent.to_string(&context.config);
2434 // FIXME this is not right, since we don't take into account that shape.width
2435 // might be reduced from max_width by something on the right.
2436 let budget = try_opt!(
2440 .checked_sub(indent.len() + lbr.len() + rbr.len())
2442 let index_str = try_opt!(index.rewrite(context, Shape::legacy(budget, shape.indent)));
2453 fn rewrite_struct_lit<'a>(
2454 context: &RewriteContext,
2456 fields: &'a [ast::Field],
2457 base: Option<&'a ast::Expr>,
2460 ) -> Option<String> {
2461 debug!("rewrite_struct_lit: shape {:?}", shape);
2463 enum StructLitField<'a> {
2464 Regular(&'a ast::Field),
2465 Base(&'a ast::Expr),
2469 let path_shape = try_opt!(shape.sub_width(2));
2470 let path_str = try_opt!(rewrite_path(
2478 if fields.len() == 0 && base.is_none() {
2479 return Some(format!("{} {{}}", path_str));
2482 let field_iter = fields
2484 .map(StructLitField::Regular)
2485 .chain(base.into_iter().map(StructLitField::Base));
2487 // Foo { a: Foo } - indent is +3, width is -5.
2488 let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
2490 let span_lo = |item: &StructLitField| match *item {
2491 StructLitField::Regular(field) => field.span.lo,
2492 StructLitField::Base(expr) => {
2493 let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
2494 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
2495 let pos = snippet.find_uncommented("..").unwrap();
2496 last_field_hi + BytePos(pos as u32)
2499 let span_hi = |item: &StructLitField| match *item {
2500 StructLitField::Regular(field) => field.span.hi,
2501 StructLitField::Base(expr) => expr.span.hi,
2503 let rewrite = |item: &StructLitField| match *item {
2504 StructLitField::Regular(field) => {
2505 // The 1 taken from the v_budget is for the comma.
2506 rewrite_field(context, field, try_opt!(v_shape.sub_width(1)))
2508 StructLitField::Base(expr) => {
2510 expr.rewrite(context, try_opt!(v_shape.shrink_left(2)))
2511 .map(|s| format!("..{}", s))
2515 let items = itemize_list(
2522 context.codemap.span_after(span, "{"),
2525 let item_vec = items.collect::<Vec<_>>();
2527 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2528 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2529 let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2531 let fields_str = try_opt!(write_list(&item_vec, &fmt));
2532 let fields_str = if context.config.struct_lit_style() == IndentStyle::Block &&
2533 (fields_str.contains('\n') ||
2534 context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti ||
2535 fields_str.len() > h_shape.map(|s| s.width).unwrap_or(0))
2539 v_shape.indent.to_string(context.config),
2541 shape.indent.to_string(context.config)
2544 // One liner or visual indent.
2545 format!(" {} ", fields_str)
2548 Some(format!("{} {{{}}}", path_str, fields_str))
2550 // FIXME if context.config.struct_lit_style() == Visual, but we run out
2551 // of space, we should fall back to BlockIndent.
2554 pub fn struct_lit_field_separator(config: &Config) -> &str {
2556 config.space_before_struct_lit_field_colon(),
2557 config.space_after_struct_lit_field_colon(),
2561 fn rewrite_field(context: &RewriteContext, field: &ast::Field, shape: Shape) -> Option<String> {
2562 let name = &field.ident.node.to_string();
2563 if field.is_shorthand {
2564 Some(name.to_string())
2566 let separator = struct_lit_field_separator(context.config);
2567 let overhead = name.len() + separator.len();
2568 let mut expr_shape = try_opt!(shape.sub_width(overhead));
2569 expr_shape.offset += overhead;
2570 let expr = field.expr.rewrite(context, expr_shape);
2572 let mut attrs_str = try_opt!((*field.attrs).rewrite(context, shape));
2573 if !attrs_str.is_empty() {
2574 attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2578 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2580 let expr_offset = shape.indent.block_indent(context.config);
2583 .rewrite(context, Shape::indented(expr_offset, context.config));
2589 expr_offset.to_string(&context.config),
2598 fn shape_from_fn_call_style(
2599 context: &RewriteContext,
2603 ) -> Option<Shape> {
2604 if context.use_block_indent() {
2608 .block_indent(context.config.tab_spaces())
2609 .with_max_width(context.config)
2612 shape.visual_indent(offset).sub_width(overhead)
2616 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2617 context: &RewriteContext,
2623 T: Rewrite + Spanned + ToExpr + 'a,
2625 let mut items = items.iter();
2626 // In case of length 1, need a trailing comma
2627 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2628 if items.len() == 1 {
2630 let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
2631 return items.next().unwrap().rewrite(context, nested_shape).map(
2632 |s| if context.config.spaces_within_parens() {
2633 format!("( {}, )", s)
2640 let list_lo = context.codemap.span_after(span, "(");
2641 let nested_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
2642 let items = itemize_list(
2646 |item| item.span().lo,
2647 |item| item.span().hi,
2648 |item| item.rewrite(context, nested_shape),
2650 span.hi - BytePos(1),
2652 let list_str = try_opt!(format_item_list(items, nested_shape, context.config));
2654 if context.config.spaces_within_parens() && list_str.len() > 0 {
2655 Some(format!("( {} )", list_str))
2657 Some(format!("({})", list_str))
2661 pub fn rewrite_tuple<'a, T>(
2662 context: &RewriteContext,
2668 T: Rewrite + Spanned + ToExpr + 'a,
2670 debug!("rewrite_tuple {:?}", shape);
2671 if context.use_block_indent() {
2672 // We use the same rule as funcation call for rewriting tuple.
2679 context.config.fn_call_width(),
2683 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2687 pub fn rewrite_unary_prefix<R: Rewrite>(
2688 context: &RewriteContext,
2692 ) -> Option<String> {
2694 .rewrite(context, try_opt!(shape.offset_left(prefix.len())))
2695 .map(|r| format!("{}{}", prefix, r))
2698 // FIXME: this is probably not correct for multi-line Rewrites. we should
2699 // subtract suffix.len() from the last line budget, not the first!
2700 pub fn rewrite_unary_suffix<R: Rewrite>(
2701 context: &RewriteContext,
2705 ) -> Option<String> {
2707 .rewrite(context, try_opt!(shape.sub_width(suffix.len())))
2714 fn rewrite_unary_op(
2715 context: &RewriteContext,
2719 ) -> Option<String> {
2720 // For some reason, an UnOp is not spanned like BinOp!
2721 let operator_str = match *op {
2722 ast::UnOp::Deref => "*",
2723 ast::UnOp::Not => "!",
2724 ast::UnOp::Neg => "-",
2726 rewrite_unary_prefix(context, operator_str, expr, shape)
2729 fn rewrite_assignment(
2730 context: &RewriteContext,
2733 op: Option<&ast::BinOp>,
2735 ) -> Option<String> {
2736 let operator_str = match op {
2737 Some(op) => context.snippet(op.span),
2738 None => "=".to_owned(),
2741 // 1 = space between lhs and operator.
2742 let lhs_shape = try_opt!(shape.sub_width(operator_str.len() + 1));
2743 let lhs_str = format!(
2745 try_opt!(lhs.rewrite(context, lhs_shape)),
2749 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2752 // The left hand side must contain everything up to, and including, the
2753 // assignment operator.
2754 pub fn rewrite_assign_rhs<S: Into<String>>(
2755 context: &RewriteContext,
2759 ) -> Option<String> {
2760 let mut result = lhs.into();
2761 let last_line_width = last_line_width(&result) -
2762 if result.contains('\n') {
2763 shape.indent.width()
2767 // 1 = space between operator and rhs.
2768 let orig_shape = try_opt!(shape.offset_left(last_line_width + 1));
2769 let rhs = ex.rewrite(context, orig_shape);
2771 fn count_line_breaks(src: &str) -> usize {
2772 src.chars().filter(|&x| x == '\n').count()
2776 Some(ref new_str) if count_line_breaks(new_str) < 2 => {
2778 result.push_str(new_str);
2781 // Expression did not fit on the same line as the identifier or is
2782 // at least three lines big. Try splitting the line and see
2783 // if that works better.
2784 let new_shape = try_opt!(shape.block_left(context.config.tab_spaces()));
2785 let new_rhs = ex.rewrite(context, new_shape);
2788 match (rhs, new_rhs) {
2789 (Some(ref orig_rhs), Some(ref replacement_rhs))
2790 if count_line_breaks(orig_rhs) > count_line_breaks(replacement_rhs) + 1 => {
2791 result.push_str(&format!("\n{}", new_shape.indent.to_string(context.config)));
2792 result.push_str(replacement_rhs);
2794 (None, Some(ref final_rhs)) => {
2795 result.push_str(&format!("\n{}", new_shape.indent.to_string(context.config)));
2796 result.push_str(final_rhs);
2798 (None, None) => return None,
2799 (Some(ref orig_rhs), _) => {
2801 result.push_str(orig_rhs);
2810 fn rewrite_expr_addrof(
2811 context: &RewriteContext,
2812 mutability: ast::Mutability,
2815 ) -> Option<String> {
2816 let operator_str = match mutability {
2817 ast::Mutability::Immutable => "&",
2818 ast::Mutability::Mutable => "&mut ",
2820 rewrite_unary_prefix(context, operator_str, expr, shape)
2824 fn to_expr(&self) -> Option<&ast::Expr>;
2825 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2828 impl ToExpr for ast::Expr {
2829 fn to_expr(&self) -> Option<&ast::Expr> {
2833 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2834 can_be_overflowed_expr(context, self, len)
2838 impl ToExpr for ast::Ty {
2839 fn to_expr(&self) -> Option<&ast::Expr> {
2843 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2844 can_be_overflowed_type(context, self, len)
2848 impl<'a> ToExpr for TuplePatField<'a> {
2849 fn to_expr(&self) -> Option<&ast::Expr> {
2853 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2854 can_be_overflowed_pat(context, self, len)