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 std::iter::ExactSizeIterator;
18 use {Indent, Spanned};
19 use rewrite::{Rewrite, RewriteContext};
20 use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic,
21 DefinitiveListTactic, definitive_tactic, ListItem, format_item_list};
22 use string::{StringFormat, rewrite_string};
23 use utils::{CodeMapSpanUtils, extra_offset, last_line_width, wrap_str, binary_search,
24 first_line_width, semicolon_for_stmt, trimmed_last_line_width};
25 use visitor::FmtVisitor;
26 use config::{Config, StructLitStyle, MultilineStyle};
27 use comment::{FindUncommented, rewrite_comment, contains_comment, recover_comment_removed};
28 use types::rewrite_path;
29 use items::{span_lo_for_arg, span_hi_for_arg};
30 use chains::rewrite_chain;
31 use macros::rewrite_macro;
33 use syntax::{ast, ptr};
34 use syntax::codemap::{CodeMap, Span, BytePos, mk_sp};
35 use syntax::visit::Visitor;
37 impl Rewrite for ast::Expr {
38 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
39 let result = match self.node {
40 ast::ExprKind::Vec(ref expr_vec) => {
41 rewrite_array(expr_vec.iter().map(|e| &**e),
42 mk_sp(context.codemap.span_after(self.span, "["), self.span.hi),
47 ast::ExprKind::Lit(ref l) => {
49 ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
50 rewrite_string_lit(context, l.span, width, offset)
53 wrap_str(context.snippet(self.span),
54 context.config.max_width,
60 ast::ExprKind::Call(ref callee, ref args) => {
61 let inner_span = mk_sp(callee.span.hi, self.span.hi);
62 rewrite_call(context, &**callee, args, inner_span, width, offset)
64 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, width, offset),
65 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
66 rewrite_binary_op(context, op, lhs, rhs, width, offset)
68 ast::ExprKind::Unary(ref op, ref subexpr) => {
69 rewrite_unary_op(context, op, subexpr, width, offset)
71 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
72 rewrite_struct_lit(context,
75 base.as_ref().map(|e| &**e),
80 ast::ExprKind::Tup(ref items) => {
81 rewrite_tuple(context,
82 items.iter().map(|x| &**x),
87 ast::ExprKind::While(ref cond, ref block, label) => {
88 Loop::new_while(None, cond, block, label).rewrite(context, width, offset)
90 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => {
91 Loop::new_while(Some(pat), cond, block, label).rewrite(context, width, offset)
93 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
94 Loop::new_for(pat, cond, block, label).rewrite(context, width, offset)
96 ast::ExprKind::Loop(ref block, label) => {
97 Loop::new_loop(block, label).rewrite(context, width, offset)
99 ast::ExprKind::Block(ref block) => block.rewrite(context, width, offset),
100 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
101 rewrite_if_else(context,
104 else_block.as_ref().map(|e| &**e),
111 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
112 rewrite_if_else(context,
115 else_block.as_ref().map(|e| &**e),
122 ast::ExprKind::Match(ref cond, ref arms) => {
123 rewrite_match(context, cond, arms, width, offset, self.span)
125 ast::ExprKind::Path(ref qself, ref path) => {
126 rewrite_path(context, true, qself.as_ref(), path, width, offset)
128 ast::ExprKind::Assign(ref lhs, ref rhs) => {
129 rewrite_assignment(context, lhs, rhs, None, width, offset)
131 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
132 rewrite_assignment(context, lhs, rhs, Some(op), width, offset)
134 ast::ExprKind::Again(ref opt_ident) => {
135 let id_str = match *opt_ident {
136 Some(ident) => format!(" {}", ident.node),
137 None => String::new(),
139 Some(format!("continue{}", id_str))
141 ast::ExprKind::Break(ref opt_ident) => {
142 let id_str = match *opt_ident {
143 Some(ident) => format!(" {}", ident.node),
144 None => String::new(),
146 Some(format!("break{}", id_str))
148 ast::ExprKind::Closure(capture, ref fn_decl, ref body) => {
149 rewrite_closure(capture, fn_decl, body, self.span, context, width, offset)
151 ast::ExprKind::Field(..) |
152 ast::ExprKind::TupField(..) |
153 ast::ExprKind::MethodCall(..) => rewrite_chain(self, context, width, offset),
154 ast::ExprKind::Mac(ref mac) => {
155 // Failure to rewrite a marco should not imply failure to
156 // rewrite the expression.
157 rewrite_macro(mac, None, context, width, offset).or_else(|| {
158 wrap_str(context.snippet(self.span),
159 context.config.max_width,
164 ast::ExprKind::Ret(None) => {
165 wrap_str("return".to_owned(), context.config.max_width, width, offset)
167 ast::ExprKind::Ret(Some(ref expr)) => {
168 rewrite_unary_prefix(context, "return ", &**expr, width, offset)
170 ast::ExprKind::Box(ref expr) => {
171 rewrite_unary_prefix(context, "box ", &**expr, width, offset)
173 ast::ExprKind::AddrOf(mutability, ref expr) => {
174 rewrite_expr_addrof(context, mutability, expr, width, offset)
176 ast::ExprKind::Cast(ref expr, ref ty) => {
177 rewrite_pair(&**expr, &**ty, "", " as ", "", context, width, offset)
179 ast::ExprKind::Index(ref expr, ref index) => {
180 rewrite_pair(&**expr, &**index, "", "[", "]", context, width, offset)
182 ast::ExprKind::Repeat(ref expr, ref repeats) => {
183 rewrite_pair(&**expr, &**repeats, "[", "; ", "]", context, width, offset)
185 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
186 let delim = match limits {
187 ast::RangeLimits::HalfOpen => "..",
188 ast::RangeLimits::Closed => "...",
191 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
192 (Some(ref lhs), Some(ref rhs)) => {
193 rewrite_pair(&**lhs, &**rhs, "", delim, "", context, width, offset)
195 (None, Some(ref rhs)) => {
196 rewrite_unary_prefix(context, delim, &**rhs, width, offset)
198 (Some(ref lhs), None) => {
200 try_opt!(lhs.rewrite(context,
201 try_opt!(width.checked_sub(delim.len())),
205 (None, None) => wrap_str(delim.into(), context.config.max_width, width, offset),
208 // We do not format these expressions yet, but they should still
209 // satisfy our width restrictions.
210 ast::ExprKind::InPlace(..) |
211 ast::ExprKind::InlineAsm(..) |
212 // TODO(#848): Handle type ascription
213 ast::ExprKind::Type(_, _) |
214 // TODO(#867): Handle try shorthand
215 ast::ExprKind::Try(_) => {
216 wrap_str(context.snippet(self.span),
217 context.config.max_width,
222 result.and_then(|res| recover_comment_removed(res, self.span, context, width, offset))
226 pub fn rewrite_pair<LHS, RHS>(lhs: &LHS,
231 context: &RewriteContext,
238 let max_width = try_opt!(width.checked_sub(prefix.len() + infix.len() + suffix.len()));
240 binary_search(1, max_width, |lhs_budget| {
241 let lhs_offset = offset + prefix.len();
242 let lhs_str = match lhs.rewrite(context, lhs_budget, lhs_offset) {
243 Some(result) => result,
244 None => return Err(Ordering::Greater),
247 let last_line_width = last_line_width(&lhs_str);
248 let rhs_budget = match max_width.checked_sub(last_line_width) {
250 None => return Err(Ordering::Less),
252 let rhs_indent = offset + last_line_width + prefix.len() + infix.len();
254 let rhs_str = match rhs.rewrite(context, rhs_budget, rhs_indent) {
255 Some(result) => result,
256 None => return Err(Ordering::Less),
259 Ok(format!("{}{}{}{}{}", prefix, lhs_str, infix, rhs_str, suffix))
263 pub fn rewrite_array<'a, I>(expr_iter: I,
265 context: &RewriteContext,
269 where I: Iterator<Item = &'a ast::Expr>
272 let offset = offset + 1;
273 let inner_context = &RewriteContext { block_indent: offset, ..*context };
274 let max_item_width = try_opt!(width.checked_sub(2));
275 let items = itemize_list(context.codemap,
281 |item| item.rewrite(&inner_context, max_item_width, offset),
284 .collect::<Vec<_>>();
286 let has_long_item = try_opt!(items.iter()
287 .map(|li| li.item.as_ref().map(|s| s.len() > 10))
289 |acc, x| acc.and_then(|y| x.map(|x| x || y))));
291 let tactic = if has_long_item || items.iter().any(ListItem::is_multiline) {
292 definitive_tactic(&items, ListTactic::HorizontalVertical, max_item_width)
294 DefinitiveListTactic::Mixed
297 let fmt = ListFormatting {
300 trailing_separator: SeparatorTactic::Never,
302 width: max_item_width,
303 ends_with_newline: false,
304 config: context.config,
306 let list_str = try_opt!(write_list(&items, &fmt));
308 Some(format!("[{}]", list_str))
311 // This functions is pretty messy because of the wrapping and unwrapping of
312 // expressions into and from blocks. See rust issue #27872.
313 fn rewrite_closure(capture: ast::CaptureBy,
314 fn_decl: &ast::FnDecl,
317 context: &RewriteContext,
321 let mover = if capture == ast::CaptureBy::Value {
326 let offset = offset + mover.len();
328 // 4 = "|| {".len(), which is overconservative when the closure consists of
329 // a single expression.
330 let budget = try_opt!(width.checked_sub(4 + mover.len()));
332 let argument_offset = offset + 1;
333 let ret_str = try_opt!(fn_decl.output.rewrite(context, budget, argument_offset));
334 // 1 = space between arguments and return type.
335 let horizontal_budget = budget.checked_sub(ret_str.len() + 1).unwrap_or(0);
337 let arg_items = itemize_list(context.codemap,
338 fn_decl.inputs.iter(),
340 |arg| span_lo_for_arg(arg),
341 |arg| span_hi_for_arg(arg),
342 |arg| arg.rewrite(context, budget, argument_offset),
343 context.codemap.span_after(span, "|"),
345 let item_vec = arg_items.collect::<Vec<_>>();
346 let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
347 let budget = match tactic {
348 DefinitiveListTactic::Horizontal => horizontal_budget,
352 let fmt = ListFormatting {
355 trailing_separator: SeparatorTactic::Never,
356 indent: argument_offset,
358 ends_with_newline: false,
359 config: context.config,
361 let list_str = try_opt!(write_list(&item_vec, &fmt));
362 let mut prefix = format!("{}|{}|", mover, list_str);
364 if !ret_str.is_empty() {
365 if prefix.contains('\n') {
367 prefix.push_str(&argument_offset.to_string(context.config));
371 prefix.push_str(&ret_str);
374 // Try to format closure body as a single line expression without braces.
375 if is_simple_block(body, context.codemap) && !prefix.contains('\n') {
376 let (spacer, closer) = if ret_str.is_empty() {
381 let expr = body.expr.as_ref().unwrap();
382 // All closure bodies are blocks in the eyes of the AST, but we may not
383 // want to unwrap them when they only contain a single expression.
384 let inner_expr = match expr.node {
385 ast::ExprKind::Block(ref inner) if inner.stmts.is_empty() && inner.expr.is_some() &&
386 inner.rules == ast::BlockCheckMode::Default => {
387 inner.expr.as_ref().unwrap()
391 let extra_offset = extra_offset(&prefix, offset) + spacer.len();
392 let budget = try_opt!(width.checked_sub(extra_offset + closer.len()));
393 let rewrite = inner_expr.rewrite(context, budget, offset + extra_offset);
395 // Checks if rewrite succeeded and fits on a single line.
396 let accept_rewrite = rewrite.as_ref().map_or(false, |result| !result.contains('\n'));
399 return Some(format!("{}{}{}{}", prefix, spacer, rewrite.unwrap(), closer));
403 // We couldn't format the closure body as a single line expression; fall
404 // back to block formatting.
405 let body_rewrite = body.expr
407 .and_then(|body_expr| {
408 if let ast::ExprKind::Block(ref inner) = body_expr.node {
409 Some(inner.rewrite(&context, 2, Indent::empty()))
414 .unwrap_or_else(|| body.rewrite(&context, 2, Indent::empty()));
416 Some(format!("{} {}", prefix, try_opt!(body_rewrite)))
419 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
420 block_str.map(|block_str| {
421 if block_str.starts_with("{") && budget >= 2 &&
422 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2) {
430 impl Rewrite for ast::Block {
431 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
432 let user_str = context.snippet(self.span);
433 if user_str == "{}" && width >= 2 {
434 return Some(user_str);
437 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
438 visitor.block_indent = context.block_indent;
440 let prefix = match self.rules {
441 ast::BlockCheckMode::Unsafe(..) => {
442 let snippet = context.snippet(self.span);
443 let open_pos = try_opt!(snippet.find_uncommented("{"));
444 visitor.last_pos = self.span.lo + BytePos(open_pos as u32);
446 // Extract comment between unsafe and block start.
447 let trimmed = &snippet[6..open_pos].trim();
449 let prefix = if !trimmed.is_empty() {
450 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
451 let budget = try_opt!(width.checked_sub(9));
452 format!("unsafe {} ",
453 try_opt!(rewrite_comment(trimmed,
462 if is_simple_block(self, context.codemap) && prefix.len() < width {
466 .rewrite(context, width - prefix.len(), offset);
467 if let Some(ref expr_str) = body {
468 let result = format!("{}{{ {} }}", prefix, expr_str);
469 if result.len() <= width && !result.contains('\n') {
477 ast::BlockCheckMode::Default => {
478 visitor.last_pos = self.span.lo;
484 visitor.visit_block(self);
486 Some(format!("{}{}", prefix, visitor.buffer))
490 impl Rewrite for ast::Stmt {
491 fn rewrite(&self, context: &RewriteContext, _width: usize, offset: Indent) -> Option<String> {
492 let result = match self.node {
493 ast::StmtKind::Decl(ref decl, _) => {
494 if let ast::DeclKind::Local(ref local) = decl.node {
495 local.rewrite(context, context.config.max_width, offset)
500 ast::StmtKind::Expr(ref ex, _) |
501 ast::StmtKind::Semi(ref ex, _) => {
502 let suffix = if semicolon_for_stmt(self) {
509 context.config.max_width - offset.width() - suffix.len(),
513 ast::StmtKind::Mac(..) => None,
515 result.and_then(|res| recover_comment_removed(res, self.span, context, _width, offset))
519 // Abstraction over for, while and loop expressions
521 cond: Option<&'a ast::Expr>,
522 block: &'a ast::Block,
523 label: Option<ast::Ident>,
524 pat: Option<&'a ast::Pat>,
531 fn new_loop(block: &'a ast::Block, label: Option<ast::Ident>) -> Loop<'a> {
543 fn new_while(pat: Option<&'a ast::Pat>,
545 block: &'a ast::Block,
546 label: Option<ast::Ident>)
562 fn new_for(pat: &'a ast::Pat,
564 block: &'a ast::Block,
565 label: Option<ast::Ident>)
579 impl<'a> Rewrite for Loop<'a> {
580 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
581 let label_string = rewrite_label(self.label);
583 let inner_width = try_opt!(width.checked_sub(self.keyword.len() + 2 + label_string.len()));
584 let inner_offset = offset + self.keyword.len() + label_string.len();
586 let pat_expr_string = match self.cond {
588 try_opt!(rewrite_pat_expr(context,
596 None => String::new(),
599 // FIXME: this drops any comment between "loop" and the block.
601 .rewrite(context, width, offset)
612 fn rewrite_label(label: Option<ast::Ident>) -> String {
614 Some(ident) => format!("{}: ", ident),
615 None => "".to_owned(),
619 fn extract_comment(span: Span,
620 context: &RewriteContext,
624 let comment_str = context.snippet(span);
625 if contains_comment(&comment_str) {
626 let comment = try_opt!(rewrite_comment(comment_str.trim(),
631 Some(format!("\n{indent}{}\n{indent}",
633 indent = offset.to_string(context.config)))
639 // Rewrites if-else blocks. If let Some(_) = pat, the expression is
640 // treated as an if-let-else expression.
641 fn rewrite_if_else(context: &RewriteContext,
643 if_block: &ast::Block,
644 else_block_opt: Option<&ast::Expr>,
646 pat: Option<&ast::Pat>,
649 allow_single_line: bool)
651 // 3 = "if ", 2 = " {"
652 let pat_expr_string = try_opt!(rewrite_pat_expr(context,
657 try_opt!(width.checked_sub(3 + 2)),
660 // Try to format if-else on single line.
661 if allow_single_line && context.config.single_line_if_else {
662 let trial = single_line_if_else(context, &pat_expr_string, if_block, else_block_opt, width);
669 let if_block_string = try_opt!(if_block.rewrite(context, width, offset));
671 let between_if_cond = mk_sp(context.codemap.span_after(span, "if"),
672 pat.map_or(cond.span.lo,
673 |_| context.codemap.span_before(span, "let")));
675 let between_if_cond_comment = extract_comment(between_if_cond, &context, offset, width);
677 let after_cond_comment = extract_comment(mk_sp(cond.span.hi, if_block.span.lo),
682 let mut result = format!("if{}{}{}{}",
683 between_if_cond_comment.as_ref().map_or(" ", |str| &**str),
685 after_cond_comment.as_ref().map_or(" ", |str| &**str),
688 if let Some(else_block) = else_block_opt {
689 let rewrite = match else_block.node {
690 // If the else expression is another if-else expression, prevent it
691 // from being formatted on a single line.
692 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
693 rewrite_if_else(context,
696 next_else_block.as_ref().map(|e| &**e),
697 mk_sp(else_block.span.lo, span.hi),
703 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
704 rewrite_if_else(context,
707 next_else_block.as_ref().map(|e| &**e),
708 mk_sp(else_block.span.lo, span.hi),
714 _ => else_block.rewrite(context, width, offset),
717 let between_if_else_block = mk_sp(if_block.span.hi,
718 context.codemap.span_before(mk_sp(if_block.span.hi,
721 let between_if_else_block_comment = extract_comment(between_if_else_block,
726 let after_else = mk_sp(context.codemap
727 .span_after(mk_sp(if_block.span.hi, else_block.span.lo),
730 let after_else_comment = extract_comment(after_else, &context, offset, width);
732 try_opt!(write!(&mut result,
734 between_if_else_block_comment.as_ref().map_or(" ", |str| &**str),
735 after_else_comment.as_ref().map_or(" ", |str| &**str))
737 result.push_str(&&try_opt!(rewrite));
743 fn single_line_if_else(context: &RewriteContext,
745 if_node: &ast::Block,
746 else_block_opt: Option<&ast::Expr>,
749 let else_block = try_opt!(else_block_opt);
750 let fixed_cost = "if { } else { }".len();
752 if let ast::ExprKind::Block(ref else_node) = else_block.node {
753 if !is_simple_block(if_node, context.codemap) ||
754 !is_simple_block(else_node, context.codemap) || pat_expr_str.contains('\n') {
758 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
759 let if_expr = if_node.expr.as_ref().unwrap();
760 let if_str = try_opt!(if_expr.rewrite(context, new_width, Indent::empty()));
762 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
763 let else_expr = else_node.expr.as_ref().unwrap();
764 let else_str = try_opt!(else_expr.rewrite(context, new_width, Indent::empty()));
766 // FIXME: this check shouldn't be necessary. Rewrites should either fail
767 // or wrap to a newline when the object does not fit the width.
768 let fits_line = fixed_cost + pat_expr_str.len() + if_str.len() + else_str.len() <= width;
770 if fits_line && !if_str.contains('\n') && !else_str.contains('\n') {
771 return Some(format!("if {} {{ {} }} else {{ {} }}",
781 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
782 let snippet = codemap.span_to_snippet(block.span).unwrap();
783 contains_comment(&snippet)
786 // Checks that a block contains no statements, an expression and no comments.
787 // FIXME: incorrectly returns false when comment is contained completely within
789 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
790 block.stmts.is_empty() && block.expr.is_some() && !block_contains_comment(block, codemap)
793 /// Checks whether a block contains at most one statement or expression, and no comments.
794 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
795 (block.stmts.is_empty() || (block.stmts.len() == 1 && block.expr.is_none())) &&
796 !block_contains_comment(block, codemap)
799 /// Checks whether a block contains no statements, expressions, or comments.
800 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
801 block.stmts.is_empty() && block.expr.is_none() && !block_contains_comment(block, codemap)
804 fn is_unsafe_block(block: &ast::Block) -> bool {
805 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
812 // inter-match-arm-comment-rules:
813 // - all comments following a match arm before the start of the next arm
814 // are about the second arm
815 fn rewrite_match_arm_comment(context: &RewriteContext,
819 arm_indent_str: &str)
821 // The leading "," is not part of the arm-comment
822 let missed_str = match missed_str.find_uncommented(",") {
823 Some(n) => &missed_str[n + 1..],
824 None => &missed_str[..],
827 let mut result = String::new();
828 // any text not preceeded by a newline is pushed unmodified to the block
829 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
830 result.push_str(&missed_str[..first_brk]);
831 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
833 let first = missed_str.find(|c: char| !c.is_whitespace()).unwrap_or(missed_str.len());
834 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
835 // Excessive vertical whitespace before comment should be preserved
836 // TODO handle vertical whitespace better
839 let missed_str = missed_str[first..].trim();
840 if !missed_str.is_empty() {
841 let comment = try_opt!(rewrite_comment(&missed_str,
847 result.push_str(arm_indent_str);
848 result.push_str(&comment);
854 fn rewrite_match(context: &RewriteContext,
866 let cond_budget = try_opt!(width.checked_sub(8));
867 let cond_str = try_opt!(cond.rewrite(context, cond_budget, offset + 6));
868 let mut result = format!("match {} {{", cond_str);
870 let nested_context = context.nested_context();
871 let arm_indent = nested_context.block_indent;
872 let arm_indent_str = arm_indent.to_string(context.config);
874 let open_brace_pos = context.codemap
875 .span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])), "{");
877 for (i, arm) in arms.iter().enumerate() {
878 // Make sure we get the stuff between arms.
879 let missed_str = if i == 0 {
880 context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
882 context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
884 let comment = try_opt!(rewrite_match_arm_comment(context,
889 result.push_str(&comment);
891 result.push_str(&arm_indent_str);
893 let arm_str = arm.rewrite(&nested_context,
894 context.config.max_width - arm_indent.width(),
896 if let Some(ref arm_str) = arm_str {
897 result.push_str(arm_str);
899 // We couldn't format the arm, just reproduce the source.
900 let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
901 result.push_str(&snippet);
902 result.push_str(arm_comma(&context.config, &arm, &arm.body));
905 // BytePos(1) = closing match brace.
906 let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
907 let last_comment = context.snippet(last_span);
908 let comment = try_opt!(rewrite_match_arm_comment(context,
913 result.push_str(&comment);
915 result.push_str(&context.block_indent.to_string(context.config));
920 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
921 let &ast::Arm { ref attrs, ref pats, .. } = arm;
922 if !attrs.is_empty() {
923 return attrs[0].span.lo;
929 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
933 fn arm_comma(config: &Config, arm: &ast::Arm, body: &ast::Expr) -> &'static str {
934 if !config.match_wildcard_trailing_comma {
935 if arm.pats.len() == 1 && arm.pats[0].node == ast::PatKind::Wild && arm.guard.is_none() {
940 if config.match_block_trailing_comma {
942 } else if let ast::ExprKind::Block(ref block) = body.node {
943 if let ast::BlockCheckMode::Default = block.rules {
954 impl Rewrite for ast::Arm {
955 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
956 let &ast::Arm { ref attrs, ref pats, ref guard, ref body } = self;
958 // FIXME this is all a bit grotty, would be nice to abstract out the
959 // treatment of attributes.
960 let attr_str = if !attrs.is_empty() {
961 // We only use this visitor for the attributes, should we use it for
963 let mut attr_visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
964 attr_visitor.block_indent = context.block_indent;
965 attr_visitor.last_pos = attrs[0].span.lo;
966 if attr_visitor.visit_attrs(attrs) {
967 // Attributes included a skip instruction.
970 attr_visitor.format_missing(pats[0].span.lo);
971 attr_visitor.buffer.to_string()
978 let pat_budget = try_opt!(width.checked_sub(5));
979 let pat_strs = try_opt!(pats.iter()
980 .map(|p| p.rewrite(context, pat_budget, offset))
981 .collect::<Option<Vec<_>>>());
983 let all_simple = pat_strs.iter().all(|p| pat_is_simple(&p));
984 let items: Vec<_> = pat_strs.into_iter().map(|s| ListItem::from_str(s)).collect();
985 let fmt = ListFormatting {
986 tactic: if all_simple {
987 DefinitiveListTactic::Mixed
989 DefinitiveListTactic::Vertical
992 trailing_separator: SeparatorTactic::Never,
995 ends_with_newline: false,
996 config: context.config,
998 let pats_str = try_opt!(write_list(items, &fmt));
1000 let budget = if pats_str.contains('\n') {
1001 context.config.max_width - offset.width()
1006 let guard_str = try_opt!(rewrite_guard(context,
1010 trimmed_last_line_width(&pats_str)));
1012 let pats_str = format!("{}{}", pats_str, guard_str);
1013 // Where the next text can start.
1014 let mut line_start = last_line_width(&pats_str);
1015 if !pats_str.contains('\n') {
1016 line_start += offset.width();
1019 let body = match **body {
1020 ast::Expr { node: ast::ExprKind::Block(ref block), .. }
1021 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) &&
1022 context.config.wrap_match_arms => block.expr.as_ref().map(|e| &**e).unwrap(),
1026 let comma = arm_comma(&context.config, self, body);
1028 // Let's try and get the arm body on the same line as the condition.
1030 if context.config.max_width > line_start + comma.len() + 4 {
1031 let budget = context.config.max_width - line_start - comma.len() - 4;
1032 let offset = Indent::new(offset.block_indent, line_start + 4 - offset.block_indent);
1033 let rewrite = nop_block_collapse(body.rewrite(context, budget, offset), budget);
1034 let is_block = if let ast::ExprKind::Block(..) = body.node {
1041 Some(ref body_str) if !body_str.contains('\n') || !context.config.wrap_match_arms ||
1043 return Some(format!("{}{} => {}{}",
1044 attr_str.trim_left(),
1053 // FIXME: we're doing a second rewrite of the expr; This may not be
1055 let body_budget = try_opt!(width.checked_sub(context.config.tab_spaces));
1056 let indent = context.block_indent.block_indent(context.config);
1057 let inner_context = &RewriteContext { block_indent: indent, ..*context };
1058 let next_line_body = try_opt!(nop_block_collapse(body.rewrite(inner_context,
1062 let indent_str = offset.block_indent(context.config).to_string(context.config);
1063 let (body_prefix, body_suffix) = if context.config.wrap_match_arms {
1064 if context.config.match_block_trailing_comma {
1073 Some(format!("{}{} =>{}\n{}{}\n{}{}",
1074 attr_str.trim_left(),
1079 offset.to_string(context.config),
1084 // A pattern is simple if it is very short or it is short-ish and just a path.
1085 // E.g. `Foo::Bar` is simple, but `Foo(..)` is not.
1086 fn pat_is_simple(pat_str: &str) -> bool {
1087 pat_str.len() <= 16 ||
1088 (pat_str.len() <= 24 && pat_str.chars().all(|c| c.is_alphabetic() || c == ':'))
1091 // The `if ...` guard on a match arm.
1092 fn rewrite_guard(context: &RewriteContext,
1093 guard: &Option<ptr::P<ast::Expr>>,
1096 // The amount of space used up on this line for the pattern in
1097 // the arm (excludes offset).
1098 pattern_width: usize)
1100 if let Some(ref guard) = *guard {
1101 // First try to fit the guard string on the same line as the pattern.
1102 // 4 = ` if `, 5 = ` => {`
1103 let overhead = pattern_width + 4 + 5;
1104 if overhead < width {
1105 let cond_str = guard.rewrite(context, width - overhead, offset + pattern_width + 4);
1106 if let Some(cond_str) = cond_str {
1107 return Some(format!(" if {}", cond_str));
1111 // Not enough space to put the guard after the pattern, try a newline.
1112 let overhead = offset.block_indent(context.config).width() + 4 + 5;
1113 if overhead < width {
1114 let cond_str = guard.rewrite(context,
1117 offset.block_indent(context.config) + 3);
1118 if let Some(cond_str) = cond_str {
1119 return Some(format!("\n{}if {}",
1120 offset.block_indent(context.config).to_string(context.config),
1131 fn rewrite_pat_expr(context: &RewriteContext,
1132 pat: Option<&ast::Pat>,
1135 // Connecting piece between pattern and expression,
1136 // *without* trailing space.
1141 let pat_offset = offset + matcher.len();
1142 let mut result = match pat {
1144 let pat_budget = try_opt!(width.checked_sub(connector.len() + matcher.len()));
1145 let pat_string = try_opt!(pat.rewrite(context, pat_budget, pat_offset));
1146 format!("{}{}{}", matcher, pat_string, connector)
1148 None => String::new(),
1151 // Consider only the last line of the pat string.
1152 let extra_offset = extra_offset(&result, offset);
1154 // The expression may (partionally) fit on the current line.
1155 if width > extra_offset + 1 {
1156 let spacer = if pat.is_some() {
1162 let expr_rewrite = expr.rewrite(context,
1163 width - extra_offset - spacer.len(),
1164 offset + extra_offset + spacer.len());
1166 if let Some(expr_string) = expr_rewrite {
1167 result.push_str(spacer);
1168 result.push_str(&expr_string);
1169 return Some(result);
1173 // The expression won't fit on the current line, jump to next.
1175 result.push_str(&pat_offset.to_string(context.config));
1177 let expr_rewrite = expr.rewrite(context,
1178 context.config.max_width - pat_offset.width(),
1180 result.push_str(&&try_opt!(expr_rewrite));
1185 fn rewrite_string_lit(context: &RewriteContext,
1190 let string_lit = context.snippet(span);
1192 if !context.config.format_strings && !context.config.force_format_strings {
1193 return Some(string_lit);
1196 if !context.config.force_format_strings &&
1197 !string_requires_rewrite(context, span, &string_lit, width, offset) {
1198 return Some(string_lit);
1201 let fmt = StringFormat {
1209 config: context.config,
1212 // Remove the quote characters.
1213 let str_lit = &string_lit[1..string_lit.len() - 1];
1215 rewrite_string(str_lit, &fmt)
1218 fn string_requires_rewrite(context: &RewriteContext,
1224 if context.codemap.lookup_char_pos(span.lo).col.0 != offset.width() {
1228 for (i, line) in string.lines().enumerate() {
1230 if line.len() > width {
1234 if line.len() > width + offset.width() {
1243 pub fn rewrite_call<R>(context: &RewriteContext,
1245 args: &[ptr::P<ast::Expr>],
1252 let closure = |callee_max_width| {
1253 rewrite_call_inner(context, callee, callee_max_width, args, span, width, offset)
1257 let max_width = try_opt!(width.checked_sub(2));
1258 binary_search(1, max_width, closure)
1261 fn rewrite_call_inner<R>(context: &RewriteContext,
1263 max_callee_width: usize,
1264 args: &[ptr::P<ast::Expr>],
1268 -> Result<String, Ordering>
1271 let callee = callee.borrow();
1272 // FIXME using byte lens instead of char lens (and probably all over the
1274 let callee_str = match callee.rewrite(context, max_callee_width, offset) {
1276 if !string.contains('\n') && string.len() > max_callee_width {
1277 panic!("{:?} {}", string, max_callee_width);
1282 None => return Err(Ordering::Greater),
1285 let span_lo = context.codemap.span_after(span, "(");
1286 let span = mk_sp(span_lo, span.hi);
1288 let extra_offset = extra_offset(&callee_str, offset);
1290 let remaining_width = match width.checked_sub(extra_offset + 2) {
1292 None => return Err(Ordering::Greater),
1294 let offset = offset + extra_offset + 1;
1295 let arg_count = args.len();
1296 let block_indent = if arg_count == 1 {
1297 context.block_indent
1301 let inner_context = &RewriteContext { block_indent: block_indent, ..*context };
1303 let items = itemize_list(context.codemap,
1306 |item| item.span.lo,
1307 |item| item.span.hi,
1308 |item| item.rewrite(&inner_context, remaining_width, offset),
1311 let mut item_vec: Vec<_> = items.collect();
1313 // Try letting the last argument overflow to the next line with block
1314 // indentation. If its first line fits on one line with the other arguments,
1315 // we format the function arguments horizontally.
1316 let overflow_last = match args.last().map(|x| &x.node) {
1317 Some(&ast::ExprKind::Closure(..)) |
1318 Some(&ast::ExprKind::Block(..)) if arg_count > 1 => true,
1320 } && context.config.chains_overflow_last;
1322 let mut orig_last = None;
1323 let mut placeholder = None;
1325 // Replace the last item with its first line to see if it fits with
1328 let inner_context = &RewriteContext { block_indent: context.block_indent, ..*context };
1329 let rewrite = args.last().unwrap().rewrite(&inner_context, remaining_width, offset);
1331 if let Some(rewrite) = rewrite {
1332 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
1333 placeholder = Some(rewrite);
1335 swap(&mut item_vec[arg_count - 1].item, &mut orig_last);
1336 item_vec[arg_count - 1].item = rewrite_first_line;
1340 let tactic = definitive_tactic(&item_vec,
1341 ListTactic::LimitedHorizontalVertical(context.config
1345 // Replace the stub with the full overflowing last argument if the rewrite
1346 // succeeded and its first line fits with the other arguments.
1347 match (overflow_last, tactic, placeholder) {
1348 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
1349 item_vec[arg_count - 1].item = placeholder;
1352 item_vec[arg_count - 1].item = orig_last;
1357 let fmt = ListFormatting {
1360 trailing_separator: SeparatorTactic::Never,
1363 ends_with_newline: false,
1364 config: context.config,
1367 let list_str = match write_list(&item_vec, &fmt) {
1369 None => return Err(Ordering::Less),
1372 Ok(format!("{}({})", callee_str, list_str))
1375 fn rewrite_paren(context: &RewriteContext,
1376 subexpr: &ast::Expr,
1380 debug!("rewrite_paren, width: {}, offset: {:?}", width, offset);
1381 // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
1382 // paren on the same line as the subexpr.
1383 let subexpr_str = subexpr.rewrite(context, try_opt!(width.checked_sub(2)), offset + 1);
1384 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1385 subexpr_str.map(|s| format!("({})", s))
1388 fn rewrite_struct_lit<'a>(context: &RewriteContext,
1390 fields: &'a [ast::Field],
1391 base: Option<&'a ast::Expr>,
1396 debug!("rewrite_struct_lit: width {}, offset {:?}", width, offset);
1398 enum StructLitField<'a> {
1399 Regular(&'a ast::Field),
1400 Base(&'a ast::Expr),
1404 let path_budget = try_opt!(width.checked_sub(2));
1405 let path_str = try_opt!(rewrite_path(context, true, None, path, path_budget, offset));
1407 // Foo { a: Foo } - indent is +3, width is -5.
1408 let h_budget = width.checked_sub(path_str.len() + 5).unwrap_or(0);
1409 // The 1 taken from the v_budget is for the comma.
1410 let (indent, v_budget) = match context.config.struct_lit_style {
1411 StructLitStyle::Visual => (offset + path_str.len() + 3, h_budget),
1412 StructLitStyle::Block => {
1413 // If we are all on one line, then we'll ignore the indent, and we
1414 // have a smaller budget.
1415 let indent = context.block_indent.block_indent(context.config);
1416 let v_budget = context.config.max_width.checked_sub(indent.width()).unwrap_or(0);
1421 let field_iter = fields.into_iter()
1422 .map(StructLitField::Regular)
1423 .chain(base.into_iter().map(StructLitField::Base));
1425 let inner_context = &RewriteContext { block_indent: indent, ..*context };
1427 let items = itemize_list(context.codemap,
1432 StructLitField::Regular(ref field) => field.span.lo,
1433 StructLitField::Base(ref expr) => {
1434 let last_field_hi = fields.last().map_or(span.lo,
1438 let snippet = context.snippet(mk_sp(last_field_hi,
1440 let pos = snippet.find_uncommented("..").unwrap();
1441 last_field_hi + BytePos(pos as u32)
1447 StructLitField::Regular(ref field) => field.span.hi,
1448 StructLitField::Base(ref expr) => expr.span.hi,
1453 StructLitField::Regular(ref field) => {
1454 rewrite_field(inner_context,
1456 v_budget.checked_sub(1).unwrap_or(0),
1459 StructLitField::Base(ref expr) => {
1461 expr.rewrite(inner_context,
1462 try_opt!(v_budget.checked_sub(2)),
1464 .map(|s| format!("..{}", s))
1468 context.codemap.span_after(span, "{"),
1470 let item_vec = items.collect::<Vec<_>>();
1473 let mut prelim_tactic = match (context.config.struct_lit_style, fields.len()) {
1474 (StructLitStyle::Visual, 1) => ListTactic::HorizontalVertical,
1475 _ => context.config.struct_lit_multiline_style.to_list_tactic(),
1478 if prelim_tactic == ListTactic::HorizontalVertical && fields.len() > 1 {
1479 prelim_tactic = ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width);
1482 definitive_tactic(&item_vec, prelim_tactic, h_budget)
1485 let budget = match tactic {
1486 DefinitiveListTactic::Horizontal => h_budget,
1490 let ends_with_newline = context.config.struct_lit_style != StructLitStyle::Visual &&
1491 tactic == DefinitiveListTactic::Vertical;
1493 let fmt = ListFormatting {
1496 trailing_separator: if base.is_some() {
1497 SeparatorTactic::Never
1499 context.config.struct_lit_trailing_comma
1503 ends_with_newline: ends_with_newline,
1504 config: context.config,
1506 let fields_str = try_opt!(write_list(&item_vec, &fmt));
1508 if fields_str.is_empty() {
1509 return Some(format!("{} {{}}", path_str));
1512 let format_on_newline = || {
1513 let inner_indent = context.block_indent
1514 .block_indent(context.config)
1515 .to_string(context.config);
1516 let outer_indent = context.block_indent.to_string(context.config);
1517 Some(format!("{} {{\n{}{}\n{}}}",
1524 match (context.config.struct_lit_style, context.config.struct_lit_multiline_style) {
1525 (StructLitStyle::Block, _) if fields_str.contains('\n') || fields_str.len() > h_budget => {
1528 (StructLitStyle::Block, MultilineStyle::ForceMulti) => format_on_newline(),
1529 _ => Some(format!("{} {{ {} }}", path_str, fields_str)),
1532 // FIXME if context.config.struct_lit_style == Visual, but we run out
1533 // of space, we should fall back to BlockIndent.
1536 fn rewrite_field(context: &RewriteContext,
1541 let name = &field.ident.node.to_string();
1542 let overhead = name.len() + 2;
1543 let expr = field.expr.rewrite(context,
1544 try_opt!(width.checked_sub(overhead)),
1548 Some(e) => Some(format!("{}: {}", name, e)),
1550 let expr_offset = offset.block_indent(&context.config);
1551 let expr = field.expr.rewrite(context,
1552 try_opt!(context.config
1554 .checked_sub(expr_offset.width())),
1556 expr.map(|s| format!("{}:\n{}{}", name, expr_offset.to_string(&context.config), s))
1561 pub fn rewrite_tuple<'a, I>(context: &RewriteContext,
1567 where I: ExactSizeIterator,
1568 <I as Iterator>::Item: Deref,
1569 <I::Item as Deref>::Target: Rewrite + Spanned + 'a
1571 let indent = offset + 1;
1572 // In case of length 1, need a trailing comma
1573 if items.len() == 1 {
1575 let budget = try_opt!(width.checked_sub(3));
1576 return items.next().unwrap().rewrite(context, budget, indent).map(|s| format!("({},)", s));
1579 let list_lo = context.codemap.span_after(span, "(");
1580 let items = itemize_list(context.codemap,
1583 |item| item.span().lo,
1584 |item| item.span().hi,
1586 let inner_width = try_opt!(context.config
1588 .checked_sub(indent.width() +
1590 item.rewrite(context, inner_width, indent)
1593 span.hi - BytePos(1));
1594 let budget = try_opt!(width.checked_sub(2));
1595 let list_str = try_opt!(format_item_list(items, budget, indent, context.config));
1597 Some(format!("({})", list_str))
1600 fn rewrite_binary_op(context: &RewriteContext,
1607 // FIXME: format comments between operands and operator
1609 let operator_str = context.snippet(op.span);
1611 // Get "full width" rhs and see if it fits on the current line. This
1612 // usually works fairly well since it tends to place operands of
1613 // operations with high precendence close together.
1614 let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
1616 // Second condition is needed in case of line break not caused by a
1617 // shortage of space, but by end-of-line comments, for example.
1618 // Note that this is non-conservative, but its just to see if it's even
1619 // worth trying to put everything on one line.
1620 if rhs_result.len() + 2 + operator_str.len() < width && !rhs_result.contains('\n') {
1621 // 1 = space between lhs expr and operator
1622 if let Some(mut result) = lhs.rewrite(context, width - 1 - operator_str.len(), offset) {
1624 result.push_str(&operator_str);
1627 let remaining_width = width.checked_sub(last_line_width(&result)).unwrap_or(0);
1629 if rhs_result.len() <= remaining_width {
1630 result.push_str(&rhs_result);
1631 return Some(result);
1634 if let Some(rhs_result) = rhs.rewrite(context, remaining_width, offset + result.len()) {
1635 if rhs_result.len() <= remaining_width {
1636 result.push_str(&rhs_result);
1637 return Some(result);
1643 // We have to use multiple lines.
1645 // Re-evaluate the lhs because we have more space now:
1646 let budget = try_opt!(context.config
1648 .checked_sub(offset.width() + 1 + operator_str.len()));
1649 Some(format!("{} {}\n{}{}",
1650 try_opt!(lhs.rewrite(context, budget, offset)),
1652 offset.to_string(context.config),
1656 pub fn rewrite_unary_prefix<R: Rewrite>(context: &RewriteContext,
1662 rewrite.rewrite(context,
1663 try_opt!(width.checked_sub(prefix.len())),
1664 offset + prefix.len())
1665 .map(|r| format!("{}{}", prefix, r))
1668 fn rewrite_unary_op(context: &RewriteContext,
1674 // For some reason, an UnOp is not spanned like BinOp!
1675 let operator_str = match *op {
1676 ast::UnOp::Deref => "*",
1677 ast::UnOp::Not => "!",
1678 ast::UnOp::Neg => "-",
1680 rewrite_unary_prefix(context, operator_str, expr, width, offset)
1683 fn rewrite_assignment(context: &RewriteContext,
1686 op: Option<&ast::BinOp>,
1690 let operator_str = match op {
1691 Some(op) => context.snippet(op.span),
1692 None => "=".to_owned(),
1695 // 1 = space between lhs and operator.
1696 let max_width = try_opt!(width.checked_sub(operator_str.len() + 1));
1697 let lhs_str = format!("{} {}",
1698 try_opt!(lhs.rewrite(context, max_width, offset)),
1701 rewrite_assign_rhs(&context, lhs_str, rhs, width, offset)
1704 // The left hand side must contain everything up to, and including, the
1705 // assignment operator.
1706 pub fn rewrite_assign_rhs<S: Into<String>>(context: &RewriteContext,
1712 let mut result = lhs.into();
1713 let last_line_width = last_line_width(&result) -
1714 if result.contains('\n') {
1719 // 1 = space between operator and rhs.
1720 let max_width = try_opt!(width.checked_sub(last_line_width + 1));
1721 let rhs = ex.rewrite(&context, max_width, offset + last_line_width + 1);
1726 result.push_str(&new_str)
1729 // Expression did not fit on the same line as the identifier. Retry
1730 // on the next line.
1731 let new_offset = offset.block_indent(context.config);
1732 result.push_str(&format!("\n{}", new_offset.to_string(context.config)));
1734 // FIXME: we probably should related max_width to width instead of
1735 // config.max_width where is the 1 coming from anyway?
1736 let max_width = try_opt!(context.config.max_width.checked_sub(new_offset.width() + 1));
1737 let inner_context = context.nested_context();
1738 let rhs = ex.rewrite(&inner_context, max_width, new_offset);
1740 result.push_str(&&try_opt!(rhs));
1747 fn rewrite_expr_addrof(context: &RewriteContext,
1748 mutability: ast::Mutability,
1753 let operator_str = match mutability {
1754 ast::Mutability::Immutable => "&",
1755 ast::Mutability::Mutable => "&mut ",
1757 rewrite_unary_prefix(context, operator_str, expr, width, offset)