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;
12 use std::borrow::Borrow;
15 use rewrite::{Rewrite, RewriteContext};
16 use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic,
17 DefinitiveListTactic, definitive_tactic, ListItem, format_fn_args};
18 use string::{StringFormat, rewrite_string};
19 use utils::{span_after, extra_offset, last_line_width, wrap_str, binary_search};
20 use visitor::FmtVisitor;
21 use config::{StructLitStyle, MultilineStyle};
22 use comment::{FindUncommented, rewrite_comment, contains_comment};
23 use types::rewrite_path;
24 use items::{span_lo_for_arg, span_hi_for_arg};
25 use chains::rewrite_chain;
26 use macros::rewrite_macro;
28 use syntax::{ast, ptr};
29 use syntax::codemap::{CodeMap, Span, BytePos, mk_sp};
30 use syntax::visit::Visitor;
32 impl Rewrite for ast::Expr {
33 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
35 ast::Expr_::ExprVec(ref expr_vec) => {
36 rewrite_array(expr_vec.iter().map(|e| &**e),
42 ast::Expr_::ExprLit(ref l) => {
44 ast::Lit_::LitStr(_, ast::StrStyle::CookedStr) => {
45 rewrite_string_lit(context, l.span, width, offset)
48 wrap_str(context.snippet(self.span),
49 context.config.max_width,
55 ast::Expr_::ExprCall(ref callee, ref args) => {
56 let inner_span = mk_sp(callee.span.hi, self.span.hi);
57 rewrite_call(context, &**callee, args, inner_span, width, offset)
59 ast::Expr_::ExprParen(ref subexpr) => {
60 rewrite_paren(context, subexpr, width, offset)
62 ast::Expr_::ExprBinary(ref op, ref lhs, ref rhs) => {
63 rewrite_binary_op(context, op, lhs, rhs, width, offset)
65 ast::Expr_::ExprUnary(ref op, ref subexpr) => {
66 rewrite_unary_op(context, op, subexpr, width, offset)
68 ast::Expr_::ExprStruct(ref path, ref fields, ref base) => {
69 rewrite_struct_lit(context,
72 base.as_ref().map(|e| &**e),
77 ast::Expr_::ExprTup(ref items) => {
78 rewrite_tuple_lit(context, items, self.span, width, offset)
80 ast::Expr_::ExprWhile(ref cond, ref block, label) => {
81 Loop::new_while(None, cond, block, label).rewrite(context, width, offset)
83 ast::Expr_::ExprWhileLet(ref pat, ref cond, ref block, label) => {
84 Loop::new_while(Some(pat), cond, block, label).rewrite(context, width, offset)
86 ast::Expr_::ExprForLoop(ref pat, ref cond, ref block, label) => {
87 Loop::new_for(pat, cond, block, label).rewrite(context, width, offset)
89 ast::Expr_::ExprLoop(ref block, label) => {
90 Loop::new_loop(block, label).rewrite(context, width, offset)
92 ast::Expr_::ExprBlock(ref block) => {
93 block.rewrite(context, width, offset)
95 ast::Expr_::ExprIf(ref cond, ref if_block, ref else_block) => {
96 rewrite_if_else(context,
99 else_block.as_ref().map(|e| &**e),
105 ast::Expr_::ExprIfLet(ref pat, ref cond, ref if_block, ref else_block) => {
106 rewrite_if_else(context,
109 else_block.as_ref().map(|e| &**e),
115 ast::Expr_::ExprMatch(ref cond, ref arms, _) => {
116 rewrite_match(context, cond, arms, width, offset, self.span)
118 ast::Expr_::ExprPath(ref qself, ref path) => {
119 rewrite_path(context, qself.as_ref(), path, width, offset)
121 ast::Expr_::ExprAssign(ref lhs, ref rhs) => {
122 rewrite_assignment(context, lhs, rhs, None, width, offset)
124 ast::Expr_::ExprAssignOp(ref op, ref lhs, ref rhs) => {
125 rewrite_assignment(context, lhs, rhs, Some(op), width, offset)
127 ast::Expr_::ExprAgain(ref opt_ident) => {
128 let id_str = match *opt_ident {
129 Some(ident) => format!(" {}", ident.node),
130 None => String::new(),
132 Some(format!("continue{}", id_str))
134 ast::Expr_::ExprBreak(ref opt_ident) => {
135 let id_str = match *opt_ident {
136 Some(ident) => format!(" {}", ident.node),
137 None => String::new(),
139 Some(format!("break{}", id_str))
141 ast::Expr_::ExprClosure(capture, ref fn_decl, ref body) => {
142 rewrite_closure(capture, fn_decl, body, self.span, context, width, offset)
144 ast::Expr_::ExprField(..) |
145 ast::Expr_::ExprTupField(..) |
146 ast::Expr_::ExprMethodCall(..) => {
147 rewrite_chain(self, context, width, offset)
149 ast::Expr_::ExprMac(ref mac) => {
150 // Failure to rewrite a marco should not imply failure to
151 // rewrite the expression.
152 rewrite_macro(mac, context, width, offset).or_else(|| {
153 wrap_str(context.snippet(self.span),
154 context.config.max_width,
159 ast::Expr_::ExprRet(None) => {
160 wrap_str("return".to_owned(), context.config.max_width, width, offset)
162 ast::Expr_::ExprRet(Some(ref expr)) => {
163 rewrite_unary_prefix(context, "return ", expr, width, offset)
165 ast::Expr_::ExprBox(ref expr) => {
166 rewrite_unary_prefix(context, "box ", expr, width, offset)
168 ast::Expr_::ExprAddrOf(mutability, ref expr) => {
169 rewrite_expr_addrof(context, mutability, expr, width, offset)
171 ast::Expr_::ExprCast(ref expr, ref ty) => {
172 rewrite_pair(&**expr, &**ty, "", " as ", "", context, width, offset)
174 ast::Expr_::ExprIndex(ref expr, ref index) => {
175 rewrite_pair(&**expr, &**index, "", "[", "]", context, width, offset)
177 ast::Expr_::ExprRepeat(ref expr, ref repeats) => {
178 rewrite_pair(&**expr, &**repeats, "[", "; ", "]", context, width, offset)
180 ast::Expr_::ExprRange(Some(ref lhs), Some(ref rhs)) => {
181 rewrite_pair(&**lhs, &**rhs, "", "..", "", context, width, offset)
183 ast::Expr_::ExprRange(None, Some(ref rhs)) => {
184 rewrite_unary_prefix(context, "..", &**rhs, width, offset)
186 ast::Expr_::ExprRange(Some(ref lhs), None) => {
188 try_opt!(lhs.rewrite(context,
189 try_opt!(width.checked_sub(2)),
192 ast::Expr_::ExprRange(None, None) => {
199 // We do not format these expressions yet, but they should still
200 // satisfy our width restrictions.
201 ast::Expr_::ExprInPlace(..) |
202 ast::Expr_::ExprInlineAsm(..) => {
203 wrap_str(context.snippet(self.span),
204 context.config.max_width,
212 fn rewrite_pair<LHS, RHS>(lhs: &LHS,
217 context: &RewriteContext,
224 let max_width = try_opt!(width.checked_sub(prefix.len() + infix.len() + suffix.len()));
229 let lhs_offset = offset + prefix.len();
230 let lhs_str = match lhs.rewrite(context, lhs_budget, lhs_offset) {
231 Some(result) => result,
232 None => return Err(Ordering::Greater),
235 let last_line_width = last_line_width(&lhs_str);
236 let rhs_budget = match max_width.checked_sub(last_line_width) {
238 None => return Err(Ordering::Less),
240 let rhs_indent = offset + last_line_width + prefix.len() + infix.len();
242 let rhs_str = match rhs.rewrite(context, rhs_budget, rhs_indent) {
243 Some(result) => result,
244 None => return Err(Ordering::Less),
247 Ok(format!("{}{}{}{}{}", prefix, lhs_str, infix, rhs_str, suffix))
251 pub fn rewrite_array<'a, I>(expr_iter: I,
253 context: &RewriteContext,
257 where I: Iterator<Item = &'a ast::Expr>
260 let max_item_width = try_opt!(width.checked_sub(2));
261 let items = itemize_list(context.codemap,
267 |item| item.rewrite(context, max_item_width, offset + 1),
268 span_after(span, "[", context.codemap),
270 .collect::<Vec<_>>();
272 let has_long_item = try_opt!(items.iter()
273 .map(|li| li.item.as_ref().map(|s| s.len() > 10))
275 |acc, x| acc.and_then(|y| x.map(|x| (x || y)))));
277 let tactic = if has_long_item || items.iter().any(ListItem::is_multiline) {
278 definitive_tactic(&items, ListTactic::HorizontalVertical, max_item_width)
280 DefinitiveListTactic::Mixed
283 let fmt = ListFormatting {
286 trailing_separator: SeparatorTactic::Never,
288 width: max_item_width,
289 ends_with_newline: false,
290 config: context.config,
292 let list_str = try_opt!(write_list(&items, &fmt));
294 Some(format!("[{}]", list_str))
297 // This functions is pretty messy because of the wrapping and unwrapping of
298 // expressions into and from blocks. See rust issue #27872.
299 fn rewrite_closure(capture: ast::CaptureClause,
300 fn_decl: &ast::FnDecl,
303 context: &RewriteContext,
307 let mover = if capture == ast::CaptureClause::CaptureByValue {
312 let offset = offset + mover.len();
314 // 4 = "|| {".len(), which is overconservative when the closure consists of
315 // a single expression.
316 let budget = try_opt!(width.checked_sub(4 + mover.len()));
318 let argument_offset = offset + 1;
319 let ret_str = try_opt!(fn_decl.output.rewrite(context, budget, argument_offset));
320 // 1 = space between arguments and return type.
321 let horizontal_budget = budget.checked_sub(ret_str.len() + 1).unwrap_or(0);
323 let arg_items = itemize_list(context.codemap,
324 fn_decl.inputs.iter(),
326 |arg| span_lo_for_arg(arg),
327 |arg| span_hi_for_arg(arg),
328 |arg| arg.rewrite(context, budget, argument_offset),
329 span_after(span, "|", context.codemap),
331 let item_vec = arg_items.collect::<Vec<_>>();
332 let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
333 let budget = match tactic {
334 DefinitiveListTactic::Horizontal => horizontal_budget,
338 let fmt = ListFormatting {
341 trailing_separator: SeparatorTactic::Never,
342 indent: argument_offset,
344 ends_with_newline: false,
345 config: context.config,
347 let list_str = try_opt!(write_list(&item_vec, &fmt));
348 let mut prefix = format!("{}|{}|", mover, list_str);
350 if !ret_str.is_empty() {
351 if prefix.contains('\n') {
353 prefix.push_str(&argument_offset.to_string(context.config));
357 prefix.push_str(&ret_str);
360 // Try to format closure body as a single line expression without braces.
361 if is_simple_block(body, context.codemap) && !prefix.contains('\n') {
362 let (spacer, closer) = if ret_str.is_empty() {
367 let expr = body.expr.as_ref().unwrap();
368 // All closure bodies are blocks in the eyes of the AST, but we may not
369 // want to unwrap them when they only contain a single expression.
370 let inner_expr = match expr.node {
371 ast::Expr_::ExprBlock(ref inner) if inner.stmts.is_empty() && inner.expr.is_some() &&
373 ast::BlockCheckMode::DefaultBlock => {
374 inner.expr.as_ref().unwrap()
378 let extra_offset = extra_offset(&prefix, offset) + spacer.len();
379 let budget = try_opt!(width.checked_sub(extra_offset + closer.len()));
380 let rewrite = inner_expr.rewrite(context, budget, offset + extra_offset);
382 // Checks if rewrite succeeded and fits on a single line.
383 let accept_rewrite = rewrite.as_ref().map(|result| !result.contains('\n')).unwrap_or(false);
386 return Some(format!("{}{}{}{}", prefix, spacer, rewrite.unwrap(), closer));
390 // We couldn't format the closure body as a single line expression; fall
391 // back to block formatting.
392 let body_rewrite = body.expr
394 .and_then(|body_expr| {
395 if let ast::Expr_::ExprBlock(ref inner) = body_expr.node {
396 Some(inner.rewrite(&context, 2, Indent::empty()))
401 .unwrap_or_else(|| body.rewrite(&context, 2, Indent::empty()));
403 Some(format!("{} {}", prefix, try_opt!(body_rewrite)))
406 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
407 block_str.map(|block_str| {
408 if block_str.starts_with("{") && budget >= 2 &&
409 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2) {
417 impl Rewrite for ast::Block {
418 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
419 let user_str = context.snippet(self.span);
420 if user_str == "{}" && width >= 2 {
421 return Some(user_str);
424 let mut visitor = FmtVisitor::from_codemap(context.codemap, context.config);
425 visitor.block_indent = context.block_indent + context.overflow_indent;
427 let prefix = match self.rules {
428 ast::BlockCheckMode::PushUnsafeBlock(..) |
429 ast::BlockCheckMode::UnsafeBlock(..) => {
430 let snippet = context.snippet(self.span);
431 let open_pos = try_opt!(snippet.find_uncommented("{"));
432 visitor.last_pos = self.span.lo + BytePos(open_pos as u32);
434 // Extract comment between unsafe and block start.
435 let trimmed = &snippet[6..open_pos].trim();
437 let prefix = if !trimmed.is_empty() {
438 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
439 let budget = try_opt!(width.checked_sub(9));
440 format!("unsafe {} ",
441 try_opt!(rewrite_comment(trimmed,
450 if is_simple_block(self, context.codemap) && prefix.len() < width {
454 .rewrite(context, width - prefix.len(), offset);
455 if let Some(ref expr_str) = body {
456 let result = format!("{}{{ {} }}", prefix, expr_str);
457 if result.len() <= width && !result.contains('\n') {
465 ast::BlockCheckMode::PopUnsafeBlock(..) |
466 ast::BlockCheckMode::DefaultBlock => {
467 visitor.last_pos = self.span.lo;
473 visitor.visit_block(self);
475 // Push text between last block item and end of block
476 let snippet = visitor.snippet(mk_sp(visitor.last_pos, self.span.hi));
477 visitor.buffer.push_str(&snippet);
479 Some(format!("{}{}", prefix, visitor.buffer))
483 // FIXME(#18): implement pattern formatting
484 impl Rewrite for ast::Pat {
485 fn rewrite(&self, context: &RewriteContext, _: usize, _: Indent) -> Option<String> {
486 Some(context.snippet(self.span))
490 // Abstraction over for, while and loop expressions
492 cond: Option<&'a ast::Expr>,
493 block: &'a ast::Block,
494 label: Option<ast::Ident>,
495 pat: Option<&'a ast::Pat>,
502 fn new_loop(block: &'a ast::Block, label: Option<ast::Ident>) -> Loop<'a> {
514 fn new_while(pat: Option<&'a ast::Pat>,
516 block: &'a ast::Block,
517 label: Option<ast::Ident>)
533 fn new_for(pat: &'a ast::Pat,
535 block: &'a ast::Block,
536 label: Option<ast::Ident>)
550 impl<'a> Rewrite for Loop<'a> {
551 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
552 let label_string = rewrite_label(self.label);
554 let inner_width = try_opt!(width.checked_sub(self.keyword.len() + 2 + label_string.len()));
555 let inner_offset = offset + self.keyword.len() + label_string.len();
557 let pat_expr_string = match self.cond {
558 Some(cond) => try_opt!(rewrite_pat_expr(context,
565 None => String::new(),
568 // FIXME: this drops any comment between "loop" and the block.
570 .rewrite(context, width, offset)
581 fn rewrite_label(label: Option<ast::Ident>) -> String {
583 Some(ident) => format!("{}: ", ident),
584 None => "".to_owned(),
588 // Rewrites if-else blocks. If let Some(_) = pat, the expression is
589 // treated as an if-let-else expression.
590 fn rewrite_if_else(context: &RewriteContext,
592 if_block: &ast::Block,
593 else_block_opt: Option<&ast::Expr>,
594 pat: Option<&ast::Pat>,
597 allow_single_line: bool)
599 // 3 = "if ", 2 = " {"
600 let pat_expr_string = try_opt!(rewrite_pat_expr(context,
605 try_opt!(width.checked_sub(3 + 2)),
608 // Try to format if-else on single line.
609 if allow_single_line && context.config.single_line_if_else {
610 let trial = single_line_if_else(context, &pat_expr_string, if_block, else_block_opt, width);
617 let if_block_string = try_opt!(if_block.rewrite(context, width, offset));
618 let mut result = format!("if {} {}", pat_expr_string, if_block_string);
620 if let Some(else_block) = else_block_opt {
621 let rewrite = match else_block.node {
622 // If the else expression is another if-else expression, prevent it
623 // from being formatted on a single line.
624 ast::Expr_::ExprIfLet(ref pat, ref cond, ref if_block, ref else_block) => {
625 rewrite_if_else(context,
628 else_block.as_ref().map(|e| &**e),
634 ast::Expr_::ExprIf(ref cond, ref if_block, ref else_block) => {
635 rewrite_if_else(context,
638 else_block.as_ref().map(|e| &**e),
644 _ => else_block.rewrite(context, width, offset),
647 result.push_str(" else ");
648 result.push_str(&&try_opt!(rewrite));
654 fn single_line_if_else(context: &RewriteContext,
656 if_node: &ast::Block,
657 else_block_opt: Option<&ast::Expr>,
660 let else_block = try_opt!(else_block_opt);
661 let fixed_cost = "if { } else { }".len();
663 if let ast::ExprBlock(ref else_node) = else_block.node {
664 if !is_simple_block(if_node, context.codemap) ||
665 !is_simple_block(else_node, context.codemap) || pat_expr_str.contains('\n') {
669 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
670 let if_expr = if_node.expr.as_ref().unwrap();
671 let if_str = try_opt!(if_expr.rewrite(context, new_width, Indent::empty()));
673 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
674 let else_expr = else_node.expr.as_ref().unwrap();
675 let else_str = try_opt!(else_expr.rewrite(context, new_width, Indent::empty()));
677 // FIXME: this check shouldn't be necessary. Rewrites should either fail
678 // or wrap to a newline when the object does not fit the width.
679 let fits_line = fixed_cost + pat_expr_str.len() + if_str.len() + else_str.len() <= width;
681 if fits_line && !if_str.contains('\n') && !else_str.contains('\n') {
682 return Some(format!("if {} {{ {} }} else {{ {} }}",
692 // Checks that a block contains no statements, an expression and no comments.
693 fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
694 if !block.stmts.is_empty() || block.expr.is_none() {
698 let snippet = codemap.span_to_snippet(block.span).unwrap();
700 !contains_comment(&snippet)
703 // inter-match-arm-comment-rules:
704 // - all comments following a match arm before the start of the next arm
705 // are about the second arm
706 fn rewrite_match_arm_comment(context: &RewriteContext,
710 arm_indent_str: &str)
712 // The leading "," is not part of the arm-comment
713 let missed_str = match missed_str.find_uncommented(",") {
714 Some(n) => &missed_str[n + 1..],
715 None => &missed_str[..],
718 let mut result = String::new();
719 // any text not preceeded by a newline is pushed unmodified to the block
720 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
721 result.push_str(&missed_str[..first_brk]);
722 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
724 let first = missed_str.find(|c: char| !c.is_whitespace()).unwrap_or(missed_str.len());
725 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
726 // Excessive vertical whitespace before comment should be preserved
727 // TODO handle vertical whitespace better
730 let missed_str = missed_str[first..].trim();
731 if !missed_str.is_empty() {
732 let comment = try_opt!(rewrite_comment(&missed_str,
738 result.push_str(arm_indent_str);
739 result.push_str(&comment);
745 fn rewrite_match(context: &RewriteContext,
757 let cond_budget = try_opt!(width.checked_sub(8));
758 let cond_str = try_opt!(cond.rewrite(context, cond_budget, offset + 6));
759 let mut result = format!("match {} {{", cond_str);
761 let nested_context = context.nested_context();
762 let arm_indent = nested_context.block_indent + context.overflow_indent;
763 let arm_indent_str = arm_indent.to_string(context.config);
765 let open_brace_pos = span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])),
769 for (i, arm) in arms.iter().enumerate() {
770 // Make sure we get the stuff between arms.
771 let missed_str = if i == 0 {
772 context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
774 context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
776 let comment = try_opt!(rewrite_match_arm_comment(context,
781 result.push_str(&comment);
783 result.push_str(&arm_indent_str);
785 let arm_str = arm.rewrite(&nested_context,
786 context.config.max_width - arm_indent.width(),
788 if let Some(ref arm_str) = arm_str {
789 result.push_str(arm_str);
791 // We couldn't format the arm, just reproduce the source.
792 let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
793 result.push_str(&snippet);
796 // BytePos(1) = closing match brace.
797 let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
798 let last_comment = context.snippet(last_span);
799 let comment = try_opt!(rewrite_match_arm_comment(context,
804 result.push_str(&comment);
806 result.push_str(&(context.block_indent + context.overflow_indent).to_string(context.config));
811 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
812 let &ast::Arm { ref attrs, ref pats, .. } = arm;
813 if !attrs.is_empty() {
814 return attrs[0].span.lo
820 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
825 impl Rewrite for ast::Arm {
826 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
827 let &ast::Arm { ref attrs, ref pats, ref guard, ref body } = self;
828 let indent_str = offset.to_string(context.config);
830 // FIXME this is all a bit grotty, would be nice to abstract out the
831 // treatment of attributes.
832 let attr_str = if !attrs.is_empty() {
833 // We only use this visitor for the attributes, should we use it for
835 let mut attr_visitor = FmtVisitor::from_codemap(context.codemap, context.config);
836 attr_visitor.block_indent = context.block_indent;
837 attr_visitor.last_pos = attrs[0].span.lo;
838 if attr_visitor.visit_attrs(attrs) {
839 // Attributes included a skip instruction.
840 let snippet = context.snippet(mk_sp(attrs[0].span.lo, body.span.hi));
841 return Some(snippet);
843 attr_visitor.format_missing(pats[0].span.lo);
844 attr_visitor.buffer.to_string()
851 let pat_budget = try_opt!(width.checked_sub(5));
852 let pat_strs = try_opt!(pats.iter()
856 offset.block_indent(context.config))
858 .collect::<Option<Vec<_>>>());
860 let mut total_width = pat_strs.iter().fold(0, |a, p| a + p.len());
862 total_width += (pat_strs.len() - 1) * 3;
864 let mut vertical = total_width > pat_budget || pat_strs.iter().any(|p| p.contains('\n'));
865 if !vertical && context.config.take_source_hints {
866 // If the patterns were previously stacked, keep them stacked.
867 let pat_span = mk_sp(pats[0].span.lo, pats[pats.len() - 1].span.hi);
868 let pat_str = context.snippet(pat_span);
869 vertical = pat_str.find('\n').is_some();
872 let pats_width = if vertical {
873 pat_strs[pat_strs.len() - 1].len()
878 let mut pats_str = String::new();
880 if !pats_str.is_empty() {
882 pats_str.push_str(" |\n");
883 pats_str.push_str(&indent_str);
885 pats_str.push_str(" | ");
888 pats_str.push_str(&p);
891 let guard_str = try_opt!(rewrite_guard(context, guard, width, offset, pats_width));
893 let pats_str = format!("{}{}", pats_str, guard_str);
894 // Where the next text can start.
895 let mut line_start = last_line_width(&pats_str);
896 if !pats_str.contains('\n') {
897 line_start += offset.width();
900 let comma = if let ast::ExprBlock(_) = body.node {
906 // Let's try and get the arm body on the same line as the condition.
908 let same_line_body = if context.config.max_width > line_start + comma.len() + 4 {
909 let budget = context.config.max_width - line_start - comma.len() - 4;
910 let offset = Indent::new(offset.block_indent, line_start + 4 - offset.block_indent);
911 let rewrite = nop_block_collapse(body.rewrite(context, budget, offset), budget);
914 Some(ref body_str) if body_str.len() <= budget || comma.is_empty() =>
915 return Some(format!("{}{} => {}{}",
916 attr_str.trim_left(),
926 if let ast::ExprBlock(_) = body.node {
927 // We're trying to fit a block in, but it still failed, give up.
931 let body_budget = try_opt!(width.checked_sub(context.config.tab_spaces));
932 let next_line_body = nop_block_collapse(body.rewrite(context,
935 .block_indent(context.config)),
938 let body_str = try_opt!(match_arm_heuristic(same_line_body.as_ref().map(|x| &x[..]),
939 next_line_body.as_ref().map(|x| &x[..])));
941 let spacer = match same_line_body {
942 Some(ref body) if body == body_str => " ".to_owned(),
944 offset.block_indent(context.config).to_string(context.config)),
947 Some(format!("{}{} =>{}{},",
948 attr_str.trim_left(),
955 // Takes two possible rewrites for the match arm body and chooses the "nicest".
956 fn match_arm_heuristic<'a>(former: Option<&'a str>, latter: Option<&'a str>) -> Option<&'a str> {
957 match (former, latter) {
958 (f @ Some(..), None) => f,
959 (Some(f), Some(l)) if f.chars().filter(|&c| c == '\n').count() <=
960 l.chars().filter(|&c| c == '\n').count() => {
967 // The `if ...` guard on a match arm.
968 fn rewrite_guard(context: &RewriteContext,
969 guard: &Option<ptr::P<ast::Expr>>,
972 // The amount of space used up on this line for the pattern in
973 // the arm (excludes offset).
974 pattern_width: usize)
976 if let &Some(ref guard) = guard {
977 // First try to fit the guard string on the same line as the pattern.
978 // 4 = ` if `, 5 = ` => {`
979 let overhead = pattern_width + 4 + 5;
980 if overhead < width {
981 let cond_str = guard.rewrite(context, width - overhead, offset + pattern_width + 4);
982 if let Some(cond_str) = cond_str {
983 return Some(format!(" if {}", cond_str));
987 // Not enough space to put the guard after the pattern, try a newline.
988 let overhead = context.config.tab_spaces + 4 + 5;
989 if overhead < width {
990 let cond_str = guard.rewrite(context,
992 offset.block_indent(context.config));
993 if let Some(cond_str) = cond_str {
994 return Some(format!("\n{}if {}",
995 offset.block_indent(context.config).to_string(context.config),
1006 fn rewrite_pat_expr(context: &RewriteContext,
1007 pat: Option<&ast::Pat>,
1010 // Connecting piece between pattern and expression,
1011 // *without* trailing space.
1016 let pat_offset = offset + matcher.len();
1017 let mut result = match pat {
1019 let pat_budget = try_opt!(width.checked_sub(connector.len() + matcher.len()));
1020 let pat_string = try_opt!(pat.rewrite(context, pat_budget, pat_offset));
1021 format!("{}{}{}", matcher, pat_string, connector)
1023 None => String::new(),
1026 // Consider only the last line of the pat string.
1027 let extra_offset = extra_offset(&result, offset);
1029 // The expression may (partionally) fit on the current line.
1030 if width > extra_offset + 1 {
1031 let spacer = if pat.is_some() {
1037 let expr_rewrite = expr.rewrite(context,
1038 width - extra_offset - spacer.len(),
1039 offset + extra_offset + spacer.len());
1041 if let Some(expr_string) = expr_rewrite {
1042 result.push_str(spacer);
1043 result.push_str(&expr_string);
1044 return Some(result);
1048 // The expression won't fit on the current line, jump to next.
1050 result.push_str(&pat_offset.to_string(context.config));
1052 let expr_rewrite = expr.rewrite(context,
1053 context.config.max_width - pat_offset.width(),
1055 result.push_str(&&try_opt!(expr_rewrite));
1060 fn rewrite_string_lit(context: &RewriteContext,
1065 if !context.config.format_strings {
1066 return Some(context.snippet(span));
1069 let fmt = StringFormat {
1077 config: context.config,
1080 let string_lit = context.snippet(span);
1081 let str_lit = &string_lit[1..string_lit.len() - 1]; // Remove the quote characters.
1083 rewrite_string(str_lit, &fmt)
1086 pub fn rewrite_call<R>(context: &RewriteContext,
1088 args: &[ptr::P<ast::Expr>],
1095 let closure = |callee_max_width| {
1096 rewrite_call_inner(context, callee, callee_max_width, args, span, width, offset)
1100 let max_width = try_opt!(width.checked_sub(2));
1101 binary_search(1, max_width, closure)
1104 fn rewrite_call_inner<R>(context: &RewriteContext,
1106 max_callee_width: usize,
1107 args: &[ptr::P<ast::Expr>],
1111 -> Result<String, Ordering>
1114 let callee = callee.borrow();
1115 // FIXME using byte lens instead of char lens (and probably all over the
1117 let callee_str = match callee.rewrite(context, max_callee_width, offset) {
1119 if !string.contains('\n') && string.len() > max_callee_width {
1120 panic!("{:?} {}", string, max_callee_width);
1125 None => return Err(Ordering::Greater),
1128 let span_lo = span_after(span, "(", context.codemap);
1129 let span = mk_sp(span_lo, span.hi);
1131 let extra_offset = extra_offset(&callee_str, offset);
1133 let remaining_width = match width.checked_sub(extra_offset + 2) {
1135 None => return Err(Ordering::Greater),
1137 let offset = offset + extra_offset + 1;
1138 let block_indent = if args.len() == 1 {
1139 context.block_indent
1143 let inner_context = &RewriteContext { block_indent: block_indent, ..*context };
1145 let items = itemize_list(context.codemap,
1148 |item| item.span.lo,
1149 |item| item.span.hi,
1150 |item| item.rewrite(&inner_context, remaining_width, offset),
1154 let list_str = match format_fn_args(items, remaining_width, offset, context.config) {
1156 None => return Err(Ordering::Less),
1159 Ok(format!("{}({})", callee_str, list_str))
1162 fn rewrite_paren(context: &RewriteContext,
1163 subexpr: &ast::Expr,
1167 debug!("rewrite_paren, width: {}, offset: {:?}", width, offset);
1168 // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
1169 // paren on the same line as the subexpr.
1170 let subexpr_str = subexpr.rewrite(context, try_opt!(width.checked_sub(2)), offset + 1);
1171 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1172 subexpr_str.map(|s| format!("({})", s))
1175 fn rewrite_struct_lit<'a>(context: &RewriteContext,
1177 fields: &'a [ast::Field],
1178 base: Option<&'a ast::Expr>,
1183 debug!("rewrite_struct_lit: width {}, offset {:?}", width, offset);
1184 assert!(!fields.is_empty() || base.is_some());
1186 enum StructLitField<'a> {
1187 Regular(&'a ast::Field),
1188 Base(&'a ast::Expr),
1192 let path_budget = try_opt!(width.checked_sub(2));
1193 let path_str = try_opt!(path.rewrite(context, path_budget, offset));
1195 // Foo { a: Foo } - indent is +3, width is -5.
1196 let h_budget = width.checked_sub(path_str.len() + 5).unwrap_or(0);
1197 let (indent, v_budget) = match context.config.struct_lit_style {
1198 StructLitStyle::Visual => {
1199 (offset + path_str.len() + 3, h_budget)
1201 StructLitStyle::Block => {
1202 // If we are all on one line, then we'll ignore the indent, and we
1203 // have a smaller budget.
1204 let indent = context.block_indent.block_indent(context.config);
1205 let v_budget = context.config.max_width.checked_sub(indent.width()).unwrap_or(0);
1210 let field_iter = fields.into_iter()
1211 .map(StructLitField::Regular)
1212 .chain(base.into_iter().map(StructLitField::Base));
1214 let inner_context = &RewriteContext { block_indent: indent, ..*context };
1216 let items = itemize_list(context.codemap,
1221 StructLitField::Regular(ref field) => field.span.lo,
1222 StructLitField::Base(ref expr) => {
1223 let last_field_hi = fields.last().map_or(span.lo,
1227 let snippet = context.snippet(mk_sp(last_field_hi,
1229 let pos = snippet.find_uncommented("..").unwrap();
1230 last_field_hi + BytePos(pos as u32)
1236 StructLitField::Regular(ref field) => field.span.hi,
1237 StructLitField::Base(ref expr) => expr.span.hi,
1242 StructLitField::Regular(ref field) => {
1243 rewrite_field(inner_context, &field, v_budget, indent)
1245 StructLitField::Base(ref expr) => {
1247 expr.rewrite(inner_context,
1248 try_opt!(v_budget.checked_sub(2)),
1250 .map(|s| format!("..{}", s))
1254 span_after(span, "{", context.codemap),
1256 let item_vec = items.collect::<Vec<_>>();
1259 let mut prelim_tactic = match (context.config.struct_lit_style, fields.len()) {
1260 (StructLitStyle::Visual, 1) => ListTactic::HorizontalVertical,
1261 _ => context.config.struct_lit_multiline_style.to_list_tactic(),
1264 if prelim_tactic == ListTactic::HorizontalVertical && fields.len() > 1 {
1265 prelim_tactic = ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width);
1268 definitive_tactic(&item_vec, prelim_tactic, h_budget)
1271 let budget = match tactic {
1272 DefinitiveListTactic::Horizontal => h_budget,
1276 let fmt = ListFormatting {
1279 trailing_separator: if base.is_some() {
1280 SeparatorTactic::Never
1282 context.config.struct_lit_trailing_comma
1286 ends_with_newline: false,
1287 config: context.config,
1289 let fields_str = try_opt!(write_list(&item_vec, &fmt));
1291 let format_on_newline = || {
1292 let inner_indent = context.block_indent
1293 .block_indent(context.config)
1294 .to_string(context.config);
1295 let outer_indent = context.block_indent.to_string(context.config);
1296 Some(format!("{} {{\n{}{}\n{}}}",
1303 match (context.config.struct_lit_style,
1304 context.config.struct_lit_multiline_style) {
1305 (StructLitStyle::Block, _) if fields_str.contains('\n') || fields_str.len() > h_budget =>
1306 format_on_newline(),
1307 (StructLitStyle::Block, MultilineStyle::ForceMulti) => format_on_newline(),
1308 _ => Some(format!("{} {{ {} }}", path_str, fields_str)),
1311 // FIXME if context.config.struct_lit_style == Visual, but we run out
1312 // of space, we should fall back to BlockIndent.
1315 fn rewrite_field(context: &RewriteContext,
1320 let name = &field.ident.node.to_string();
1321 let overhead = name.len() + 2;
1322 let expr = field.expr.rewrite(context,
1323 try_opt!(width.checked_sub(overhead)),
1325 expr.map(|s| format!("{}: {}", name, s))
1328 fn rewrite_tuple_lit(context: &RewriteContext,
1329 items: &[ptr::P<ast::Expr>],
1334 debug!("rewrite_tuple_lit: width: {}, offset: {:?}", width, offset);
1335 let indent = offset + 1;
1336 // In case of length 1, need a trailing comma
1337 if items.len() == 1 {
1339 let budget = try_opt!(width.checked_sub(3));
1340 return items[0].rewrite(context, budget, indent).map(|s| format!("({},)", s));
1343 let items = itemize_list(context.codemap,
1346 |item| item.span.lo,
1347 |item| item.span.hi,
1349 let inner_width = context.config.max_width - indent.width() - 1;
1350 item.rewrite(context, inner_width, indent)
1352 span.lo + BytePos(1), // Remove parens
1353 span.hi - BytePos(1));
1354 let budget = try_opt!(width.checked_sub(2));
1355 let list_str = try_opt!(format_fn_args(items, budget, indent, context.config));
1357 Some(format!("({})", list_str))
1360 fn rewrite_binary_op(context: &RewriteContext,
1367 // FIXME: format comments between operands and operator
1369 let operator_str = context.snippet(op.span);
1371 // Get "full width" rhs and see if it fits on the current line. This
1372 // usually works fairly well since it tends to place operands of
1373 // operations with high precendence close together.
1374 let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
1376 // Second condition is needed in case of line break not caused by a
1377 // shortage of space, but by end-of-line comments, for example.
1378 // Note that this is non-conservative, but its just to see if it's even
1379 // worth trying to put everything on one line.
1380 if rhs_result.len() + 2 + operator_str.len() < width && !rhs_result.contains('\n') {
1381 // 1 = space between lhs expr and operator
1382 if let Some(mut result) = lhs.rewrite(context, width - 1 - operator_str.len(), offset) {
1384 result.push_str(&operator_str);
1387 let remaining_width = width.checked_sub(last_line_width(&result)).unwrap_or(0);
1389 if rhs_result.len() <= remaining_width {
1390 result.push_str(&rhs_result);
1391 return Some(result);
1394 if let Some(rhs_result) = rhs.rewrite(context, remaining_width, offset + result.len()) {
1395 if rhs_result.len() <= remaining_width {
1396 result.push_str(&rhs_result);
1397 return Some(result);
1403 // We have to use multiple lines.
1405 // Re-evaluate the lhs because we have more space now:
1406 let budget = try_opt!(context.config
1408 .checked_sub(offset.width() + 1 + operator_str.len()));
1409 Some(format!("{} {}\n{}{}",
1410 try_opt!(lhs.rewrite(context, budget, offset)),
1412 offset.to_string(context.config),
1416 fn rewrite_unary_prefix(context: &RewriteContext,
1422 expr.rewrite(context,
1423 try_opt!(width.checked_sub(prefix.len())),
1424 offset + prefix.len())
1425 .map(|r| format!("{}{}", prefix, r))
1428 fn rewrite_unary_op(context: &RewriteContext,
1434 // For some reason, an UnOp is not spanned like BinOp!
1435 let operator_str = match *op {
1436 ast::UnOp::UnDeref => "*",
1437 ast::UnOp::UnNot => "!",
1438 ast::UnOp::UnNeg => "-",
1440 rewrite_unary_prefix(context, operator_str, expr, width, offset)
1443 fn rewrite_assignment(context: &RewriteContext,
1446 op: Option<&ast::BinOp>,
1450 let operator_str = match op {
1451 Some(op) => context.snippet(op.span),
1452 None => "=".to_owned(),
1455 // 1 = space between lhs and operator.
1456 let max_width = try_opt!(width.checked_sub(operator_str.len() + 1));
1457 let lhs_str = format!("{} {}",
1458 try_opt!(lhs.rewrite(context, max_width, offset)),
1461 rewrite_assign_rhs(&context, lhs_str, rhs, width, offset)
1464 // The left hand side must contain everything up to, and including, the
1465 // assignment operator.
1466 pub fn rewrite_assign_rhs<S: Into<String>>(context: &RewriteContext,
1472 let mut result = lhs.into();
1474 // 1 = space between operator and rhs.
1475 let max_width = try_opt!(width.checked_sub(result.len() + 1));
1476 let rhs = ex.rewrite(&context, max_width, offset + result.len() + 1);
1481 result.push_str(&new_str)
1484 // Expression did not fit on the same line as the identifier. Retry
1485 // on the next line.
1486 let new_offset = offset.block_indent(context.config);
1487 result.push_str(&format!("\n{}", new_offset.to_string(context.config)));
1489 // FIXME: we probably should related max_width to width instead of config.max_width
1490 // where is the 1 coming from anyway?
1491 let max_width = try_opt!(context.config.max_width.checked_sub(new_offset.width() + 1));
1492 let rhs_indent = Indent::new(context.config.tab_spaces, 0);
1493 let overflow_context = context.overflow_context(rhs_indent);
1494 let rhs = ex.rewrite(&overflow_context, max_width, new_offset);
1496 result.push_str(&&try_opt!(rhs));
1503 fn rewrite_expr_addrof(context: &RewriteContext,
1504 mutability: ast::Mutability,
1509 let operator_str = match mutability {
1510 ast::Mutability::MutImmutable => "&",
1511 ast::Mutability::MutMutable => "&mut ",
1513 rewrite_unary_prefix(context, operator_str, expr, width, offset)