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};
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, 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, _) | ast::StmtKind::Semi(ref ex, _) => {
501 let suffix = if semicolon_for_stmt(self) {
508 context.config.max_width - offset.width() - suffix.len(),
512 ast::StmtKind::Mac(..) => None,
514 result.and_then(|res| recover_comment_removed(res, self.span, context, _width, offset))
518 // Abstraction over for, while and loop expressions
520 cond: Option<&'a ast::Expr>,
521 block: &'a ast::Block,
522 label: Option<ast::Ident>,
523 pat: Option<&'a ast::Pat>,
530 fn new_loop(block: &'a ast::Block, label: Option<ast::Ident>) -> Loop<'a> {
542 fn new_while(pat: Option<&'a ast::Pat>,
544 block: &'a ast::Block,
545 label: Option<ast::Ident>)
561 fn new_for(pat: &'a ast::Pat,
563 block: &'a ast::Block,
564 label: Option<ast::Ident>)
578 impl<'a> Rewrite for Loop<'a> {
579 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
580 let label_string = rewrite_label(self.label);
582 let inner_width = try_opt!(width.checked_sub(self.keyword.len() + 2 + label_string.len()));
583 let inner_offset = offset + self.keyword.len() + label_string.len();
585 let pat_expr_string = match self.cond {
587 try_opt!(rewrite_pat_expr(context,
595 None => String::new(),
598 // FIXME: this drops any comment between "loop" and the block.
600 .rewrite(context, width, offset)
611 fn rewrite_label(label: Option<ast::Ident>) -> String {
613 Some(ident) => format!("{}: ", ident),
614 None => "".to_owned(),
618 fn extract_comment(span: Span,
619 context: &RewriteContext,
623 let comment_str = context.snippet(span);
624 if contains_comment(&comment_str) {
625 let comment = try_opt!(rewrite_comment(comment_str.trim(),
630 Some(format!("\n{indent}{}\n{indent}",
632 indent = offset.to_string(context.config)))
638 // Rewrites if-else blocks. If let Some(_) = pat, the expression is
639 // treated as an if-let-else expression.
640 fn rewrite_if_else(context: &RewriteContext,
642 if_block: &ast::Block,
643 else_block_opt: Option<&ast::Expr>,
645 pat: Option<&ast::Pat>,
648 allow_single_line: bool)
650 // 3 = "if ", 2 = " {"
651 let pat_expr_string = try_opt!(rewrite_pat_expr(context,
656 try_opt!(width.checked_sub(3 + 2)),
659 // Try to format if-else on single line.
660 if allow_single_line && context.config.single_line_if_else {
661 let trial = single_line_if_else(context, &pat_expr_string, if_block, else_block_opt, width);
668 let if_block_string = try_opt!(if_block.rewrite(context, width, offset));
670 let between_if_cond = mk_sp(context.codemap.span_after(span, "if"),
671 pat.map_or(cond.span.lo,
672 |_| context.codemap.span_before(span, "let")));
674 let between_if_cond_comment = extract_comment(between_if_cond, &context, offset, width);
676 let after_cond_comment = extract_comment(mk_sp(cond.span.hi, if_block.span.lo),
681 let mut result = format!("if{}{}{}{}",
682 between_if_cond_comment.as_ref().map_or(" ", |str| &**str),
684 after_cond_comment.as_ref().map_or(" ", |str| &**str),
687 if let Some(else_block) = else_block_opt {
688 let rewrite = match else_block.node {
689 // If the else expression is another if-else expression, prevent it
690 // from being formatted on a single line.
691 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
692 rewrite_if_else(context,
695 next_else_block.as_ref().map(|e| &**e),
696 mk_sp(else_block.span.lo, span.hi),
702 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
703 rewrite_if_else(context,
706 next_else_block.as_ref().map(|e| &**e),
707 mk_sp(else_block.span.lo, span.hi),
713 _ => else_block.rewrite(context, width, offset),
716 let between_if_else_block = mk_sp(if_block.span.hi,
717 context.codemap.span_before(mk_sp(if_block.span.hi,
720 let between_if_else_block_comment = extract_comment(between_if_else_block,
725 let after_else = mk_sp(context.codemap
726 .span_after(mk_sp(if_block.span.hi, else_block.span.lo),
729 let after_else_comment = extract_comment(after_else, &context, offset, width);
731 try_opt!(write!(&mut result,
733 between_if_else_block_comment.as_ref().map_or(" ", |str| &**str),
734 after_else_comment.as_ref().map_or(" ", |str| &**str))
736 result.push_str(&&try_opt!(rewrite));
742 fn single_line_if_else(context: &RewriteContext,
744 if_node: &ast::Block,
745 else_block_opt: Option<&ast::Expr>,
748 let else_block = try_opt!(else_block_opt);
749 let fixed_cost = "if { } else { }".len();
751 if let ast::ExprKind::Block(ref else_node) = else_block.node {
752 if !is_simple_block(if_node, context.codemap) ||
753 !is_simple_block(else_node, context.codemap) || pat_expr_str.contains('\n') {
757 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
758 let if_expr = if_node.expr.as_ref().unwrap();
759 let if_str = try_opt!(if_expr.rewrite(context, new_width, Indent::empty()));
761 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
762 let else_expr = else_node.expr.as_ref().unwrap();
763 let else_str = try_opt!(else_expr.rewrite(context, new_width, Indent::empty()));
765 // FIXME: this check shouldn't be necessary. Rewrites should either fail
766 // or wrap to a newline when the object does not fit the width.
767 let fits_line = fixed_cost + pat_expr_str.len() + if_str.len() + else_str.len() <= width;
769 if fits_line && !if_str.contains('\n') && !else_str.contains('\n') {
770 return Some(format!("if {} {{ {} }} else {{ {} }}",
780 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
781 let snippet = codemap.span_to_snippet(block.span).unwrap();
782 contains_comment(&snippet)
785 // Checks that a block contains no statements, an expression and no comments.
786 // FIXME: incorrectly returns false when comment is contained completely within
788 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
789 block.stmts.is_empty() && block.expr.is_some() && !block_contains_comment(block, codemap)
792 /// Checks whether a block contains at most one statement or expression, and no comments.
793 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
794 (block.stmts.is_empty() || (block.stmts.len() == 1 && block.expr.is_none())) &&
795 !block_contains_comment(block, codemap)
798 /// Checks whether a block contains no statements, expressions, or comments.
799 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
800 block.stmts.is_empty() && block.expr.is_none() && !block_contains_comment(block, codemap)
803 fn is_unsafe_block(block: &ast::Block) -> bool {
804 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
811 // inter-match-arm-comment-rules:
812 // - all comments following a match arm before the start of the next arm
813 // are about the second arm
814 fn rewrite_match_arm_comment(context: &RewriteContext,
818 arm_indent_str: &str)
820 // The leading "," is not part of the arm-comment
821 let missed_str = match missed_str.find_uncommented(",") {
822 Some(n) => &missed_str[n + 1..],
823 None => &missed_str[..],
826 let mut result = String::new();
827 // any text not preceeded by a newline is pushed unmodified to the block
828 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
829 result.push_str(&missed_str[..first_brk]);
830 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
832 let first = missed_str.find(|c: char| !c.is_whitespace()).unwrap_or(missed_str.len());
833 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
834 // Excessive vertical whitespace before comment should be preserved
835 // TODO handle vertical whitespace better
838 let missed_str = missed_str[first..].trim();
839 if !missed_str.is_empty() {
840 let comment = try_opt!(rewrite_comment(&missed_str,
846 result.push_str(arm_indent_str);
847 result.push_str(&comment);
853 fn rewrite_match(context: &RewriteContext,
865 let cond_budget = try_opt!(width.checked_sub(8));
866 let cond_str = try_opt!(cond.rewrite(context, cond_budget, offset + 6));
867 let mut result = format!("match {} {{", cond_str);
869 let nested_context = context.nested_context();
870 let arm_indent = nested_context.block_indent;
871 let arm_indent_str = arm_indent.to_string(context.config);
873 let open_brace_pos = context.codemap
874 .span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])), "{");
876 for (i, arm) in arms.iter().enumerate() {
877 // Make sure we get the stuff between arms.
878 let missed_str = if i == 0 {
879 context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
881 context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
883 let comment = try_opt!(rewrite_match_arm_comment(context,
888 result.push_str(&comment);
890 result.push_str(&arm_indent_str);
892 let arm_str = arm.rewrite(&nested_context,
893 context.config.max_width - arm_indent.width(),
895 if let Some(ref arm_str) = arm_str {
896 result.push_str(arm_str);
898 // We couldn't format the arm, just reproduce the source.
899 let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
900 result.push_str(&snippet);
901 result.push_str(arm_comma(&context.config, &arm, &arm.body));
904 // BytePos(1) = closing match brace.
905 let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
906 let last_comment = context.snippet(last_span);
907 let comment = try_opt!(rewrite_match_arm_comment(context,
912 result.push_str(&comment);
914 result.push_str(&context.block_indent.to_string(context.config));
919 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
920 let &ast::Arm { ref attrs, ref pats, .. } = arm;
921 if !attrs.is_empty() {
922 return attrs[0].span.lo;
928 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
932 fn arm_comma(config: &Config, arm: &ast::Arm, body: &ast::Expr) -> &'static str {
933 if !config.match_wildcard_trailing_comma {
934 if arm.pats.len() == 1 && arm.pats[0].node == ast::PatKind::Wild && arm.guard.is_none() {
939 if config.match_block_trailing_comma {
941 } else if let ast::ExprKind::Block(ref block) = body.node {
942 if let ast::BlockCheckMode::Default = block.rules {
953 impl Rewrite for ast::Arm {
954 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
955 let &ast::Arm { ref attrs, ref pats, ref guard, ref body } = self;
956 let indent_str = offset.to_string(context.config);
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 mut total_width = pat_strs.iter().fold(0, |a, p| a + p.len());
985 total_width += (pat_strs.len() - 1) * 3;
987 let mut vertical = total_width > pat_budget || pat_strs.iter().any(|p| p.contains('\n'));
988 if !vertical && context.config.take_source_hints {
989 // If the patterns were previously stacked, keep them stacked.
990 let pat_span = mk_sp(pats[0].span.lo, pats[pats.len() - 1].span.hi);
991 let pat_str = context.snippet(pat_span);
992 vertical = pat_str.contains('\n');
995 let pats_width = if vertical {
996 pat_strs.last().unwrap().len()
1001 let mut pats_str = String::new();
1003 if !pats_str.is_empty() {
1005 pats_str.push_str(" |\n");
1006 pats_str.push_str(&indent_str);
1008 pats_str.push_str(" | ");
1011 pats_str.push_str(&p);
1014 let guard_str = try_opt!(rewrite_guard(context, guard, width, offset, pats_width));
1016 let pats_str = format!("{}{}", pats_str, guard_str);
1017 // Where the next text can start.
1018 let mut line_start = last_line_width(&pats_str);
1019 if !pats_str.contains('\n') {
1020 line_start += offset.width();
1023 let body = match **body {
1024 ast::Expr { node: ast::ExprKind::Block(ref block), .. }
1025 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) &&
1026 context.config.wrap_match_arms => block.expr.as_ref().map(|e| &**e).unwrap(),
1030 let comma = arm_comma(&context.config, self, body);
1032 // Let's try and get the arm body on the same line as the condition.
1034 if context.config.max_width > line_start + comma.len() + 4 {
1035 let budget = context.config.max_width - line_start - comma.len() - 4;
1036 let offset = Indent::new(offset.block_indent, line_start + 4 - offset.block_indent);
1037 let rewrite = nop_block_collapse(body.rewrite(context, budget, offset), budget);
1038 let is_block = if let ast::ExprKind::Block(..) = body.node {
1045 Some(ref body_str) if !body_str.contains('\n') || !context.config.wrap_match_arms ||
1047 return Some(format!("{}{} => {}{}",
1048 attr_str.trim_left(),
1057 // FIXME: we're doing a second rewrite of the expr; This may not be
1059 let body_budget = try_opt!(width.checked_sub(context.config.tab_spaces));
1060 let indent = context.block_indent.block_indent(context.config);
1061 let inner_context = &RewriteContext { block_indent: indent, ..*context };
1062 let next_line_body = try_opt!(nop_block_collapse(body.rewrite(inner_context,
1066 let indent_str = offset.block_indent(context.config).to_string(context.config);
1067 let (body_prefix, body_suffix) = if context.config.wrap_match_arms {
1068 if context.config.match_block_trailing_comma {
1077 Some(format!("{}{} =>{}\n{}{}\n{}{}",
1078 attr_str.trim_left(),
1083 offset.to_string(context.config),
1088 // The `if ...` guard on a match arm.
1089 fn rewrite_guard(context: &RewriteContext,
1090 guard: &Option<ptr::P<ast::Expr>>,
1093 // The amount of space used up on this line for the pattern in
1094 // the arm (excludes offset).
1095 pattern_width: usize)
1097 if let Some(ref guard) = *guard {
1098 // First try to fit the guard string on the same line as the pattern.
1099 // 4 = ` if `, 5 = ` => {`
1100 let overhead = pattern_width + 4 + 5;
1101 if overhead < width {
1102 let cond_str = guard.rewrite(context, width - overhead, offset + pattern_width + 4);
1103 if let Some(cond_str) = cond_str {
1104 return Some(format!(" if {}", cond_str));
1108 // Not enough space to put the guard after the pattern, try a newline.
1109 let overhead = context.config.tab_spaces + 4 + 5;
1110 if overhead < width {
1111 let cond_str = guard.rewrite(context,
1113 offset.block_indent(context.config));
1114 if let Some(cond_str) = cond_str {
1115 return Some(format!("\n{}if {}",
1116 offset.block_indent(context.config).to_string(context.config),
1127 fn rewrite_pat_expr(context: &RewriteContext,
1128 pat: Option<&ast::Pat>,
1131 // Connecting piece between pattern and expression,
1132 // *without* trailing space.
1137 let pat_offset = offset + matcher.len();
1138 let mut result = match pat {
1140 let pat_budget = try_opt!(width.checked_sub(connector.len() + matcher.len()));
1141 let pat_string = try_opt!(pat.rewrite(context, pat_budget, pat_offset));
1142 format!("{}{}{}", matcher, pat_string, connector)
1144 None => String::new(),
1147 // Consider only the last line of the pat string.
1148 let extra_offset = extra_offset(&result, offset);
1150 // The expression may (partionally) fit on the current line.
1151 if width > extra_offset + 1 {
1152 let spacer = if pat.is_some() {
1158 let expr_rewrite = expr.rewrite(context,
1159 width - extra_offset - spacer.len(),
1160 offset + extra_offset + spacer.len());
1162 if let Some(expr_string) = expr_rewrite {
1163 result.push_str(spacer);
1164 result.push_str(&expr_string);
1165 return Some(result);
1169 // The expression won't fit on the current line, jump to next.
1171 result.push_str(&pat_offset.to_string(context.config));
1173 let expr_rewrite = expr.rewrite(context,
1174 context.config.max_width - pat_offset.width(),
1176 result.push_str(&&try_opt!(expr_rewrite));
1181 fn rewrite_string_lit(context: &RewriteContext,
1186 let string_lit = context.snippet(span);
1188 if !context.config.format_strings && !context.config.force_format_strings {
1189 return Some(string_lit);
1192 if !context.config.force_format_strings &&
1193 !string_requires_rewrite(context, span, &string_lit, width, offset) {
1194 return Some(string_lit);
1197 let fmt = StringFormat {
1205 config: context.config,
1208 // Remove the quote characters.
1209 let str_lit = &string_lit[1..string_lit.len() - 1];
1211 rewrite_string(str_lit, &fmt)
1214 fn string_requires_rewrite(context: &RewriteContext,
1220 if context.codemap.lookup_char_pos(span.lo).col.0 != offset.width() {
1224 for (i, line) in string.lines().enumerate() {
1226 if line.len() > width {
1230 if line.len() > width + offset.width() {
1239 pub fn rewrite_call<R>(context: &RewriteContext,
1241 args: &[ptr::P<ast::Expr>],
1248 let closure = |callee_max_width| {
1249 rewrite_call_inner(context, callee, callee_max_width, args, span, width, offset)
1253 let max_width = try_opt!(width.checked_sub(2));
1254 binary_search(1, max_width, closure)
1257 fn rewrite_call_inner<R>(context: &RewriteContext,
1259 max_callee_width: usize,
1260 args: &[ptr::P<ast::Expr>],
1264 -> Result<String, Ordering>
1267 let callee = callee.borrow();
1268 // FIXME using byte lens instead of char lens (and probably all over the
1270 let callee_str = match callee.rewrite(context, max_callee_width, offset) {
1272 if !string.contains('\n') && string.len() > max_callee_width {
1273 panic!("{:?} {}", string, max_callee_width);
1278 None => return Err(Ordering::Greater),
1281 let span_lo = context.codemap.span_after(span, "(");
1282 let span = mk_sp(span_lo, span.hi);
1284 let extra_offset = extra_offset(&callee_str, offset);
1286 let remaining_width = match width.checked_sub(extra_offset + 2) {
1288 None => return Err(Ordering::Greater),
1290 let offset = offset + extra_offset + 1;
1291 let arg_count = args.len();
1292 let block_indent = if arg_count == 1 {
1293 context.block_indent
1297 let inner_context = &RewriteContext { block_indent: block_indent, ..*context };
1299 let items = itemize_list(context.codemap,
1302 |item| item.span.lo,
1303 |item| item.span.hi,
1304 |item| item.rewrite(&inner_context, remaining_width, offset),
1307 let mut item_vec: Vec<_> = items.collect();
1309 // Try letting the last argument overflow to the next line with block
1310 // indentation. If its first line fits on one line with the other arguments,
1311 // we format the function arguments horizontally.
1312 let overflow_last = match args.last().map(|x| &x.node) {
1313 Some(&ast::ExprKind::Closure(..)) |
1314 Some(&ast::ExprKind::Block(..)) if arg_count > 1 => true,
1316 } && context.config.chains_overflow_last;
1318 let mut orig_last = None;
1319 let mut placeholder = None;
1321 // Replace the last item with its first line to see if it fits with
1324 let inner_context = &RewriteContext { block_indent: context.block_indent, ..*context };
1325 let rewrite = args.last().unwrap().rewrite(&inner_context, remaining_width, offset);
1327 if let Some(rewrite) = rewrite {
1328 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
1329 placeholder = Some(rewrite);
1331 swap(&mut item_vec[arg_count - 1].item, &mut orig_last);
1332 item_vec[arg_count - 1].item = rewrite_first_line;
1336 let tactic = definitive_tactic(&item_vec,
1337 ListTactic::LimitedHorizontalVertical(context.config
1341 // Replace the stub with the full overflowing last argument if the rewrite
1342 // succeeded and its first line fits with the other arguments.
1343 match (overflow_last, tactic, placeholder) {
1344 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
1345 item_vec[arg_count - 1].item = placeholder;
1348 item_vec[arg_count - 1].item = orig_last;
1353 let fmt = ListFormatting {
1356 trailing_separator: SeparatorTactic::Never,
1359 ends_with_newline: false,
1360 config: context.config,
1363 let list_str = match write_list(&item_vec, &fmt) {
1365 None => return Err(Ordering::Less),
1368 Ok(format!("{}({})", callee_str, list_str))
1371 fn rewrite_paren(context: &RewriteContext,
1372 subexpr: &ast::Expr,
1376 debug!("rewrite_paren, width: {}, offset: {:?}", width, offset);
1377 // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
1378 // paren on the same line as the subexpr.
1379 let subexpr_str = subexpr.rewrite(context, try_opt!(width.checked_sub(2)), offset + 1);
1380 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1381 subexpr_str.map(|s| format!("({})", s))
1384 fn rewrite_struct_lit<'a>(context: &RewriteContext,
1386 fields: &'a [ast::Field],
1387 base: Option<&'a ast::Expr>,
1392 debug!("rewrite_struct_lit: width {}, offset {:?}", width, offset);
1393 assert!(!fields.is_empty() || base.is_some());
1395 enum StructLitField<'a> {
1396 Regular(&'a ast::Field),
1397 Base(&'a ast::Expr),
1401 let path_budget = try_opt!(width.checked_sub(2));
1402 let path_str = try_opt!(rewrite_path(context, true, None, path, path_budget, offset));
1404 // Foo { a: Foo } - indent is +3, width is -5.
1405 let h_budget = width.checked_sub(path_str.len() + 5).unwrap_or(0);
1406 // The 1 taken from the v_budget is for the comma.
1407 let (indent, v_budget) = match context.config.struct_lit_style {
1408 StructLitStyle::Visual => (offset + path_str.len() + 3, h_budget),
1409 StructLitStyle::Block => {
1410 // If we are all on one line, then we'll ignore the indent, and we
1411 // have a smaller budget.
1412 let indent = context.block_indent.block_indent(context.config);
1413 let v_budget = context.config.max_width.checked_sub(indent.width()).unwrap_or(0);
1418 let field_iter = fields.into_iter()
1419 .map(StructLitField::Regular)
1420 .chain(base.into_iter().map(StructLitField::Base));
1422 let inner_context = &RewriteContext { block_indent: indent, ..*context };
1424 let items = itemize_list(context.codemap,
1429 StructLitField::Regular(ref field) => field.span.lo,
1430 StructLitField::Base(ref expr) => {
1431 let last_field_hi = fields.last().map_or(span.lo,
1435 let snippet = context.snippet(mk_sp(last_field_hi,
1437 let pos = snippet.find_uncommented("..").unwrap();
1438 last_field_hi + BytePos(pos as u32)
1444 StructLitField::Regular(ref field) => field.span.hi,
1445 StructLitField::Base(ref expr) => expr.span.hi,
1450 StructLitField::Regular(ref field) => {
1451 rewrite_field(inner_context,
1453 v_budget.checked_sub(1).unwrap_or(0),
1456 StructLitField::Base(ref expr) => {
1458 expr.rewrite(inner_context,
1459 try_opt!(v_budget.checked_sub(2)),
1461 .map(|s| format!("..{}", s))
1465 context.codemap.span_after(span, "{"),
1467 let item_vec = items.collect::<Vec<_>>();
1470 let mut prelim_tactic = match (context.config.struct_lit_style, fields.len()) {
1471 (StructLitStyle::Visual, 1) => ListTactic::HorizontalVertical,
1472 _ => context.config.struct_lit_multiline_style.to_list_tactic(),
1475 if prelim_tactic == ListTactic::HorizontalVertical && fields.len() > 1 {
1476 prelim_tactic = ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width);
1479 definitive_tactic(&item_vec, prelim_tactic, h_budget)
1482 let budget = match tactic {
1483 DefinitiveListTactic::Horizontal => h_budget,
1487 let ends_with_newline = context.config.struct_lit_style != StructLitStyle::Visual &&
1488 tactic == DefinitiveListTactic::Vertical;
1490 let fmt = ListFormatting {
1493 trailing_separator: if base.is_some() {
1494 SeparatorTactic::Never
1496 context.config.struct_lit_trailing_comma
1500 ends_with_newline: ends_with_newline,
1501 config: context.config,
1503 let fields_str = try_opt!(write_list(&item_vec, &fmt));
1505 let format_on_newline = || {
1506 let inner_indent = context.block_indent
1507 .block_indent(context.config)
1508 .to_string(context.config);
1509 let outer_indent = context.block_indent.to_string(context.config);
1510 Some(format!("{} {{\n{}{}\n{}}}",
1517 match (context.config.struct_lit_style, context.config.struct_lit_multiline_style) {
1518 (StructLitStyle::Block, _) if fields_str.contains('\n') || fields_str.len() > h_budget => {
1521 (StructLitStyle::Block, MultilineStyle::ForceMulti) => format_on_newline(),
1522 _ => Some(format!("{} {{ {} }}", path_str, fields_str)),
1525 // FIXME if context.config.struct_lit_style == Visual, but we run out
1526 // of space, we should fall back to BlockIndent.
1529 fn rewrite_field(context: &RewriteContext,
1534 let name = &field.ident.node.to_string();
1535 let overhead = name.len() + 2;
1536 let expr = field.expr.rewrite(context,
1537 try_opt!(width.checked_sub(overhead)),
1541 Some(e) => Some(format!("{}: {}", name, e)),
1543 let expr_offset = offset.block_indent(&context.config);
1544 let expr = field.expr.rewrite(context,
1545 try_opt!(context.config
1547 .checked_sub(expr_offset.width())),
1549 expr.map(|s| format!("{}:\n{}{}", name, expr_offset.to_string(&context.config), s))
1554 pub fn rewrite_tuple<'a, I>(context: &RewriteContext,
1560 where I: ExactSizeIterator,
1561 <I as Iterator>::Item: Deref,
1562 <I::Item as Deref>::Target: Rewrite + Spanned + 'a
1564 let indent = offset + 1;
1565 // In case of length 1, need a trailing comma
1566 if items.len() == 1 {
1568 let budget = try_opt!(width.checked_sub(3));
1569 return items.next().unwrap().rewrite(context, budget, indent).map(|s| format!("({},)", s));
1572 let list_lo = context.codemap.span_after(span, "(");
1573 let items = itemize_list(context.codemap,
1576 |item| item.span().lo,
1577 |item| item.span().hi,
1579 let inner_width = try_opt!(context.config
1581 .checked_sub(indent.width() +
1583 item.rewrite(context, inner_width, indent)
1586 span.hi - BytePos(1));
1587 let budget = try_opt!(width.checked_sub(2));
1588 let list_str = try_opt!(format_item_list(items, budget, indent, context.config));
1590 Some(format!("({})", list_str))
1593 fn rewrite_binary_op(context: &RewriteContext,
1600 // FIXME: format comments between operands and operator
1602 let operator_str = context.snippet(op.span);
1604 // Get "full width" rhs and see if it fits on the current line. This
1605 // usually works fairly well since it tends to place operands of
1606 // operations with high precendence close together.
1607 let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
1609 // Second condition is needed in case of line break not caused by a
1610 // shortage of space, but by end-of-line comments, for example.
1611 // Note that this is non-conservative, but its just to see if it's even
1612 // worth trying to put everything on one line.
1613 if rhs_result.len() + 2 + operator_str.len() < width && !rhs_result.contains('\n') {
1614 // 1 = space between lhs expr and operator
1615 if let Some(mut result) = lhs.rewrite(context, width - 1 - operator_str.len(), offset) {
1617 result.push_str(&operator_str);
1620 let remaining_width = width.checked_sub(last_line_width(&result)).unwrap_or(0);
1622 if rhs_result.len() <= remaining_width {
1623 result.push_str(&rhs_result);
1624 return Some(result);
1627 if let Some(rhs_result) = rhs.rewrite(context, remaining_width, offset + result.len()) {
1628 if rhs_result.len() <= remaining_width {
1629 result.push_str(&rhs_result);
1630 return Some(result);
1636 // We have to use multiple lines.
1638 // Re-evaluate the lhs because we have more space now:
1639 let budget = try_opt!(context.config
1641 .checked_sub(offset.width() + 1 + operator_str.len()));
1642 Some(format!("{} {}\n{}{}",
1643 try_opt!(lhs.rewrite(context, budget, offset)),
1645 offset.to_string(context.config),
1649 pub fn rewrite_unary_prefix<R: Rewrite>(context: &RewriteContext,
1655 rewrite.rewrite(context,
1656 try_opt!(width.checked_sub(prefix.len())),
1657 offset + prefix.len())
1658 .map(|r| format!("{}{}", prefix, r))
1661 fn rewrite_unary_op(context: &RewriteContext,
1667 // For some reason, an UnOp is not spanned like BinOp!
1668 let operator_str = match *op {
1669 ast::UnOp::Deref => "*",
1670 ast::UnOp::Not => "!",
1671 ast::UnOp::Neg => "-",
1673 rewrite_unary_prefix(context, operator_str, expr, width, offset)
1676 fn rewrite_assignment(context: &RewriteContext,
1679 op: Option<&ast::BinOp>,
1683 let operator_str = match op {
1684 Some(op) => context.snippet(op.span),
1685 None => "=".to_owned(),
1688 // 1 = space between lhs and operator.
1689 let max_width = try_opt!(width.checked_sub(operator_str.len() + 1));
1690 let lhs_str = format!("{} {}",
1691 try_opt!(lhs.rewrite(context, max_width, offset)),
1694 rewrite_assign_rhs(&context, lhs_str, rhs, width, offset)
1697 // The left hand side must contain everything up to, and including, the
1698 // assignment operator.
1699 pub fn rewrite_assign_rhs<S: Into<String>>(context: &RewriteContext,
1705 let mut result = lhs.into();
1706 let last_line_width = last_line_width(&result) -
1707 if result.contains('\n') {
1712 // 1 = space between operator and rhs.
1713 let max_width = try_opt!(width.checked_sub(last_line_width + 1));
1714 let rhs = ex.rewrite(&context, max_width, offset + last_line_width + 1);
1719 result.push_str(&new_str)
1722 // Expression did not fit on the same line as the identifier. Retry
1723 // on the next line.
1724 let new_offset = offset.block_indent(context.config);
1725 result.push_str(&format!("\n{}", new_offset.to_string(context.config)));
1727 // FIXME: we probably should related max_width to width instead of
1728 // config.max_width where is the 1 coming from anyway?
1729 let max_width = try_opt!(context.config.max_width.checked_sub(new_offset.width() + 1));
1730 let inner_context = context.nested_context();
1731 let rhs = ex.rewrite(&inner_context, max_width, new_offset);
1733 result.push_str(&&try_opt!(rhs));
1740 fn rewrite_expr_addrof(context: &RewriteContext,
1741 mutability: ast::Mutability,
1746 let operator_str = match mutability {
1747 ast::Mutability::Immutable => "&",
1748 ast::Mutability::Mutable => "&mut ",
1750 rewrite_unary_prefix(context, operator_str, expr, width, offset)