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;
16 use rewrite::{Rewrite, RewriteContext};
17 use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic,
18 DefinitiveListTactic, definitive_tactic, ListItem, format_fn_args};
19 use string::{StringFormat, rewrite_string};
20 use utils::{span_after, extra_offset, last_line_width, wrap_str, binary_search, first_line_width};
21 use visitor::FmtVisitor;
22 use config::{StructLitStyle, MultilineStyle};
23 use comment::{FindUncommented, rewrite_comment, contains_comment};
24 use types::rewrite_path;
25 use items::{span_lo_for_arg, span_hi_for_arg};
26 use chains::rewrite_chain;
27 use macros::rewrite_macro;
29 use syntax::{ast, ptr};
30 use syntax::codemap::{CodeMap, Span, BytePos, mk_sp};
31 use syntax::visit::Visitor;
33 impl Rewrite for ast::Expr {
34 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
36 ast::Expr_::ExprVec(ref expr_vec) => {
37 rewrite_array(expr_vec.iter().map(|e| &**e),
38 mk_sp(span_after(self.span, "[", context.codemap), self.span.hi),
43 ast::Expr_::ExprLit(ref l) => {
45 ast::Lit_::LitStr(_, ast::StrStyle::CookedStr) => {
46 rewrite_string_lit(context, l.span, width, offset)
49 wrap_str(context.snippet(self.span),
50 context.config.max_width,
56 ast::Expr_::ExprCall(ref callee, ref args) => {
57 let inner_span = mk_sp(callee.span.hi, self.span.hi);
58 rewrite_call(context, &**callee, args, inner_span, width, offset)
60 ast::Expr_::ExprParen(ref subexpr) => {
61 rewrite_paren(context, subexpr, width, offset)
63 ast::Expr_::ExprBinary(ref op, ref lhs, ref rhs) => {
64 rewrite_binary_op(context, op, lhs, rhs, width, offset)
66 ast::Expr_::ExprUnary(ref op, ref subexpr) => {
67 rewrite_unary_op(context, op, subexpr, width, offset)
69 ast::Expr_::ExprStruct(ref path, ref fields, ref base) => {
70 rewrite_struct_lit(context,
73 base.as_ref().map(|e| &**e),
78 ast::Expr_::ExprTup(ref items) => {
79 rewrite_tuple_lit(context, items, self.span, width, offset)
81 ast::Expr_::ExprWhile(ref cond, ref block, label) => {
82 Loop::new_while(None, cond, block, label).rewrite(context, width, offset)
84 ast::Expr_::ExprWhileLet(ref pat, ref cond, ref block, label) => {
85 Loop::new_while(Some(pat), cond, block, label).rewrite(context, width, offset)
87 ast::Expr_::ExprForLoop(ref pat, ref cond, ref block, label) => {
88 Loop::new_for(pat, cond, block, label).rewrite(context, width, offset)
90 ast::Expr_::ExprLoop(ref block, label) => {
91 Loop::new_loop(block, label).rewrite(context, width, offset)
93 ast::Expr_::ExprBlock(ref block) => {
94 block.rewrite(context, width, offset)
96 ast::Expr_::ExprIf(ref cond, ref if_block, ref else_block) => {
97 rewrite_if_else(context,
100 else_block.as_ref().map(|e| &**e),
106 ast::Expr_::ExprIfLet(ref pat, ref cond, ref if_block, ref else_block) => {
107 rewrite_if_else(context,
110 else_block.as_ref().map(|e| &**e),
116 ast::Expr_::ExprMatch(ref cond, ref arms) => {
117 rewrite_match(context, cond, arms, width, offset, self.span)
119 ast::Expr_::ExprPath(ref qself, ref path) => {
120 rewrite_path(context, qself.as_ref(), path, width, offset)
122 ast::Expr_::ExprAssign(ref lhs, ref rhs) => {
123 rewrite_assignment(context, lhs, rhs, None, width, offset)
125 ast::Expr_::ExprAssignOp(ref op, ref lhs, ref rhs) => {
126 rewrite_assignment(context, lhs, rhs, Some(op), width, offset)
128 ast::Expr_::ExprAgain(ref opt_ident) => {
129 let id_str = match *opt_ident {
130 Some(ident) => format!(" {}", ident.node),
131 None => String::new(),
133 Some(format!("continue{}", id_str))
135 ast::Expr_::ExprBreak(ref opt_ident) => {
136 let id_str = match *opt_ident {
137 Some(ident) => format!(" {}", ident.node),
138 None => String::new(),
140 Some(format!("break{}", id_str))
142 ast::Expr_::ExprClosure(capture, ref fn_decl, ref body) => {
143 rewrite_closure(capture, fn_decl, body, self.span, context, width, offset)
145 ast::Expr_::ExprField(..) |
146 ast::Expr_::ExprTupField(..) |
147 ast::Expr_::ExprMethodCall(..) => {
148 rewrite_chain(self, context, width, offset)
150 ast::Expr_::ExprMac(ref mac) => {
151 // Failure to rewrite a marco should not imply failure to
152 // rewrite the expression.
153 rewrite_macro(mac, context, width, offset).or_else(|| {
154 wrap_str(context.snippet(self.span),
155 context.config.max_width,
160 ast::Expr_::ExprRet(None) => {
161 wrap_str("return".to_owned(), context.config.max_width, width, offset)
163 ast::Expr_::ExprRet(Some(ref expr)) => {
164 rewrite_unary_prefix(context, "return ", &**expr, width, offset)
166 ast::Expr_::ExprBox(ref expr) => {
167 rewrite_unary_prefix(context, "box ", &**expr, width, offset)
169 ast::Expr_::ExprAddrOf(mutability, ref expr) => {
170 rewrite_expr_addrof(context, mutability, expr, width, offset)
172 ast::Expr_::ExprCast(ref expr, ref ty) => {
173 rewrite_pair(&**expr, &**ty, "", " as ", "", context, width, offset)
175 ast::Expr_::ExprIndex(ref expr, ref index) => {
176 rewrite_pair(&**expr, &**index, "", "[", "]", context, width, offset)
178 ast::Expr_::ExprRepeat(ref expr, ref repeats) => {
179 rewrite_pair(&**expr, &**repeats, "[", "; ", "]", context, width, offset)
181 ast::Expr_::ExprRange(Some(ref lhs), Some(ref rhs)) => {
182 rewrite_pair(&**lhs, &**rhs, "", "..", "", context, width, offset)
184 ast::Expr_::ExprRange(None, Some(ref rhs)) => {
185 rewrite_unary_prefix(context, "..", &**rhs, width, offset)
187 ast::Expr_::ExprRange(Some(ref lhs), None) => {
189 try_opt!(lhs.rewrite(context,
190 try_opt!(width.checked_sub(2)),
193 ast::Expr_::ExprRange(None, None) => {
200 // We do not format these expressions yet, but they should still
201 // satisfy our width restrictions.
202 ast::Expr_::ExprInPlace(..) |
203 ast::Expr_::ExprInlineAsm(..) => {
204 wrap_str(context.snippet(self.span),
205 context.config.max_width,
213 pub fn rewrite_pair<LHS, RHS>(lhs: &LHS,
218 context: &RewriteContext,
225 let max_width = try_opt!(width.checked_sub(prefix.len() + infix.len() + suffix.len()));
227 binary_search(1, max_width, |lhs_budget| {
228 let lhs_offset = offset + prefix.len();
229 let lhs_str = match lhs.rewrite(context, lhs_budget, lhs_offset) {
230 Some(result) => result,
231 None => return Err(Ordering::Greater),
234 let last_line_width = last_line_width(&lhs_str);
235 let rhs_budget = match max_width.checked_sub(last_line_width) {
237 None => return Err(Ordering::Less),
239 let rhs_indent = offset + last_line_width + prefix.len() + infix.len();
241 let rhs_str = match rhs.rewrite(context, rhs_budget, rhs_indent) {
242 Some(result) => result,
243 None => return Err(Ordering::Less),
246 Ok(format!("{}{}{}{}{}", prefix, lhs_str, infix, rhs_str, suffix))
250 pub fn rewrite_array<'a, I>(expr_iter: I,
252 context: &RewriteContext,
256 where I: Iterator<Item = &'a ast::Expr>
259 let offset = offset + 1;
260 let inner_context = &RewriteContext { block_indent: offset, ..*context };
261 let max_item_width = try_opt!(width.checked_sub(2));
262 let items = itemize_list(context.codemap,
268 |item| item.rewrite(&inner_context, max_item_width, offset),
271 .collect::<Vec<_>>();
273 let has_long_item = try_opt!(items.iter()
274 .map(|li| li.item.as_ref().map(|s| s.len() > 10))
276 |acc, x| acc.and_then(|y| x.map(|x| x || y))));
278 let tactic = if has_long_item || items.iter().any(ListItem::is_multiline) {
279 definitive_tactic(&items, ListTactic::HorizontalVertical, max_item_width)
281 DefinitiveListTactic::Mixed
284 let fmt = ListFormatting {
287 trailing_separator: SeparatorTactic::Never,
289 width: max_item_width,
290 ends_with_newline: false,
291 config: context.config,
293 let list_str = try_opt!(write_list(&items, &fmt));
295 Some(format!("[{}]", list_str))
298 // This functions is pretty messy because of the wrapping and unwrapping of
299 // expressions into and from blocks. See rust issue #27872.
300 fn rewrite_closure(capture: ast::CaptureClause,
301 fn_decl: &ast::FnDecl,
304 context: &RewriteContext,
308 let mover = if capture == ast::CaptureClause::CaptureByValue {
313 let offset = offset + mover.len();
315 // 4 = "|| {".len(), which is overconservative when the closure consists of
316 // a single expression.
317 let budget = try_opt!(width.checked_sub(4 + mover.len()));
319 let argument_offset = offset + 1;
320 let ret_str = try_opt!(fn_decl.output.rewrite(context, budget, argument_offset));
321 // 1 = space between arguments and return type.
322 let horizontal_budget = budget.checked_sub(ret_str.len() + 1).unwrap_or(0);
324 let arg_items = itemize_list(context.codemap,
325 fn_decl.inputs.iter(),
327 |arg| span_lo_for_arg(arg),
328 |arg| span_hi_for_arg(arg),
329 |arg| arg.rewrite(context, budget, argument_offset),
330 span_after(span, "|", context.codemap),
332 let item_vec = arg_items.collect::<Vec<_>>();
333 let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
334 let budget = match tactic {
335 DefinitiveListTactic::Horizontal => horizontal_budget,
339 let fmt = ListFormatting {
342 trailing_separator: SeparatorTactic::Never,
343 indent: argument_offset,
345 ends_with_newline: false,
346 config: context.config,
348 let list_str = try_opt!(write_list(&item_vec, &fmt));
349 let mut prefix = format!("{}|{}|", mover, list_str);
351 if !ret_str.is_empty() {
352 if prefix.contains('\n') {
354 prefix.push_str(&argument_offset.to_string(context.config));
358 prefix.push_str(&ret_str);
361 // Try to format closure body as a single line expression without braces.
362 if is_simple_block(body, context.codemap) && !prefix.contains('\n') {
363 let (spacer, closer) = if ret_str.is_empty() {
368 let expr = body.expr.as_ref().unwrap();
369 // All closure bodies are blocks in the eyes of the AST, but we may not
370 // want to unwrap them when they only contain a single expression.
371 let inner_expr = match expr.node {
372 ast::Expr_::ExprBlock(ref inner) if inner.stmts.is_empty() && inner.expr.is_some() &&
374 ast::BlockCheckMode::DefaultBlock => {
375 inner.expr.as_ref().unwrap()
379 let extra_offset = extra_offset(&prefix, offset) + spacer.len();
380 let budget = try_opt!(width.checked_sub(extra_offset + closer.len()));
381 let rewrite = inner_expr.rewrite(context, budget, offset + extra_offset);
383 // Checks if rewrite succeeded and fits on a single line.
384 let accept_rewrite = rewrite.as_ref().map(|result| !result.contains('\n')).unwrap_or(false);
387 return Some(format!("{}{}{}{}", prefix, spacer, rewrite.unwrap(), closer));
391 // We couldn't format the closure body as a single line expression; fall
392 // back to block formatting.
393 let body_rewrite = body.expr
395 .and_then(|body_expr| {
396 if let ast::Expr_::ExprBlock(ref inner) = body_expr.node {
397 Some(inner.rewrite(&context, 2, Indent::empty()))
402 .unwrap_or_else(|| body.rewrite(&context, 2, Indent::empty()));
404 Some(format!("{} {}", prefix, try_opt!(body_rewrite)))
407 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
408 block_str.map(|block_str| {
409 if block_str.starts_with("{") && budget >= 2 &&
410 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2) {
418 impl Rewrite for ast::Block {
419 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
420 let user_str = context.snippet(self.span);
421 if user_str == "{}" && width >= 2 {
422 return Some(user_str);
425 let mut visitor = FmtVisitor::from_codemap(context.codemap, context.config);
426 visitor.block_indent = context.block_indent + context.overflow_indent;
428 let prefix = match self.rules {
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::DefaultBlock => {
466 visitor.last_pos = self.span.lo;
472 visitor.visit_block(self);
474 // Push text between last block item and end of block
475 let snippet = visitor.snippet(mk_sp(visitor.last_pos, self.span.hi));
476 visitor.buffer.push_str(&snippet);
478 Some(format!("{}{}", prefix, visitor.buffer))
482 // FIXME(#18): implement pattern formatting
483 impl Rewrite for ast::Pat {
484 fn rewrite(&self, context: &RewriteContext, _: usize, _: Indent) -> Option<String> {
485 Some(context.snippet(self.span))
489 // Abstraction over for, while and loop expressions
491 cond: Option<&'a ast::Expr>,
492 block: &'a ast::Block,
493 label: Option<ast::Ident>,
494 pat: Option<&'a ast::Pat>,
501 fn new_loop(block: &'a ast::Block, label: Option<ast::Ident>) -> Loop<'a> {
513 fn new_while(pat: Option<&'a ast::Pat>,
515 block: &'a ast::Block,
516 label: Option<ast::Ident>)
532 fn new_for(pat: &'a ast::Pat,
534 block: &'a ast::Block,
535 label: Option<ast::Ident>)
549 impl<'a> Rewrite for Loop<'a> {
550 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
551 let label_string = rewrite_label(self.label);
553 let inner_width = try_opt!(width.checked_sub(self.keyword.len() + 2 + label_string.len()));
554 let inner_offset = offset + self.keyword.len() + label_string.len();
556 let pat_expr_string = match self.cond {
557 Some(cond) => try_opt!(rewrite_pat_expr(context,
564 None => String::new(),
567 // FIXME: this drops any comment between "loop" and the block.
569 .rewrite(context, width, offset)
580 fn rewrite_label(label: Option<ast::Ident>) -> String {
582 Some(ident) => format!("{}: ", ident),
583 None => "".to_owned(),
587 // Rewrites if-else blocks. If let Some(_) = pat, the expression is
588 // treated as an if-let-else expression.
589 fn rewrite_if_else(context: &RewriteContext,
591 if_block: &ast::Block,
592 else_block_opt: Option<&ast::Expr>,
593 pat: Option<&ast::Pat>,
596 allow_single_line: bool)
598 // 3 = "if ", 2 = " {"
599 let pat_expr_string = try_opt!(rewrite_pat_expr(context,
604 try_opt!(width.checked_sub(3 + 2)),
607 // Try to format if-else on single line.
608 if allow_single_line && context.config.single_line_if_else {
609 let trial = single_line_if_else(context, &pat_expr_string, if_block, else_block_opt, width);
616 let if_block_string = try_opt!(if_block.rewrite(context, width, offset));
617 let mut result = format!("if {} {}", pat_expr_string, if_block_string);
619 if let Some(else_block) = else_block_opt {
620 let rewrite = match else_block.node {
621 // If the else expression is another if-else expression, prevent it
622 // from being formatted on a single line.
623 ast::Expr_::ExprIfLet(ref pat, ref cond, ref if_block, ref else_block) => {
624 rewrite_if_else(context,
627 else_block.as_ref().map(|e| &**e),
633 ast::Expr_::ExprIf(ref cond, ref if_block, ref else_block) => {
634 rewrite_if_else(context,
637 else_block.as_ref().map(|e| &**e),
643 _ => else_block.rewrite(context, width, offset),
646 result.push_str(" else ");
647 result.push_str(&&try_opt!(rewrite));
653 fn single_line_if_else(context: &RewriteContext,
655 if_node: &ast::Block,
656 else_block_opt: Option<&ast::Expr>,
659 let else_block = try_opt!(else_block_opt);
660 let fixed_cost = "if { } else { }".len();
662 if let ast::ExprBlock(ref else_node) = else_block.node {
663 if !is_simple_block(if_node, context.codemap) ||
664 !is_simple_block(else_node, context.codemap) || pat_expr_str.contains('\n') {
668 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
669 let if_expr = if_node.expr.as_ref().unwrap();
670 let if_str = try_opt!(if_expr.rewrite(context, new_width, Indent::empty()));
672 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
673 let else_expr = else_node.expr.as_ref().unwrap();
674 let else_str = try_opt!(else_expr.rewrite(context, new_width, Indent::empty()));
676 // FIXME: this check shouldn't be necessary. Rewrites should either fail
677 // or wrap to a newline when the object does not fit the width.
678 let fits_line = fixed_cost + pat_expr_str.len() + if_str.len() + else_str.len() <= width;
680 if fits_line && !if_str.contains('\n') && !else_str.contains('\n') {
681 return Some(format!("if {} {{ {} }} else {{ {} }}",
691 // Checks that a block contains no statements, an expression and no comments.
692 fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
693 if !block.stmts.is_empty() || block.expr.is_none() {
697 let snippet = codemap.span_to_snippet(block.span).unwrap();
699 !contains_comment(&snippet)
702 // inter-match-arm-comment-rules:
703 // - all comments following a match arm before the start of the next arm
704 // are about the second arm
705 fn rewrite_match_arm_comment(context: &RewriteContext,
709 arm_indent_str: &str)
711 // The leading "," is not part of the arm-comment
712 let missed_str = match missed_str.find_uncommented(",") {
713 Some(n) => &missed_str[n + 1..],
714 None => &missed_str[..],
717 let mut result = String::new();
718 // any text not preceeded by a newline is pushed unmodified to the block
719 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
720 result.push_str(&missed_str[..first_brk]);
721 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
723 let first = missed_str.find(|c: char| !c.is_whitespace()).unwrap_or(missed_str.len());
724 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
725 // Excessive vertical whitespace before comment should be preserved
726 // TODO handle vertical whitespace better
729 let missed_str = missed_str[first..].trim();
730 if !missed_str.is_empty() {
731 let comment = try_opt!(rewrite_comment(&missed_str,
737 result.push_str(arm_indent_str);
738 result.push_str(&comment);
744 fn rewrite_match(context: &RewriteContext,
756 let cond_budget = try_opt!(width.checked_sub(8));
757 let cond_str = try_opt!(cond.rewrite(context, cond_budget, offset + 6));
758 let mut result = format!("match {} {{", cond_str);
760 let nested_context = context.nested_context();
761 let arm_indent = nested_context.block_indent + context.overflow_indent;
762 let arm_indent_str = arm_indent.to_string(context.config);
764 let open_brace_pos = span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])),
768 for (i, arm) in arms.iter().enumerate() {
769 // Make sure we get the stuff between arms.
770 let missed_str = if i == 0 {
771 context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
773 context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
775 let comment = try_opt!(rewrite_match_arm_comment(context,
780 result.push_str(&comment);
782 result.push_str(&arm_indent_str);
784 let arm_str = arm.rewrite(&nested_context,
785 context.config.max_width - arm_indent.width(),
787 if let Some(ref arm_str) = arm_str {
788 result.push_str(arm_str);
790 // We couldn't format the arm, just reproduce the source.
791 let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
792 result.push_str(&snippet);
795 // BytePos(1) = closing match brace.
796 let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
797 let last_comment = context.snippet(last_span);
798 let comment = try_opt!(rewrite_match_arm_comment(context,
803 result.push_str(&comment);
805 result.push_str(&(context.block_indent + context.overflow_indent).to_string(context.config));
810 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
811 let &ast::Arm { ref attrs, ref pats, .. } = arm;
812 if !attrs.is_empty() {
813 return attrs[0].span.lo;
819 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
824 impl Rewrite for ast::Arm {
825 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
826 let &ast::Arm { ref attrs, ref pats, ref guard, ref body } = self;
827 let indent_str = offset.to_string(context.config);
829 // FIXME this is all a bit grotty, would be nice to abstract out the
830 // treatment of attributes.
831 let attr_str = if !attrs.is_empty() {
832 // We only use this visitor for the attributes, should we use it for
834 let mut attr_visitor = FmtVisitor::from_codemap(context.codemap, context.config);
835 attr_visitor.block_indent = context.block_indent;
836 attr_visitor.last_pos = attrs[0].span.lo;
837 if attr_visitor.visit_attrs(attrs) {
838 // Attributes included a skip instruction.
839 let snippet = context.snippet(mk_sp(attrs[0].span.lo, body.span.hi));
840 return Some(snippet);
842 attr_visitor.format_missing(pats[0].span.lo);
843 attr_visitor.buffer.to_string()
850 let pat_budget = try_opt!(width.checked_sub(5));
851 let pat_strs = try_opt!(pats.iter()
855 offset.block_indent(context.config))
857 .collect::<Option<Vec<_>>>());
859 let mut total_width = pat_strs.iter().fold(0, |a, p| a + p.len());
861 total_width += (pat_strs.len() - 1) * 3;
863 let mut vertical = total_width > pat_budget || pat_strs.iter().any(|p| p.contains('\n'));
864 if !vertical && context.config.take_source_hints {
865 // If the patterns were previously stacked, keep them stacked.
866 let pat_span = mk_sp(pats[0].span.lo, pats[pats.len() - 1].span.hi);
867 let pat_str = context.snippet(pat_span);
868 vertical = pat_str.find('\n').is_some();
871 let pats_width = if vertical {
872 pat_strs[pat_strs.len() - 1].len()
877 let mut pats_str = String::new();
879 if !pats_str.is_empty() {
881 pats_str.push_str(" |\n");
882 pats_str.push_str(&indent_str);
884 pats_str.push_str(" | ");
887 pats_str.push_str(&p);
890 let guard_str = try_opt!(rewrite_guard(context, guard, width, offset, pats_width));
892 let pats_str = format!("{}{}", pats_str, guard_str);
893 // Where the next text can start.
894 let mut line_start = last_line_width(&pats_str);
895 if !pats_str.contains('\n') {
896 line_start += offset.width();
899 let comma = if let ast::ExprBlock(_) = body.node {
905 // Let's try and get the arm body on the same line as the condition.
907 let same_line_body = if context.config.max_width > line_start + comma.len() + 4 {
908 let budget = context.config.max_width - line_start - comma.len() - 4;
909 let offset = Indent::new(offset.block_indent, line_start + 4 - offset.block_indent);
910 let rewrite = nop_block_collapse(body.rewrite(context, budget, offset), budget);
913 Some(ref body_str) if body_str.len() <= budget || comma.is_empty() =>
914 return Some(format!("{}{} => {}{}",
915 attr_str.trim_left(),
925 if let ast::ExprBlock(_) = body.node {
926 // We're trying to fit a block in, but it still failed, give up.
930 let body_budget = try_opt!(width.checked_sub(context.config.tab_spaces));
931 let next_line_body = nop_block_collapse(body.rewrite(context,
934 .block_indent(context.config)),
937 let body_str = try_opt!(match_arm_heuristic(same_line_body.as_ref().map(|x| &x[..]),
938 next_line_body.as_ref().map(|x| &x[..])));
940 let spacer = match same_line_body {
941 Some(ref body) if body == body_str => " ".to_owned(),
943 offset.block_indent(context.config).to_string(context.config)),
946 Some(format!("{}{} =>{}{},",
947 attr_str.trim_left(),
954 // Takes two possible rewrites for the match arm body and chooses the "nicest".
955 fn match_arm_heuristic<'a>(former: Option<&'a str>, latter: Option<&'a str>) -> Option<&'a str> {
956 match (former, latter) {
957 (f @ Some(..), None) => f,
958 (Some(f), Some(l)) if f.chars().filter(|&c| c == '\n').count() <=
959 l.chars().filter(|&c| c == '\n').count() => {
966 // The `if ...` guard on a match arm.
967 fn rewrite_guard(context: &RewriteContext,
968 guard: &Option<ptr::P<ast::Expr>>,
971 // The amount of space used up on this line for the pattern in
972 // the arm (excludes offset).
973 pattern_width: usize)
975 if let &Some(ref guard) = guard {
976 // First try to fit the guard string on the same line as the pattern.
977 // 4 = ` if `, 5 = ` => {`
978 let overhead = pattern_width + 4 + 5;
979 if overhead < width {
980 let cond_str = guard.rewrite(context, width - overhead, offset + pattern_width + 4);
981 if let Some(cond_str) = cond_str {
982 return Some(format!(" if {}", cond_str));
986 // Not enough space to put the guard after the pattern, try a newline.
987 let overhead = context.config.tab_spaces + 4 + 5;
988 if overhead < width {
989 let cond_str = guard.rewrite(context,
991 offset.block_indent(context.config));
992 if let Some(cond_str) = cond_str {
993 return Some(format!("\n{}if {}",
994 offset.block_indent(context.config).to_string(context.config),
1005 fn rewrite_pat_expr(context: &RewriteContext,
1006 pat: Option<&ast::Pat>,
1009 // Connecting piece between pattern and expression,
1010 // *without* trailing space.
1015 let pat_offset = offset + matcher.len();
1016 let mut result = match pat {
1018 let pat_budget = try_opt!(width.checked_sub(connector.len() + matcher.len()));
1019 let pat_string = try_opt!(pat.rewrite(context, pat_budget, pat_offset));
1020 format!("{}{}{}", matcher, pat_string, connector)
1022 None => String::new(),
1025 // Consider only the last line of the pat string.
1026 let extra_offset = extra_offset(&result, offset);
1028 // The expression may (partionally) fit on the current line.
1029 if width > extra_offset + 1 {
1030 let spacer = if pat.is_some() {
1036 let expr_rewrite = expr.rewrite(context,
1037 width - extra_offset - spacer.len(),
1038 offset + extra_offset + spacer.len());
1040 if let Some(expr_string) = expr_rewrite {
1041 result.push_str(spacer);
1042 result.push_str(&expr_string);
1043 return Some(result);
1047 // The expression won't fit on the current line, jump to next.
1049 result.push_str(&pat_offset.to_string(context.config));
1051 let expr_rewrite = expr.rewrite(context,
1052 context.config.max_width - pat_offset.width(),
1054 result.push_str(&&try_opt!(expr_rewrite));
1059 fn rewrite_string_lit(context: &RewriteContext,
1064 if !context.config.format_strings {
1065 return Some(context.snippet(span));
1068 let fmt = StringFormat {
1076 config: context.config,
1079 let string_lit = context.snippet(span);
1080 let str_lit = &string_lit[1..string_lit.len() - 1]; // Remove the quote characters.
1082 rewrite_string(str_lit, &fmt)
1085 pub fn rewrite_call<R>(context: &RewriteContext,
1087 args: &[ptr::P<ast::Expr>],
1094 let closure = |callee_max_width| {
1095 rewrite_call_inner(context, callee, callee_max_width, args, span, width, offset)
1099 let max_width = try_opt!(width.checked_sub(2));
1100 binary_search(1, max_width, closure)
1103 fn rewrite_call_inner<R>(context: &RewriteContext,
1105 max_callee_width: usize,
1106 args: &[ptr::P<ast::Expr>],
1110 -> Result<String, Ordering>
1113 let callee = callee.borrow();
1114 // FIXME using byte lens instead of char lens (and probably all over the
1116 let callee_str = match callee.rewrite(context, max_callee_width, offset) {
1118 if !string.contains('\n') && string.len() > max_callee_width {
1119 panic!("{:?} {}", string, max_callee_width);
1124 None => return Err(Ordering::Greater),
1127 let span_lo = span_after(span, "(", context.codemap);
1128 let span = mk_sp(span_lo, span.hi);
1130 let extra_offset = extra_offset(&callee_str, offset);
1132 let remaining_width = match width.checked_sub(extra_offset + 2) {
1134 None => return Err(Ordering::Greater),
1136 let offset = offset + extra_offset + 1;
1137 let arg_count = args.len();
1138 let block_indent = if arg_count == 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),
1153 let mut item_vec: Vec<_> = items.collect();
1155 // Try letting the last argument overflow to the next line with block
1156 // indentation. If its first line fits on one line with the other arguments,
1157 // we format the function arguments horizontally.
1158 let overflow_last = match args.last().map(|x| &x.node) {
1159 Some(&ast::Expr_::ExprClosure(..)) |
1160 Some(&ast::Expr_::ExprBlock(..)) if arg_count > 1 => true,
1162 } && context.config.chains_overflow_last;
1164 let mut orig_last = None;
1165 let mut placeholder = None;
1167 // Replace the last item with its first line to see if it fits with
1170 let inner_context = &RewriteContext { block_indent: context.block_indent, ..*context };
1171 let rewrite = args.last().unwrap().rewrite(&inner_context, remaining_width, offset);
1173 if let Some(rewrite) = rewrite {
1174 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
1175 placeholder = Some(rewrite);
1177 swap(&mut item_vec[arg_count - 1].item, &mut orig_last);
1178 item_vec[arg_count - 1].item = rewrite_first_line;
1182 let tactic = definitive_tactic(&item_vec,
1183 ListTactic::LimitedHorizontalVertical(context.config
1187 // Replace the stub with the full overflowing last argument if the rewrite
1188 // succeeded and its first line fits with the other arguments.
1189 match (overflow_last, tactic, placeholder) {
1190 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
1191 item_vec[arg_count - 1].item = placeholder;
1194 item_vec[arg_count - 1].item = orig_last;
1199 let fmt = ListFormatting {
1202 trailing_separator: SeparatorTactic::Never,
1205 ends_with_newline: false,
1206 config: context.config,
1209 // format_fn_args(items, remaining_width, offset, context.config)
1211 let list_str = match write_list(&item_vec, &fmt) {
1213 None => return Err(Ordering::Less),
1216 Ok(format!("{}({})", callee_str, list_str))
1219 fn rewrite_paren(context: &RewriteContext,
1220 subexpr: &ast::Expr,
1224 debug!("rewrite_paren, width: {}, offset: {:?}", width, offset);
1225 // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
1226 // paren on the same line as the subexpr.
1227 let subexpr_str = subexpr.rewrite(context, try_opt!(width.checked_sub(2)), offset + 1);
1228 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1229 subexpr_str.map(|s| format!("({})", s))
1232 fn rewrite_struct_lit<'a>(context: &RewriteContext,
1234 fields: &'a [ast::Field],
1235 base: Option<&'a ast::Expr>,
1240 debug!("rewrite_struct_lit: width {}, offset {:?}", width, offset);
1241 assert!(!fields.is_empty() || base.is_some());
1243 enum StructLitField<'a> {
1244 Regular(&'a ast::Field),
1245 Base(&'a ast::Expr),
1249 let path_budget = try_opt!(width.checked_sub(2));
1250 let path_str = try_opt!(path.rewrite(context, path_budget, offset));
1252 // Foo { a: Foo } - indent is +3, width is -5.
1253 let h_budget = width.checked_sub(path_str.len() + 5).unwrap_or(0);
1254 let (indent, v_budget) = match context.config.struct_lit_style {
1255 StructLitStyle::Visual => {
1256 (offset + path_str.len() + 3, h_budget)
1258 StructLitStyle::Block => {
1259 // If we are all on one line, then we'll ignore the indent, and we
1260 // have a smaller budget.
1261 let indent = context.block_indent.block_indent(context.config);
1262 let v_budget = context.config.max_width.checked_sub(indent.width()).unwrap_or(0);
1267 let field_iter = fields.into_iter()
1268 .map(StructLitField::Regular)
1269 .chain(base.into_iter().map(StructLitField::Base));
1271 let inner_context = &RewriteContext { block_indent: indent, ..*context };
1273 let items = itemize_list(context.codemap,
1278 StructLitField::Regular(ref field) => field.span.lo,
1279 StructLitField::Base(ref expr) => {
1280 let last_field_hi = fields.last().map_or(span.lo,
1284 let snippet = context.snippet(mk_sp(last_field_hi,
1286 let pos = snippet.find_uncommented("..").unwrap();
1287 last_field_hi + BytePos(pos as u32)
1293 StructLitField::Regular(ref field) => field.span.hi,
1294 StructLitField::Base(ref expr) => expr.span.hi,
1299 StructLitField::Regular(ref field) => {
1300 rewrite_field(inner_context, &field, v_budget, indent)
1302 StructLitField::Base(ref expr) => {
1304 expr.rewrite(inner_context,
1305 try_opt!(v_budget.checked_sub(2)),
1307 .map(|s| format!("..{}", s))
1311 span_after(span, "{", context.codemap),
1313 let item_vec = items.collect::<Vec<_>>();
1316 let mut prelim_tactic = match (context.config.struct_lit_style, fields.len()) {
1317 (StructLitStyle::Visual, 1) => ListTactic::HorizontalVertical,
1318 _ => context.config.struct_lit_multiline_style.to_list_tactic(),
1321 if prelim_tactic == ListTactic::HorizontalVertical && fields.len() > 1 {
1322 prelim_tactic = ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width);
1325 definitive_tactic(&item_vec, prelim_tactic, h_budget)
1328 let budget = match tactic {
1329 DefinitiveListTactic::Horizontal => h_budget,
1333 let fmt = ListFormatting {
1336 trailing_separator: if base.is_some() {
1337 SeparatorTactic::Never
1339 context.config.struct_lit_trailing_comma
1343 ends_with_newline: false,
1344 config: context.config,
1346 let fields_str = try_opt!(write_list(&item_vec, &fmt));
1348 let format_on_newline = || {
1349 let inner_indent = context.block_indent
1350 .block_indent(context.config)
1351 .to_string(context.config);
1352 let outer_indent = context.block_indent.to_string(context.config);
1353 Some(format!("{} {{\n{}{}\n{}}}",
1360 match (context.config.struct_lit_style,
1361 context.config.struct_lit_multiline_style) {
1362 (StructLitStyle::Block, _) if fields_str.contains('\n') || fields_str.len() > h_budget =>
1363 format_on_newline(),
1364 (StructLitStyle::Block, MultilineStyle::ForceMulti) => format_on_newline(),
1365 _ => Some(format!("{} {{ {} }}", path_str, fields_str)),
1368 // FIXME if context.config.struct_lit_style == Visual, but we run out
1369 // of space, we should fall back to BlockIndent.
1372 fn rewrite_field(context: &RewriteContext,
1377 let name = &field.ident.node.to_string();
1378 let overhead = name.len() + 2;
1379 let expr = field.expr.rewrite(context,
1380 try_opt!(width.checked_sub(overhead)),
1382 expr.map(|s| format!("{}: {}", name, s))
1385 fn rewrite_tuple_lit(context: &RewriteContext,
1386 items: &[ptr::P<ast::Expr>],
1391 debug!("rewrite_tuple_lit: width: {}, offset: {:?}", width, offset);
1392 let indent = offset + 1;
1393 // In case of length 1, need a trailing comma
1394 if items.len() == 1 {
1396 let budget = try_opt!(width.checked_sub(3));
1397 return items[0].rewrite(context, budget, indent).map(|s| format!("({},)", s));
1400 let items = itemize_list(context.codemap,
1403 |item| item.span.lo,
1404 |item| item.span.hi,
1406 let inner_width = context.config.max_width - indent.width() - 1;
1407 item.rewrite(context, inner_width, indent)
1409 span.lo + BytePos(1), // Remove parens
1410 span.hi - BytePos(1));
1411 let budget = try_opt!(width.checked_sub(2));
1412 let list_str = try_opt!(format_fn_args(items, budget, indent, context.config));
1414 Some(format!("({})", list_str))
1417 fn rewrite_binary_op(context: &RewriteContext,
1424 // FIXME: format comments between operands and operator
1426 let operator_str = context.snippet(op.span);
1428 // Get "full width" rhs and see if it fits on the current line. This
1429 // usually works fairly well since it tends to place operands of
1430 // operations with high precendence close together.
1431 let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
1433 // Second condition is needed in case of line break not caused by a
1434 // shortage of space, but by end-of-line comments, for example.
1435 // Note that this is non-conservative, but its just to see if it's even
1436 // worth trying to put everything on one line.
1437 if rhs_result.len() + 2 + operator_str.len() < width && !rhs_result.contains('\n') {
1438 // 1 = space between lhs expr and operator
1439 if let Some(mut result) = lhs.rewrite(context, width - 1 - operator_str.len(), offset) {
1441 result.push_str(&operator_str);
1444 let remaining_width = width.checked_sub(last_line_width(&result)).unwrap_or(0);
1446 if rhs_result.len() <= remaining_width {
1447 result.push_str(&rhs_result);
1448 return Some(result);
1451 if let Some(rhs_result) = rhs.rewrite(context, remaining_width, offset + result.len()) {
1452 if rhs_result.len() <= remaining_width {
1453 result.push_str(&rhs_result);
1454 return Some(result);
1460 // We have to use multiple lines.
1462 // Re-evaluate the lhs because we have more space now:
1463 let budget = try_opt!(context.config
1465 .checked_sub(offset.width() + 1 + operator_str.len()));
1466 Some(format!("{} {}\n{}{}",
1467 try_opt!(lhs.rewrite(context, budget, offset)),
1469 offset.to_string(context.config),
1473 pub fn rewrite_unary_prefix<R: Rewrite>(context: &RewriteContext,
1479 rewrite.rewrite(context,
1480 try_opt!(width.checked_sub(prefix.len())),
1481 offset + prefix.len())
1482 .map(|r| format!("{}{}", prefix, r))
1485 fn rewrite_unary_op(context: &RewriteContext,
1491 // For some reason, an UnOp is not spanned like BinOp!
1492 let operator_str = match *op {
1493 ast::UnOp::UnDeref => "*",
1494 ast::UnOp::UnNot => "!",
1495 ast::UnOp::UnNeg => "-",
1497 rewrite_unary_prefix(context, operator_str, expr, width, offset)
1500 fn rewrite_assignment(context: &RewriteContext,
1503 op: Option<&ast::BinOp>,
1507 let operator_str = match op {
1508 Some(op) => context.snippet(op.span),
1509 None => "=".to_owned(),
1512 // 1 = space between lhs and operator.
1513 let max_width = try_opt!(width.checked_sub(operator_str.len() + 1));
1514 let lhs_str = format!("{} {}",
1515 try_opt!(lhs.rewrite(context, max_width, offset)),
1518 rewrite_assign_rhs(&context, lhs_str, rhs, width, offset)
1521 // The left hand side must contain everything up to, and including, the
1522 // assignment operator.
1523 pub fn rewrite_assign_rhs<S: Into<String>>(context: &RewriteContext,
1529 let mut result = lhs.into();
1531 // 1 = space between operator and rhs.
1532 let max_width = try_opt!(width.checked_sub(result.len() + 1));
1533 let rhs = ex.rewrite(&context, max_width, offset + result.len() + 1);
1538 result.push_str(&new_str)
1541 // Expression did not fit on the same line as the identifier. Retry
1542 // on the next line.
1543 let new_offset = offset.block_indent(context.config);
1544 result.push_str(&format!("\n{}", new_offset.to_string(context.config)));
1546 // FIXME: we probably should related max_width to width instead of config.max_width
1547 // where is the 1 coming from anyway?
1548 let max_width = try_opt!(context.config.max_width.checked_sub(new_offset.width() + 1));
1549 let rhs_indent = Indent::new(context.config.tab_spaces, 0);
1550 let overflow_context = context.overflow_context(rhs_indent);
1551 let rhs = ex.rewrite(&overflow_context, max_width, new_offset);
1553 result.push_str(&&try_opt!(rhs));
1560 fn rewrite_expr_addrof(context: &RewriteContext,
1561 mutability: ast::Mutability,
1566 let operator_str = match mutability {
1567 ast::Mutability::MutImmutable => "&",
1568 ast::Mutability::MutMutable => "&mut ",
1570 rewrite_unary_prefix(context, operator_str, expr, width, offset)