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 use string::{StringFormat, rewrite_string};
18 use utils::{span_after, extra_offset, last_line_width, wrap_str, binary_search};
19 use visitor::FmtVisitor;
20 use config::{StructLitStyle, MultilineStyle};
21 use comment::{FindUncommented, rewrite_comment, contains_comment};
22 use types::rewrite_path;
23 use items::{span_lo_for_arg, span_hi_for_arg};
24 use chains::rewrite_chain;
25 use macros::rewrite_macro;
27 use syntax::{ast, ptr};
28 use syntax::codemap::{CodeMap, Span, BytePos, mk_sp};
29 use syntax::visit::Visitor;
31 impl Rewrite for ast::Expr {
32 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
34 ast::Expr_::ExprVec(ref expr_vec) => {
35 rewrite_array(expr_vec.iter().map(|e| &**e),
41 ast::Expr_::ExprLit(ref l) => {
43 ast::Lit_::LitStr(_, ast::StrStyle::CookedStr) => {
44 rewrite_string_lit(context, l.span, width, offset)
47 wrap_str(context.snippet(self.span),
48 context.config.max_width,
54 ast::Expr_::ExprCall(ref callee, ref args) => {
55 let inner_span = mk_sp(callee.span.hi, self.span.hi);
56 rewrite_call(context, &**callee, args, inner_span, width, offset)
58 ast::Expr_::ExprParen(ref subexpr) => {
59 rewrite_paren(context, subexpr, width, offset)
61 ast::Expr_::ExprBinary(ref op, ref lhs, ref rhs) => {
62 rewrite_binary_op(context, op, lhs, rhs, width, offset)
64 ast::Expr_::ExprUnary(ref op, ref subexpr) => {
65 rewrite_unary_op(context, op, subexpr, width, offset)
67 ast::Expr_::ExprStruct(ref path, ref fields, ref base) => {
68 rewrite_struct_lit(context,
71 base.as_ref().map(|e| &**e),
76 ast::Expr_::ExprTup(ref items) => {
77 rewrite_tuple_lit(context, items, self.span, width, offset)
79 ast::Expr_::ExprWhile(ref cond, ref block, label) => {
80 Loop::new_while(None, cond, block, label).rewrite(context, width, offset)
82 ast::Expr_::ExprWhileLet(ref pat, ref cond, ref block, label) => {
83 Loop::new_while(Some(pat), cond, block, label).rewrite(context, width, offset)
85 ast::Expr_::ExprForLoop(ref pat, ref cond, ref block, label) => {
86 Loop::new_for(pat, cond, block, label).rewrite(context, width, offset)
88 ast::Expr_::ExprLoop(ref block, label) => {
89 Loop::new_loop(block, label).rewrite(context, width, offset)
91 ast::Expr_::ExprBlock(ref block) => {
92 block.rewrite(context, width, offset)
94 ast::Expr_::ExprIf(ref cond, ref if_block, ref else_block) => {
95 rewrite_if_else(context,
98 else_block.as_ref().map(|e| &**e),
104 ast::Expr_::ExprIfLet(ref pat, ref cond, ref if_block, ref else_block) => {
105 rewrite_if_else(context,
108 else_block.as_ref().map(|e| &**e),
114 // We reformat it ourselves because rustc gives us a bad span
115 // for ranges, see rust#27162
116 ast::Expr_::ExprRange(ref left, ref right) => {
117 rewrite_range(context,
118 left.as_ref().map(|e| &**e),
119 right.as_ref().map(|e| &**e),
123 ast::Expr_::ExprMatch(ref cond, ref arms, _) => {
124 rewrite_match(context, cond, arms, width, offset, self.span)
126 ast::Expr_::ExprPath(ref qself, ref path) => {
127 rewrite_path(context, qself.as_ref(), path, width, offset)
129 ast::Expr_::ExprAssign(ref lhs, ref rhs) => {
130 rewrite_assignment(context, lhs, rhs, None, width, offset)
132 ast::Expr_::ExprAssignOp(ref op, ref lhs, ref rhs) => {
133 rewrite_assignment(context, lhs, rhs, Some(op), width, offset)
135 ast::Expr_::ExprAgain(ref opt_ident) => {
136 let id_str = match *opt_ident {
137 Some(ident) => format!(" {}", ident.node),
138 None => String::new(),
140 Some(format!("continue{}", id_str))
142 ast::Expr_::ExprBreak(ref opt_ident) => {
143 let id_str = match *opt_ident {
144 Some(ident) => format!(" {}", ident.node),
145 None => String::new(),
147 Some(format!("break{}", id_str))
149 ast::Expr_::ExprClosure(capture, ref fn_decl, ref body) => {
150 rewrite_closure(capture, fn_decl, body, self.span, context, width, offset)
152 ast::Expr_::ExprField(..) |
153 ast::Expr_::ExprTupField(..) |
154 ast::Expr_::ExprMethodCall(..) => {
155 rewrite_chain(self, context, width, offset)
157 ast::Expr_::ExprMac(ref mac) => {
158 // Failure to rewrite a marco should not imply failure to
159 // rewrite the expression.
160 rewrite_macro(mac, context, width, offset).or_else(|| {
161 wrap_str(context.snippet(self.span),
162 context.config.max_width,
167 ast::Expr_::ExprRet(None) => {
168 wrap_str("return".to_owned(),
169 context.config.max_width,
173 ast::Expr_::ExprRet(Some(ref expr)) => {
174 rewrite_unary_prefix(context, "return ", expr, width, offset)
176 ast::Expr_::ExprBox(ref expr) => {
177 rewrite_unary_prefix(context, "box ", expr, width, offset)
179 ast::Expr_::ExprAddrOf(mutability, ref expr) => {
180 rewrite_expr_addrof(context, mutability, &expr, width, offset)
182 // We do not format these expressions yet, but they should still
183 // satisfy our width restrictions.
184 ast::Expr_::ExprInPlace(..) |
185 ast::Expr_::ExprCast(..) |
186 ast::Expr_::ExprIndex(..) |
187 ast::Expr_::ExprInlineAsm(..) |
188 ast::Expr_::ExprRepeat(..) => {
189 wrap_str(context.snippet(self.span),
190 context.config.max_width,
198 pub fn rewrite_array<'a, I>(expr_iter: I,
200 context: &RewriteContext,
204 where I: Iterator<Item = &'a ast::Expr>
207 let max_item_width = try_opt!(width.checked_sub(2));
208 let items = itemize_list(context.codemap,
214 // FIXME(#133): itemize_list doesn't support
215 // rewrite failure. This may not be its
216 // responsibility, but that of write_list.
218 item.rewrite(context, max_item_width, offset + 1)
219 .unwrap_or_else(|| context.snippet(item.span))
221 span_after(span, "[", context.codemap),
223 .collect::<Vec<_>>();
225 let tactic = if items.iter().any(|li| li.item.len() > 10 || li.is_multiline()) {
226 ListTactic::HorizontalVertical
231 let fmt = ListFormatting {
234 trailing_separator: SeparatorTactic::Never,
236 h_width: max_item_width,
237 v_width: max_item_width,
238 ends_with_newline: false,
239 config: context.config,
241 let list_str = try_opt!(write_list(&items, &fmt));
243 Some(format!("[{}]", list_str))
246 // This functions is pretty messy because of the wrapping and unwrapping of
247 // expressions into and from blocks. See rust issue #27872.
248 fn rewrite_closure(capture: ast::CaptureClause,
249 fn_decl: &ast::FnDecl,
252 context: &RewriteContext,
256 let mover = if capture == ast::CaptureClause::CaptureByValue {
261 let offset = offset + mover.len();
263 // 4 = "|| {".len(), which is overconservative when the closure consists of
264 // a single expression.
265 let budget = try_opt!(width.checked_sub(4 + mover.len()));
267 let argument_offset = offset + 1;
268 let ret_str = try_opt!(fn_decl.output.rewrite(context, budget, argument_offset));
269 // 1 = space between arguments and return type.
270 let horizontal_budget = budget.checked_sub(ret_str.len() + 1).unwrap_or(0);
272 let arg_items = itemize_list(context.codemap,
273 fn_decl.inputs.iter(),
275 |arg| span_lo_for_arg(arg),
276 |arg| span_hi_for_arg(arg),
278 // FIXME: we should just escalate failure
279 // here, but itemize_list doesn't allow it.
280 arg.rewrite(context, budget, argument_offset)
282 context.snippet(mk_sp(span_lo_for_arg(arg),
283 span_hi_for_arg(arg)))
286 span_after(span, "|", context.codemap),
289 let fmt = ListFormatting {
290 tactic: ListTactic::HorizontalVertical,
292 trailing_separator: SeparatorTactic::Never,
293 indent: argument_offset,
294 h_width: horizontal_budget,
296 ends_with_newline: false,
297 config: context.config,
299 let list_str = try_opt!(write_list(&arg_items.collect::<Vec<_>>(), &fmt));
300 let mut prefix = format!("{}|{}|", mover, list_str);
302 if !ret_str.is_empty() {
303 if prefix.contains('\n') {
305 prefix.push_str(&argument_offset.to_string(context.config));
309 prefix.push_str(&ret_str);
312 // Try to format closure body as a single line expression without braces.
313 if is_simple_block(body, context.codemap) && !prefix.contains('\n') {
314 let (spacer, closer) = if ret_str.is_empty() {
319 let expr = body.expr.as_ref().unwrap();
320 // All closure bodies are blocks in the eyes of the AST, but we may not
321 // want to unwrap them when they only contain a single expression.
322 let inner_expr = match expr.node {
323 ast::Expr_::ExprBlock(ref inner) if inner.stmts.is_empty() && inner.expr.is_some() &&
325 ast::BlockCheckMode::DefaultBlock => {
326 inner.expr.as_ref().unwrap()
330 let extra_offset = extra_offset(&prefix, offset) + spacer.len();
331 let budget = try_opt!(width.checked_sub(extra_offset + closer.len()));
332 let rewrite = inner_expr.rewrite(context, budget, offset + extra_offset);
334 // Checks if rewrite succeeded and fits on a single line.
335 let accept_rewrite = rewrite.as_ref().map(|result| !result.contains('\n')).unwrap_or(false);
338 return Some(format!("{}{}{}{}", prefix, spacer, rewrite.unwrap(), closer));
342 // We couldn't format the closure body as a single line expression; fall
343 // back to block formatting.
344 let body_rewrite = body.expr
346 .and_then(|body_expr| {
347 if let ast::Expr_::ExprBlock(ref inner) = body_expr.node {
348 Some(inner.rewrite(&context, 2, Indent::empty()))
353 .unwrap_or_else(|| body.rewrite(&context, 2, Indent::empty()));
355 Some(format!("{} {}", prefix, try_opt!(body_rewrite)))
358 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
359 block_str.map(|block_str| {
360 if block_str.starts_with("{") && budget >= 2 &&
361 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2) {
369 impl Rewrite for ast::Block {
370 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
371 let user_str = context.snippet(self.span);
372 if user_str == "{}" && width >= 2 {
373 return Some(user_str);
376 let mut visitor = FmtVisitor::from_codemap(context.codemap, context.config);
377 visitor.block_indent = context.block_indent + context.overflow_indent;
379 let prefix = match self.rules {
380 ast::BlockCheckMode::PushUnsafeBlock(..) |
381 ast::BlockCheckMode::UnsafeBlock(..) => {
382 let snippet = context.snippet(self.span);
383 let open_pos = try_opt!(snippet.find_uncommented("{"));
384 visitor.last_pos = self.span.lo + BytePos(open_pos as u32);
386 // Extract comment between unsafe and block start.
387 let trimmed = &snippet[6..open_pos].trim();
389 let prefix = if !trimmed.is_empty() {
390 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
391 let budget = try_opt!(width.checked_sub(9));
392 format!("unsafe {} ",
393 try_opt!(rewrite_comment(trimmed,
402 if is_simple_block(self, context.codemap) && prefix.len() < width {
406 .rewrite(context, width - prefix.len(), offset);
407 if let Some(ref expr_str) = body {
408 let result = format!("{}{{ {} }}", prefix, expr_str);
409 if result.len() <= width && !result.contains('\n') {
417 ast::BlockCheckMode::PopUnsafeBlock(..) |
418 ast::BlockCheckMode::DefaultBlock => {
419 visitor.last_pos = self.span.lo;
425 visitor.visit_block(self);
427 // Push text between last block item and end of block
428 let snippet = visitor.snippet(mk_sp(visitor.last_pos, self.span.hi));
429 visitor.buffer.push_str(&snippet);
431 Some(format!("{}{}", prefix, visitor.buffer))
435 // FIXME(#18): implement pattern formatting
436 impl Rewrite for ast::Pat {
437 fn rewrite(&self, context: &RewriteContext, _: usize, _: Indent) -> Option<String> {
438 Some(context.snippet(self.span))
442 // Abstraction over for, while and loop expressions
444 cond: Option<&'a ast::Expr>,
445 block: &'a ast::Block,
446 label: Option<ast::Ident>,
447 pat: Option<&'a ast::Pat>,
454 fn new_loop(block: &'a ast::Block, label: Option<ast::Ident>) -> Loop<'a> {
466 fn new_while(pat: Option<&'a ast::Pat>,
468 block: &'a ast::Block,
469 label: Option<ast::Ident>)
485 fn new_for(pat: &'a ast::Pat,
487 block: &'a ast::Block,
488 label: Option<ast::Ident>)
502 impl<'a> Rewrite for Loop<'a> {
503 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
504 let label_string = rewrite_label(self.label);
506 let inner_width = try_opt!(width.checked_sub(self.keyword.len() + 2 + label_string.len()));
507 let inner_offset = offset + self.keyword.len() + label_string.len();
509 let pat_expr_string = match self.cond {
510 Some(cond) => try_opt!(rewrite_pat_expr(context,
517 None => String::new(),
520 // FIXME: this drops any comment between "loop" and the block.
522 .rewrite(context, width, offset)
533 fn rewrite_label(label: Option<ast::Ident>) -> String {
535 Some(ident) => format!("{}: ", ident),
536 None => "".to_owned(),
540 // FIXME: this doesn't play well with line breaks
541 fn rewrite_range(context: &RewriteContext,
542 left: Option<&ast::Expr>,
543 right: Option<&ast::Expr>,
547 let left_string = match left {
550 let max_width = try_opt!(width.checked_sub(2));
551 try_opt!(expr.rewrite(context, max_width, offset))
553 None => String::new(),
556 let right_string = match right {
558 let max_width = try_opt!(width.checked_sub(left_string.len() + 2));
559 try_opt!(expr.rewrite(context, max_width, offset + 2 + left_string.len()))
561 None => String::new(),
564 Some(format!("{}..{}", left_string, right_string))
567 // Rewrites if-else blocks. If let Some(_) = pat, the expression is
568 // treated as an if-let-else expression.
569 fn rewrite_if_else(context: &RewriteContext,
571 if_block: &ast::Block,
572 else_block_opt: Option<&ast::Expr>,
573 pat: Option<&ast::Pat>,
576 allow_single_line: bool)
578 // 3 = "if ", 2 = " {"
579 let pat_expr_string = try_opt!(rewrite_pat_expr(context,
584 try_opt!(width.checked_sub(3 + 2)),
587 // Try to format if-else on single line.
588 if allow_single_line && context.config.single_line_if_else {
589 let trial = single_line_if_else(context, &pat_expr_string, if_block, else_block_opt, width);
596 let if_block_string = try_opt!(if_block.rewrite(context, width, offset));
597 let mut result = format!("if {} {}", pat_expr_string, if_block_string);
599 if let Some(else_block) = else_block_opt {
600 let rewrite = match else_block.node {
601 // If the else expression is another if-else expression, prevent it
602 // from being formatted on a single line.
603 ast::Expr_::ExprIfLet(ref pat, ref cond, ref if_block, ref else_block) => {
604 rewrite_if_else(context,
607 else_block.as_ref().map(|e| &**e),
613 ast::Expr_::ExprIf(ref cond, ref if_block, ref else_block) => {
614 rewrite_if_else(context,
617 else_block.as_ref().map(|e| &**e),
623 _ => else_block.rewrite(context, width, offset),
626 result.push_str(" else ");
627 result.push_str(&&try_opt!(rewrite));
633 fn single_line_if_else(context: &RewriteContext,
635 if_node: &ast::Block,
636 else_block_opt: Option<&ast::Expr>,
639 let else_block = try_opt!(else_block_opt);
640 let fixed_cost = "if { } else { }".len();
642 if let ast::ExprBlock(ref else_node) = else_block.node {
643 if !is_simple_block(if_node, context.codemap) ||
644 !is_simple_block(else_node, context.codemap) || pat_expr_str.contains('\n') {
648 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
649 let if_expr = if_node.expr.as_ref().unwrap();
650 let if_str = try_opt!(if_expr.rewrite(context, new_width, Indent::empty()));
652 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
653 let else_expr = else_node.expr.as_ref().unwrap();
654 let else_str = try_opt!(else_expr.rewrite(context, new_width, Indent::empty()));
656 // FIXME: this check shouldn't be necessary. Rewrites should either fail
657 // or wrap to a newline when the object does not fit the width.
658 let fits_line = fixed_cost + pat_expr_str.len() + if_str.len() + else_str.len() <= width;
660 if fits_line && !if_str.contains('\n') && !else_str.contains('\n') {
661 return Some(format!("if {} {{ {} }} else {{ {} }}",
671 // Checks that a block contains no statements, an expression and no comments.
672 fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
673 if !block.stmts.is_empty() || block.expr.is_none() {
677 let snippet = codemap.span_to_snippet(block.span).unwrap();
679 !contains_comment(&snippet)
682 // inter-match-arm-comment-rules:
683 // - all comments following a match arm before the start of the next arm
684 // are about the second arm
685 fn rewrite_match_arm_comment(context: &RewriteContext,
689 arm_indent_str: &str)
691 // The leading "," is not part of the arm-comment
692 let missed_str = match missed_str.find_uncommented(",") {
693 Some(n) => &missed_str[n+1..],
694 None => &missed_str[..],
696 // Nor the trailing "}" which closes the match
697 let missed_str = match missed_str.find_uncommented("}") {
698 Some(n) => &missed_str[..n-1],
699 None => &missed_str[..],
702 let mut result = String::new();
703 // any text not preceeded by a newline is pushed unmodified to the block
704 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
705 result.push_str(&missed_str[..first_brk]);
706 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
708 let first = missed_str.find(|c: char| !c.is_whitespace()).unwrap_or(missed_str.len());
709 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
710 // Excessive vertical whitespace before comment should be preserved
711 // TODO handle vertical whitespace better
714 let missed_str = missed_str[first..].trim();
715 if !missed_str.is_empty() {
716 let comment = try_opt!(rewrite_comment(&missed_str,
722 result.push_str(arm_indent_str);
723 result.push_str(&comment);
729 fn rewrite_match(context: &RewriteContext,
741 let cond_budget = try_opt!(width.checked_sub(8));
742 let cond_str = try_opt!(cond.rewrite(context, cond_budget, offset + 6));
743 let mut result = format!("match {} {{", cond_str);
745 let nested_context = context.nested_context();
746 let arm_indent = nested_context.block_indent + context.overflow_indent;
747 let arm_indent_str = arm_indent.to_string(context.config);
749 let open_brace_pos = span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])),
753 for (i, arm) in arms.iter().enumerate() {
754 // Make sure we get the stuff between arms.
755 let missed_str = if i == 0 {
756 context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
758 context.snippet(mk_sp(arm_end_pos(&arms[i-1]), arm_start_pos(arm)))
760 let comment = try_opt!(rewrite_match_arm_comment(context,
765 result.push_str(&comment);
767 result.push_str(&arm_indent_str);
769 let arm_str = arm.rewrite(&nested_context,
770 context.config.max_width - arm_indent.width(),
772 if let Some(ref arm_str) = arm_str {
773 result.push_str(arm_str);
775 // We couldn't format the arm, just reproduce the source.
776 let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
777 result.push_str(&snippet);
780 let last_comment = context.snippet(mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi));
781 let comment = try_opt!(rewrite_match_arm_comment(context,
786 result.push_str(&comment);
788 result.push_str(&(context.block_indent + context.overflow_indent).to_string(context.config));
793 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
794 let &ast::Arm { ref attrs, ref pats, .. } = arm;
795 if !attrs.is_empty() {
796 return attrs[0].span.lo
802 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
807 impl Rewrite for ast::Arm {
808 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
809 let &ast::Arm { ref attrs, ref pats, ref guard, ref body } = self;
810 let indent_str = offset.to_string(context.config);
812 // FIXME this is all a bit grotty, would be nice to abstract out the
813 // treatment of attributes.
814 let attr_str = if !attrs.is_empty() {
815 // We only use this visitor for the attributes, should we use it for
817 let mut attr_visitor = FmtVisitor::from_codemap(context.codemap, context.config);
818 attr_visitor.block_indent = context.block_indent;
819 attr_visitor.last_pos = attrs[0].span.lo;
820 if attr_visitor.visit_attrs(attrs) {
821 // Attributes included a skip instruction.
822 let snippet = context.snippet(mk_sp(attrs[0].span.lo, body.span.hi));
823 return Some(snippet);
825 attr_visitor.format_missing(pats[0].span.lo);
826 attr_visitor.buffer.to_string()
833 let pat_budget = try_opt!(width.checked_sub(5));
834 let pat_strs = try_opt!(pats.iter()
838 offset.block_indent(context.config))
840 .collect::<Option<Vec<_>>>());
842 let mut total_width = pat_strs.iter().fold(0, |a, p| a + p.len());
844 total_width += (pat_strs.len() - 1) * 3;
846 let mut vertical = total_width > pat_budget || pat_strs.iter().any(|p| p.contains('\n'));
847 if !vertical && context.config.take_source_hints {
848 // If the patterns were previously stacked, keep them stacked.
849 let pat_span = mk_sp(pats[0].span.lo, pats[pats.len() - 1].span.hi);
850 let pat_str = context.snippet(pat_span);
851 vertical = pat_str.find('\n').is_some();
854 let pats_width = if vertical {
855 pat_strs[pat_strs.len() - 1].len()
860 let mut pats_str = String::new();
862 if !pats_str.is_empty() {
864 pats_str.push_str(" |\n");
865 pats_str.push_str(&indent_str);
867 pats_str.push_str(" | ");
870 pats_str.push_str(&p);
873 let guard_str = try_opt!(rewrite_guard(context, guard, width, offset, pats_width));
875 let pats_str = format!("{}{}", pats_str, guard_str);
876 // Where the next text can start.
877 let mut line_start = last_line_width(&pats_str);
878 if !pats_str.contains('\n') {
879 line_start += offset.width();
882 let comma = if let ast::ExprBlock(_) = body.node {
888 // Let's try and get the arm body on the same line as the condition.
890 let same_line_body = if context.config.max_width > line_start + comma.len() + 4 {
891 let budget = context.config.max_width - line_start - comma.len() - 4;
892 let offset = Indent::new(offset.block_indent,
893 line_start + 4 - offset.block_indent);
894 let rewrite = nop_block_collapse(body.rewrite(context, budget, offset), budget);
897 Some(ref body_str) if body_str.len() <= budget || comma.is_empty() =>
898 return Some(format!("{}{} => {}{}",
899 attr_str.trim_left(),
909 if let ast::ExprBlock(_) = body.node {
910 // We're trying to fit a block in, but it still failed, give up.
914 let body_budget = try_opt!(width.checked_sub(context.config.tab_spaces));
915 let next_line_body = nop_block_collapse(body.rewrite(context,
918 .block_indent(context.config)),
921 let body_str = try_opt!(match_arm_heuristic(same_line_body.as_ref().map(|x| &x[..]),
922 next_line_body.as_ref().map(|x| &x[..])));
924 let spacer = match same_line_body {
925 Some(ref body) if body == body_str => " ".to_owned(),
927 offset.block_indent(context.config).to_string(context.config)),
930 Some(format!("{}{} =>{}{},",
931 attr_str.trim_left(),
938 // Takes two possible rewrites for the match arm body and chooses the "nicest".
939 fn match_arm_heuristic<'a>(former: Option<&'a str>, latter: Option<&'a str>) -> Option<&'a str> {
940 match (former, latter) {
941 (f @ Some(..), None) => f,
942 (Some(f), Some(l)) if f.chars().filter(|&c| c == '\n').count() <=
943 l.chars().filter(|&c| c == '\n').count() => {
950 // The `if ...` guard on a match arm.
951 fn rewrite_guard(context: &RewriteContext,
952 guard: &Option<ptr::P<ast::Expr>>,
955 // The amount of space used up on this line for the pattern in
956 // the arm (excludes offset).
957 pattern_width: usize)
959 if let &Some(ref guard) = guard {
960 // First try to fit the guard string on the same line as the pattern.
961 // 4 = ` if `, 5 = ` => {`
962 let overhead = pattern_width + 4 + 5;
963 if overhead < width {
964 let cond_str = guard.rewrite(context, width - overhead, offset + pattern_width + 4);
965 if let Some(cond_str) = cond_str {
966 return Some(format!(" if {}", cond_str));
970 // Not enough space to put the guard after the pattern, try a newline.
971 let overhead = context.config.tab_spaces + 4 + 5;
972 if overhead < width {
973 let cond_str = guard.rewrite(context,
975 offset.block_indent(context.config));
976 if let Some(cond_str) = cond_str {
977 return Some(format!("\n{}if {}",
978 offset.block_indent(context.config).to_string(context.config),
989 fn rewrite_pat_expr(context: &RewriteContext,
990 pat: Option<&ast::Pat>,
993 // Connecting piece between pattern and expression,
994 // *without* trailing space.
999 let pat_offset = offset + matcher.len();
1000 let mut result = match pat {
1002 let pat_budget = try_opt!(width.checked_sub(connector.len() + matcher.len()));
1003 let pat_string = try_opt!(pat.rewrite(context, pat_budget, pat_offset));
1004 format!("{}{}{}", matcher, pat_string, connector)
1006 None => String::new(),
1009 // Consider only the last line of the pat string.
1010 let extra_offset = extra_offset(&result, offset);
1012 // The expression may (partionally) fit on the current line.
1013 if width > extra_offset + 1 {
1014 let spacer = if pat.is_some() {
1020 let expr_rewrite = expr.rewrite(context,
1021 width - extra_offset - spacer.len(),
1022 offset + extra_offset + spacer.len());
1024 if let Some(expr_string) = expr_rewrite {
1025 result.push_str(spacer);
1026 result.push_str(&expr_string);
1027 return Some(result);
1031 // The expression won't fit on the current line, jump to next.
1033 result.push_str(&pat_offset.to_string(context.config));
1035 let expr_rewrite = expr.rewrite(context,
1036 context.config.max_width - pat_offset.width(),
1038 result.push_str(&&try_opt!(expr_rewrite));
1043 fn rewrite_string_lit(context: &RewriteContext,
1048 if !context.config.format_strings {
1049 return Some(context.snippet(span));
1052 let fmt = StringFormat {
1060 config: context.config,
1063 let string_lit = context.snippet(span);
1064 let str_lit = &string_lit[1..string_lit.len() - 1]; // Remove the quote characters.
1066 rewrite_string(str_lit, &fmt)
1069 pub fn rewrite_call<R>(context: &RewriteContext,
1071 args: &[ptr::P<ast::Expr>],
1078 let closure = |callee_max_width| {
1079 rewrite_call_inner(context, callee, callee_max_width, args, span, width, offset)
1083 let max_width = try_opt!(width.checked_sub(2));
1084 binary_search(1, max_width, closure)
1087 fn rewrite_call_inner<R>(context: &RewriteContext,
1089 max_callee_width: usize,
1090 args: &[ptr::P<ast::Expr>],
1094 -> Result<String, Ordering>
1097 let callee = callee.borrow();
1098 // FIXME using byte lens instead of char lens (and probably all over the
1100 let callee_str = match callee.rewrite(context, max_callee_width, offset) {
1102 if !string.contains('\n') && string.len() > max_callee_width {
1103 panic!("{:?} {}", string, max_callee_width);
1108 None => return Err(Ordering::Greater),
1111 let span_lo = span_after(span, "(", context.codemap);
1112 let span = mk_sp(span_lo, span.hi);
1114 let extra_offset = extra_offset(&callee_str, offset);
1116 let remaining_width = match width.checked_sub(extra_offset + 2) {
1118 None => return Err(Ordering::Greater),
1120 let offset = offset + extra_offset + 1;
1121 let block_indent = if args.len() == 1 {
1122 context.block_indent
1126 let inner_context = &RewriteContext { block_indent: block_indent, ..*context };
1128 let items = itemize_list(context.codemap,
1131 |item| item.span.lo,
1132 |item| item.span.hi,
1133 // Take old span when rewrite fails.
1135 item.rewrite(&inner_context, remaining_width, offset)
1136 .unwrap_or(context.snippet(item.span))
1141 let fmt = ListFormatting::for_fn(remaining_width, offset, context.config);
1142 let list_str = match write_list(&items.collect::<Vec<_>>(), &fmt) {
1144 None => return Err(Ordering::Less),
1147 Ok(format!("{}({})", callee_str, list_str))
1150 fn rewrite_paren(context: &RewriteContext,
1151 subexpr: &ast::Expr,
1155 debug!("rewrite_paren, width: {}, offset: {:?}",
1158 // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
1159 // paren on the same line as the subexpr.
1160 let subexpr_str = subexpr.rewrite(context, try_opt!(width.checked_sub(2)), offset + 1);
1161 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1162 subexpr_str.map(|s| format!("({})", s))
1165 fn rewrite_struct_lit<'a>(context: &RewriteContext,
1167 fields: &'a [ast::Field],
1168 base: Option<&'a ast::Expr>,
1173 debug!("rewrite_struct_lit: width {}, offset {:?}",
1176 assert!(!fields.is_empty() || base.is_some());
1178 enum StructLitField<'a> {
1179 Regular(&'a ast::Field),
1180 Base(&'a ast::Expr),
1184 let path_budget = try_opt!(width.checked_sub(2));
1185 let path_str = try_opt!(path.rewrite(context, path_budget, offset));
1187 // Foo { a: Foo } - indent is +3, width is -5.
1188 let h_budget = width.checked_sub(path_str.len() + 5).unwrap_or(0);
1189 let (indent, v_budget) = match context.config.struct_lit_style {
1190 StructLitStyle::Visual => {
1191 (offset + path_str.len() + 3, h_budget)
1193 StructLitStyle::Block => {
1194 // If we are all on one line, then we'll ignore the indent, and we
1195 // have a smaller budget.
1196 let indent = context.block_indent.block_indent(context.config);
1197 let v_budget = context.config.max_width.checked_sub(indent.width()).unwrap_or(0);
1202 let field_iter = fields.into_iter()
1203 .map(StructLitField::Regular)
1204 .chain(base.into_iter().map(StructLitField::Base));
1206 let inner_context = &RewriteContext { block_indent: indent, ..*context };
1208 let items = itemize_list(context.codemap,
1213 StructLitField::Regular(ref field) => field.span.lo,
1214 StructLitField::Base(ref expr) => {
1215 let last_field_hi = fields.last().map_or(span.lo,
1219 let snippet = context.snippet(mk_sp(last_field_hi,
1221 let pos = snippet.find_uncommented("..").unwrap();
1222 last_field_hi + BytePos(pos as u32)
1228 StructLitField::Regular(ref field) => field.span.hi,
1229 StructLitField::Base(ref expr) => expr.span.hi,
1234 StructLitField::Regular(ref field) => {
1235 rewrite_field(inner_context, &field, v_budget, indent)
1236 .unwrap_or(context.snippet(field.span))
1238 StructLitField::Base(ref expr) => {
1241 v_budget.checked_sub(2)
1242 .and_then(|v_budget| {
1243 expr.rewrite(inner_context,
1247 .unwrap_or(context.snippet(expr.span)))
1251 span_after(span, "{", context.codemap),
1254 let mut tactic = match (context.config.struct_lit_style, fields.len()) {
1255 (StructLitStyle::Visual, 1) => ListTactic::HorizontalVertical,
1256 _ => context.config.struct_lit_multiline_style.to_list_tactic(),
1259 if tactic == ListTactic::HorizontalVertical && fields.len() > 1 {
1260 tactic = ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width);
1263 let fmt = ListFormatting {
1266 trailing_separator: if base.is_some() {
1267 SeparatorTactic::Never
1269 context.config.struct_lit_trailing_comma
1274 ends_with_newline: false,
1275 config: context.config,
1277 let fields_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
1279 let format_on_newline = || {
1280 let inner_indent = context.block_indent
1281 .block_indent(context.config)
1282 .to_string(context.config);
1283 let outer_indent = context.block_indent.to_string(context.config);
1284 Some(format!("{} {{\n{}{}\n{}}}",
1291 match (context.config.struct_lit_style,
1292 context.config.struct_lit_multiline_style) {
1293 (StructLitStyle::Block, _) if fields_str.contains('\n') || fields_str.len() > h_budget =>
1294 format_on_newline(),
1295 (StructLitStyle::Block, MultilineStyle::ForceMulti) => format_on_newline(),
1296 _ => Some(format!("{} {{ {} }}", path_str, fields_str)),
1299 // FIXME if context.config.struct_lit_style == Visual, but we run out
1300 // of space, we should fall back to BlockIndent.
1303 fn rewrite_field(context: &RewriteContext,
1308 let name = &field.ident.node.to_string();
1309 let overhead = name.len() + 2;
1310 let expr = field.expr.rewrite(context,
1311 try_opt!(width.checked_sub(overhead)),
1313 expr.map(|s| format!("{}: {}", name, s))
1316 fn rewrite_tuple_lit(context: &RewriteContext,
1317 items: &[ptr::P<ast::Expr>],
1322 debug!("rewrite_tuple_lit: width: {}, offset: {:?}",
1325 let indent = offset + 1;
1326 // In case of length 1, need a trailing comma
1327 if items.len() == 1 {
1329 let budget = try_opt!(width.checked_sub(3));
1330 return items[0].rewrite(context, budget, indent).map(|s| format!("({},)", s));
1333 let items = itemize_list(context.codemap,
1336 |item| item.span.lo,
1337 |item| item.span.hi,
1339 let inner_width = context.config.max_width - indent.width() - 1;
1340 item.rewrite(context, inner_width, indent)
1341 .unwrap_or(context.snippet(item.span))
1343 span.lo + BytePos(1), // Remove parens
1344 span.hi - BytePos(1));
1346 let budget = try_opt!(width.checked_sub(2));
1347 let fmt = ListFormatting::for_fn(budget, indent, context.config);
1348 let list_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
1350 Some(format!("({})", list_str))
1353 fn rewrite_binary_op(context: &RewriteContext,
1360 // FIXME: format comments between operands and operator
1362 let operator_str = context.snippet(op.span);
1364 // Get "full width" rhs and see if it fits on the current line. This
1365 // usually works fairly well since it tends to place operands of
1366 // operations with high precendence close together.
1367 let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
1369 // Second condition is needed in case of line break not caused by a
1370 // shortage of space, but by end-of-line comments, for example.
1371 // Note that this is non-conservative, but its just to see if it's even
1372 // worth trying to put everything on one line.
1373 if rhs_result.len() + 2 + operator_str.len() < width && !rhs_result.contains('\n') {
1374 // 1 = space between lhs expr and operator
1375 if let Some(mut result) = lhs.rewrite(context, width - 1 - operator_str.len(), offset) {
1377 result.push_str(&operator_str);
1380 let remaining_width = width.checked_sub(last_line_width(&result)).unwrap_or(0);
1382 if rhs_result.len() <= remaining_width {
1383 result.push_str(&rhs_result);
1384 return Some(result);
1387 if let Some(rhs_result) = rhs.rewrite(context, remaining_width, offset + result.len()) {
1388 if rhs_result.len() <= remaining_width {
1389 result.push_str(&rhs_result);
1390 return Some(result);
1396 // We have to use multiple lines.
1398 // Re-evaluate the lhs because we have more space now:
1399 let budget = try_opt!(context.config
1401 .checked_sub(offset.width() + 1 + operator_str.len()));
1402 Some(format!("{} {}\n{}{}",
1403 try_opt!(lhs.rewrite(context, budget, offset)),
1405 offset.to_string(context.config),
1409 fn rewrite_unary_prefix(context: &RewriteContext,
1415 expr.rewrite(context,
1416 try_opt!(width.checked_sub(prefix.len())),
1417 offset + prefix.len())
1418 .map(|r| format!("{}{}", prefix, r))
1421 fn rewrite_unary_op(context: &RewriteContext,
1427 // For some reason, an UnOp is not spanned like BinOp!
1428 let operator_str = match *op {
1429 ast::UnOp::UnDeref => "*",
1430 ast::UnOp::UnNot => "!",
1431 ast::UnOp::UnNeg => "-",
1433 rewrite_unary_prefix(context, operator_str, expr, width, offset)
1436 fn rewrite_assignment(context: &RewriteContext,
1439 op: Option<&ast::BinOp>,
1443 let operator_str = match op {
1444 Some(op) => context.snippet(op.span),
1445 None => "=".to_owned(),
1448 // 1 = space between lhs and operator.
1449 let max_width = try_opt!(width.checked_sub(operator_str.len() + 1));
1450 let lhs_str = format!("{} {}",
1451 try_opt!(lhs.rewrite(context, max_width, offset)),
1454 rewrite_assign_rhs(&context, lhs_str, rhs, width, offset)
1457 // The left hand side must contain everything up to, and including, the
1458 // assignment operator.
1459 pub fn rewrite_assign_rhs<S: Into<String>>(context: &RewriteContext,
1465 let mut result = lhs.into();
1467 // 1 = space between operator and rhs.
1468 let max_width = try_opt!(width.checked_sub(result.len() + 1));
1469 let rhs = ex.rewrite(&context, max_width, offset + result.len() + 1);
1474 result.push_str(&new_str)
1477 // Expression did not fit on the same line as the identifier. Retry
1478 // on the next line.
1479 let new_offset = offset.block_indent(context.config);
1480 result.push_str(&format!("\n{}", new_offset.to_string(context.config)));
1482 // FIXME: we probably should related max_width to width instead of config.max_width
1483 // where is the 1 coming from anyway?
1484 let max_width = try_opt!(context.config.max_width.checked_sub(new_offset.width() + 1));
1485 let rhs_indent = Indent::new(context.config.tab_spaces, 0);
1486 let overflow_context = context.overflow_context(rhs_indent);
1487 let rhs = ex.rewrite(&overflow_context, max_width, new_offset);
1489 result.push_str(&&try_opt!(rhs));
1496 fn rewrite_expr_addrof(context: &RewriteContext,
1497 mutability: ast::Mutability,
1502 let operator_str = match mutability {
1503 ast::Mutability::MutImmutable => "&",
1504 ast::Mutability::MutMutable => "&mut ",
1506 rewrite_unary_prefix(context, operator_str, expr, width, offset)