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, 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 // TODO(#848): Handle type ascription; rust tracking issue
180 // https://github.com/rust-lang/rust/issues/23416
181 ast::ExprKind::Type(_, _) => unimplemented!(),
182 ast::ExprKind::Index(ref expr, ref index) => {
183 rewrite_pair(&**expr, &**index, "", "[", "]", context, width, offset)
185 ast::ExprKind::Repeat(ref expr, ref repeats) => {
186 rewrite_pair(&**expr, &**repeats, "[", "; ", "]", context, width, offset)
188 ast::ExprKind::Range(Some(ref lhs), Some(ref rhs)) => {
189 rewrite_pair(&**lhs, &**rhs, "", "..", "", context, width, offset)
191 ast::ExprKind::Range(None, Some(ref rhs)) => {
192 rewrite_unary_prefix(context, "..", &**rhs, width, offset)
194 ast::ExprKind::Range(Some(ref lhs), None) => {
196 try_opt!(lhs.rewrite(context,
197 try_opt!(width.checked_sub(2)),
200 ast::ExprKind::Range(None, None) => {
207 // We do not format these expressions yet, but they should still
208 // satisfy our width restrictions.
209 ast::ExprKind::InPlace(..) |
210 ast::ExprKind::InlineAsm(..) => {
211 wrap_str(context.snippet(self.span),
212 context.config.max_width,
217 result.and_then(|res| recover_comment_removed(res, self.span, context, width, offset))
221 pub fn rewrite_pair<LHS, RHS>(lhs: &LHS,
226 context: &RewriteContext,
233 let max_width = try_opt!(width.checked_sub(prefix.len() + infix.len() + suffix.len()));
235 binary_search(1, max_width, |lhs_budget| {
236 let lhs_offset = offset + prefix.len();
237 let lhs_str = match lhs.rewrite(context, lhs_budget, lhs_offset) {
238 Some(result) => result,
239 None => return Err(Ordering::Greater),
242 let last_line_width = last_line_width(&lhs_str);
243 let rhs_budget = match max_width.checked_sub(last_line_width) {
245 None => return Err(Ordering::Less),
247 let rhs_indent = offset + last_line_width + prefix.len() + infix.len();
249 let rhs_str = match rhs.rewrite(context, rhs_budget, rhs_indent) {
250 Some(result) => result,
251 None => return Err(Ordering::Less),
254 Ok(format!("{}{}{}{}{}", prefix, lhs_str, infix, rhs_str, suffix))
258 pub fn rewrite_array<'a, I>(expr_iter: I,
260 context: &RewriteContext,
264 where I: Iterator<Item = &'a ast::Expr>
267 let offset = offset + 1;
268 let inner_context = &RewriteContext { block_indent: offset, ..*context };
269 let max_item_width = try_opt!(width.checked_sub(2));
270 let items = itemize_list(context.codemap,
276 |item| item.rewrite(&inner_context, max_item_width, offset),
279 .collect::<Vec<_>>();
281 let has_long_item = try_opt!(items.iter()
282 .map(|li| li.item.as_ref().map(|s| s.len() > 10))
284 |acc, x| acc.and_then(|y| x.map(|x| x || y))));
286 let tactic = if has_long_item || items.iter().any(ListItem::is_multiline) {
287 definitive_tactic(&items, ListTactic::HorizontalVertical, max_item_width)
289 DefinitiveListTactic::Mixed
292 let fmt = ListFormatting {
295 trailing_separator: SeparatorTactic::Never,
297 width: max_item_width,
298 ends_with_newline: false,
299 config: context.config,
301 let list_str = try_opt!(write_list(&items, &fmt));
303 Some(format!("[{}]", list_str))
306 // This functions is pretty messy because of the wrapping and unwrapping of
307 // expressions into and from blocks. See rust issue #27872.
308 fn rewrite_closure(capture: ast::CaptureBy,
309 fn_decl: &ast::FnDecl,
312 context: &RewriteContext,
316 let mover = if capture == ast::CaptureBy::Value {
321 let offset = offset + mover.len();
323 // 4 = "|| {".len(), which is overconservative when the closure consists of
324 // a single expression.
325 let budget = try_opt!(width.checked_sub(4 + mover.len()));
327 let argument_offset = offset + 1;
328 let ret_str = try_opt!(fn_decl.output.rewrite(context, budget, argument_offset));
329 // 1 = space between arguments and return type.
330 let horizontal_budget = budget.checked_sub(ret_str.len() + 1).unwrap_or(0);
332 let arg_items = itemize_list(context.codemap,
333 fn_decl.inputs.iter(),
335 |arg| span_lo_for_arg(arg),
336 |arg| span_hi_for_arg(arg),
337 |arg| arg.rewrite(context, budget, argument_offset),
338 context.codemap.span_after(span, "|"),
340 let item_vec = arg_items.collect::<Vec<_>>();
341 let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
342 let budget = match tactic {
343 DefinitiveListTactic::Horizontal => horizontal_budget,
347 let fmt = ListFormatting {
350 trailing_separator: SeparatorTactic::Never,
351 indent: argument_offset,
353 ends_with_newline: false,
354 config: context.config,
356 let list_str = try_opt!(write_list(&item_vec, &fmt));
357 let mut prefix = format!("{}|{}|", mover, list_str);
359 if !ret_str.is_empty() {
360 if prefix.contains('\n') {
362 prefix.push_str(&argument_offset.to_string(context.config));
366 prefix.push_str(&ret_str);
369 // Try to format closure body as a single line expression without braces.
370 if is_simple_block(body, context.codemap) && !prefix.contains('\n') {
371 let (spacer, closer) = if ret_str.is_empty() {
376 let expr = body.expr.as_ref().unwrap();
377 // All closure bodies are blocks in the eyes of the AST, but we may not
378 // want to unwrap them when they only contain a single expression.
379 let inner_expr = match expr.node {
380 ast::ExprKind::Block(ref inner) if inner.stmts.is_empty() && inner.expr.is_some() &&
381 inner.rules == ast::BlockCheckMode::Default => {
382 inner.expr.as_ref().unwrap()
386 let extra_offset = extra_offset(&prefix, offset) + spacer.len();
387 let budget = try_opt!(width.checked_sub(extra_offset + closer.len()));
388 let rewrite = inner_expr.rewrite(context, budget, offset + extra_offset);
390 // Checks if rewrite succeeded and fits on a single line.
391 let accept_rewrite = rewrite.as_ref().map_or(false, |result| !result.contains('\n'));
394 return Some(format!("{}{}{}{}", prefix, spacer, rewrite.unwrap(), closer));
398 // We couldn't format the closure body as a single line expression; fall
399 // back to block formatting.
400 let body_rewrite = body.expr
402 .and_then(|body_expr| {
403 if let ast::ExprKind::Block(ref inner) = body_expr.node {
404 Some(inner.rewrite(&context, 2, Indent::empty()))
409 .unwrap_or_else(|| body.rewrite(&context, 2, Indent::empty()));
411 Some(format!("{} {}", prefix, try_opt!(body_rewrite)))
414 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
415 block_str.map(|block_str| {
416 if block_str.starts_with("{") && budget >= 2 &&
417 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2) {
425 impl Rewrite for ast::Block {
426 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
427 let user_str = context.snippet(self.span);
428 if user_str == "{}" && width >= 2 {
429 return Some(user_str);
432 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
433 visitor.block_indent = context.block_indent;
435 let prefix = match self.rules {
436 ast::BlockCheckMode::Unsafe(..) => {
437 let snippet = context.snippet(self.span);
438 let open_pos = try_opt!(snippet.find_uncommented("{"));
439 visitor.last_pos = self.span.lo + BytePos(open_pos as u32);
441 // Extract comment between unsafe and block start.
442 let trimmed = &snippet[6..open_pos].trim();
444 let prefix = if !trimmed.is_empty() {
445 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
446 let budget = try_opt!(width.checked_sub(9));
447 format!("unsafe {} ",
448 try_opt!(rewrite_comment(trimmed,
457 if is_simple_block(self, context.codemap) && prefix.len() < width {
461 .rewrite(context, width - prefix.len(), offset);
462 if let Some(ref expr_str) = body {
463 let result = format!("{}{{ {} }}", prefix, expr_str);
464 if result.len() <= width && !result.contains('\n') {
472 ast::BlockCheckMode::Default => {
473 visitor.last_pos = self.span.lo;
479 visitor.visit_block(self);
481 Some(format!("{}{}", prefix, visitor.buffer))
485 impl Rewrite for ast::Stmt {
486 fn rewrite(&self, context: &RewriteContext, _width: usize, offset: Indent) -> Option<String> {
487 let result = match self.node {
488 ast::StmtKind::Decl(ref decl, _) => {
489 if let ast::DeclKind::Local(ref local) = decl.node {
490 local.rewrite(context, context.config.max_width, offset)
495 ast::StmtKind::Expr(ref ex, _) | ast::StmtKind::Semi(ref ex, _) => {
496 let suffix = if semicolon_for_stmt(self) {
503 context.config.max_width - offset.width() - suffix.len(),
507 ast::StmtKind::Mac(..) => None,
509 result.and_then(|res| recover_comment_removed(res, self.span, context, _width, offset))
513 // Abstraction over for, while and loop expressions
515 cond: Option<&'a ast::Expr>,
516 block: &'a ast::Block,
517 label: Option<ast::Ident>,
518 pat: Option<&'a ast::Pat>,
525 fn new_loop(block: &'a ast::Block, label: Option<ast::Ident>) -> Loop<'a> {
537 fn new_while(pat: Option<&'a ast::Pat>,
539 block: &'a ast::Block,
540 label: Option<ast::Ident>)
556 fn new_for(pat: &'a ast::Pat,
558 block: &'a ast::Block,
559 label: Option<ast::Ident>)
573 impl<'a> Rewrite for Loop<'a> {
574 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
575 let label_string = rewrite_label(self.label);
577 let inner_width = try_opt!(width.checked_sub(self.keyword.len() + 2 + label_string.len()));
578 let inner_offset = offset + self.keyword.len() + label_string.len();
580 let pat_expr_string = match self.cond {
582 try_opt!(rewrite_pat_expr(context,
590 None => String::new(),
593 // FIXME: this drops any comment between "loop" and the block.
595 .rewrite(context, width, offset)
606 fn rewrite_label(label: Option<ast::Ident>) -> String {
608 Some(ident) => format!("{}: ", ident),
609 None => "".to_owned(),
613 fn extract_comment(span: Span,
614 context: &RewriteContext,
618 let comment_str = context.snippet(span);
619 if contains_comment(&comment_str) {
620 let comment = try_opt!(rewrite_comment(comment_str.trim(),
625 Some(format!("\n{indent}{}\n{indent}",
627 indent = offset.to_string(context.config)))
633 // Rewrites if-else blocks. If let Some(_) = pat, the expression is
634 // treated as an if-let-else expression.
635 fn rewrite_if_else(context: &RewriteContext,
637 if_block: &ast::Block,
638 else_block_opt: Option<&ast::Expr>,
640 pat: Option<&ast::Pat>,
643 allow_single_line: bool)
645 // 3 = "if ", 2 = " {"
646 let pat_expr_string = try_opt!(rewrite_pat_expr(context,
651 try_opt!(width.checked_sub(3 + 2)),
654 // Try to format if-else on single line.
655 if allow_single_line && context.config.single_line_if_else {
656 let trial = single_line_if_else(context, &pat_expr_string, if_block, else_block_opt, width);
663 let if_block_string = try_opt!(if_block.rewrite(context, width, offset));
665 let between_if_cond = mk_sp(context.codemap.span_after(span, "if"),
666 pat.map_or(cond.span.lo,
667 |_| context.codemap.span_before(span, "let")));
669 let between_if_cond_comment = extract_comment(between_if_cond, &context, offset, width);
671 let after_cond_comment = extract_comment(mk_sp(cond.span.hi, if_block.span.lo),
676 let mut result = format!("if{}{}{}{}",
677 between_if_cond_comment.as_ref().map_or(" ", |str| &**str),
679 after_cond_comment.as_ref().map_or(" ", |str| &**str),
682 if let Some(else_block) = else_block_opt {
683 let rewrite = match else_block.node {
684 // If the else expression is another if-else expression, prevent it
685 // from being formatted on a single line.
686 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
687 rewrite_if_else(context,
690 next_else_block.as_ref().map(|e| &**e),
691 mk_sp(else_block.span.lo, span.hi),
697 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
698 rewrite_if_else(context,
701 next_else_block.as_ref().map(|e| &**e),
702 mk_sp(else_block.span.lo, span.hi),
708 _ => else_block.rewrite(context, width, offset),
711 let between_if_else_block = mk_sp(if_block.span.hi,
712 context.codemap.span_before(mk_sp(if_block.span.hi,
715 let between_if_else_block_comment = extract_comment(between_if_else_block,
720 let after_else = mk_sp(context.codemap
721 .span_after(mk_sp(if_block.span.hi, else_block.span.lo),
724 let after_else_comment = extract_comment(after_else, &context, offset, width);
726 try_opt!(write!(&mut result,
728 between_if_else_block_comment.as_ref().map_or(" ", |str| &**str),
729 after_else_comment.as_ref().map_or(" ", |str| &**str))
731 result.push_str(&&try_opt!(rewrite));
737 fn single_line_if_else(context: &RewriteContext,
739 if_node: &ast::Block,
740 else_block_opt: Option<&ast::Expr>,
743 let else_block = try_opt!(else_block_opt);
744 let fixed_cost = "if { } else { }".len();
746 if let ast::ExprKind::Block(ref else_node) = else_block.node {
747 if !is_simple_block(if_node, context.codemap) ||
748 !is_simple_block(else_node, context.codemap) || pat_expr_str.contains('\n') {
752 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
753 let if_expr = if_node.expr.as_ref().unwrap();
754 let if_str = try_opt!(if_expr.rewrite(context, new_width, Indent::empty()));
756 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
757 let else_expr = else_node.expr.as_ref().unwrap();
758 let else_str = try_opt!(else_expr.rewrite(context, new_width, Indent::empty()));
760 // FIXME: this check shouldn't be necessary. Rewrites should either fail
761 // or wrap to a newline when the object does not fit the width.
762 let fits_line = fixed_cost + pat_expr_str.len() + if_str.len() + else_str.len() <= width;
764 if fits_line && !if_str.contains('\n') && !else_str.contains('\n') {
765 return Some(format!("if {} {{ {} }} else {{ {} }}",
775 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
776 let snippet = codemap.span_to_snippet(block.span).unwrap();
777 contains_comment(&snippet)
780 // Checks that a block contains no statements, an expression and no comments.
781 // FIXME: incorrectly returns false when comment is contained completely within
783 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
784 block.stmts.is_empty() && block.expr.is_some() && !block_contains_comment(block, codemap)
787 /// Checks whether a block contains at most one statement or expression, and no comments.
788 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
789 (block.stmts.is_empty() || (block.stmts.len() == 1 && block.expr.is_none())) &&
790 !block_contains_comment(block, codemap)
793 /// Checks whether a block contains no statements, expressions, or comments.
794 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
795 block.stmts.is_empty() && block.expr.is_none() && !block_contains_comment(block, codemap)
798 fn is_unsafe_block(block: &ast::Block) -> bool {
799 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
806 // inter-match-arm-comment-rules:
807 // - all comments following a match arm before the start of the next arm
808 // are about the second arm
809 fn rewrite_match_arm_comment(context: &RewriteContext,
813 arm_indent_str: &str)
815 // The leading "," is not part of the arm-comment
816 let missed_str = match missed_str.find_uncommented(",") {
817 Some(n) => &missed_str[n + 1..],
818 None => &missed_str[..],
821 let mut result = String::new();
822 // any text not preceeded by a newline is pushed unmodified to the block
823 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
824 result.push_str(&missed_str[..first_brk]);
825 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
827 let first = missed_str.find(|c: char| !c.is_whitespace()).unwrap_or(missed_str.len());
828 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
829 // Excessive vertical whitespace before comment should be preserved
830 // TODO handle vertical whitespace better
833 let missed_str = missed_str[first..].trim();
834 if !missed_str.is_empty() {
835 let comment = try_opt!(rewrite_comment(&missed_str,
841 result.push_str(arm_indent_str);
842 result.push_str(&comment);
848 fn rewrite_match(context: &RewriteContext,
860 let cond_budget = try_opt!(width.checked_sub(8));
861 let cond_str = try_opt!(cond.rewrite(context, cond_budget, offset + 6));
862 let mut result = format!("match {} {{", cond_str);
864 let nested_context = context.nested_context();
865 let arm_indent = nested_context.block_indent;
866 let arm_indent_str = arm_indent.to_string(context.config);
868 let open_brace_pos = context.codemap
869 .span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])), "{");
871 for (i, arm) in arms.iter().enumerate() {
872 // Make sure we get the stuff between arms.
873 let missed_str = if i == 0 {
874 context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
876 context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
878 let comment = try_opt!(rewrite_match_arm_comment(context,
883 result.push_str(&comment);
885 result.push_str(&arm_indent_str);
887 let arm_str = arm.rewrite(&nested_context,
888 context.config.max_width - arm_indent.width(),
890 if let Some(ref arm_str) = arm_str {
891 result.push_str(arm_str);
893 // We couldn't format the arm, just reproduce the source.
894 let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
895 result.push_str(&snippet);
896 result.push_str(arm_comma(&context.config, &arm, &arm.body));
899 // BytePos(1) = closing match brace.
900 let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
901 let last_comment = context.snippet(last_span);
902 let comment = try_opt!(rewrite_match_arm_comment(context,
907 result.push_str(&comment);
909 result.push_str(&context.block_indent.to_string(context.config));
914 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
915 let &ast::Arm { ref attrs, ref pats, .. } = arm;
916 if !attrs.is_empty() {
917 return attrs[0].span.lo;
923 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
927 fn arm_comma(config: &Config, arm: &ast::Arm, body: &ast::Expr) -> &'static str {
928 if !config.match_wildcard_trailing_comma {
929 if arm.pats.len() == 1 && arm.pats[0].node == ast::PatKind::Wild && arm.guard.is_none() {
934 if config.match_block_trailing_comma {
936 } else if let ast::ExprKind::Block(ref block) = body.node {
937 if let ast::BlockCheckMode::Default = block.rules {
948 impl Rewrite for ast::Arm {
949 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
950 let &ast::Arm { ref attrs, ref pats, ref guard, ref body } = self;
951 let indent_str = offset.to_string(context.config);
953 // FIXME this is all a bit grotty, would be nice to abstract out the
954 // treatment of attributes.
955 let attr_str = if !attrs.is_empty() {
956 // We only use this visitor for the attributes, should we use it for
958 let mut attr_visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
959 attr_visitor.block_indent = context.block_indent;
960 attr_visitor.last_pos = attrs[0].span.lo;
961 if attr_visitor.visit_attrs(attrs) {
962 // Attributes included a skip instruction.
965 attr_visitor.format_missing(pats[0].span.lo);
966 attr_visitor.buffer.to_string()
973 let pat_budget = try_opt!(width.checked_sub(5));
974 let pat_strs = try_opt!(pats.iter()
975 .map(|p| p.rewrite(context, pat_budget, offset))
976 .collect::<Option<Vec<_>>>());
978 let mut total_width = pat_strs.iter().fold(0, |a, p| a + p.len());
980 total_width += (pat_strs.len() - 1) * 3;
982 let mut vertical = total_width > pat_budget || pat_strs.iter().any(|p| p.contains('\n'));
983 if !vertical && context.config.take_source_hints {
984 // If the patterns were previously stacked, keep them stacked.
985 let pat_span = mk_sp(pats[0].span.lo, pats[pats.len() - 1].span.hi);
986 let pat_str = context.snippet(pat_span);
987 vertical = pat_str.contains('\n');
990 let pats_width = if vertical {
991 pat_strs.last().unwrap().len()
996 let mut pats_str = String::new();
998 if !pats_str.is_empty() {
1000 pats_str.push_str(" |\n");
1001 pats_str.push_str(&indent_str);
1003 pats_str.push_str(" | ");
1006 pats_str.push_str(&p);
1009 let guard_str = try_opt!(rewrite_guard(context, guard, width, offset, pats_width));
1011 let pats_str = format!("{}{}", pats_str, guard_str);
1012 // Where the next text can start.
1013 let mut line_start = last_line_width(&pats_str);
1014 if !pats_str.contains('\n') {
1015 line_start += offset.width();
1018 let body = match **body {
1019 ast::Expr { node: ast::ExprKind::Block(ref block), .. }
1020 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) &&
1021 context.config.wrap_match_arms => block.expr.as_ref().map(|e| &**e).unwrap(),
1025 let comma = arm_comma(&context.config, self, body);
1027 // Let's try and get the arm body on the same line as the condition.
1029 if context.config.max_width > line_start + comma.len() + 4 {
1030 let budget = context.config.max_width - line_start - comma.len() - 4;
1031 let offset = Indent::new(offset.block_indent, line_start + 4 - offset.block_indent);
1032 let rewrite = nop_block_collapse(body.rewrite(context, budget, offset), budget);
1033 let is_block = if let ast::ExprKind::Block(..) = body.node {
1040 Some(ref body_str) if !body_str.contains('\n') || !context.config.wrap_match_arms ||
1042 return Some(format!("{}{} => {}{}",
1043 attr_str.trim_left(),
1052 // FIXME: we're doing a second rewrite of the expr; This may not be
1054 let body_budget = try_opt!(width.checked_sub(context.config.tab_spaces));
1055 let indent = context.block_indent.block_indent(context.config);
1056 let inner_context = &RewriteContext { block_indent: indent, ..*context };
1057 let next_line_body = try_opt!(nop_block_collapse(body.rewrite(inner_context,
1061 let indent_str = offset.block_indent(context.config).to_string(context.config);
1062 let (body_prefix, body_suffix) = if context.config.wrap_match_arms {
1063 if context.config.match_block_trailing_comma {
1072 Some(format!("{}{} =>{}\n{}{}\n{}{}",
1073 attr_str.trim_left(),
1078 offset.to_string(context.config),
1083 // The `if ...` guard on a match arm.
1084 fn rewrite_guard(context: &RewriteContext,
1085 guard: &Option<ptr::P<ast::Expr>>,
1088 // The amount of space used up on this line for the pattern in
1089 // the arm (excludes offset).
1090 pattern_width: usize)
1092 if let Some(ref guard) = *guard {
1093 // First try to fit the guard string on the same line as the pattern.
1094 // 4 = ` if `, 5 = ` => {`
1095 let overhead = pattern_width + 4 + 5;
1096 if overhead < width {
1097 let cond_str = guard.rewrite(context, width - overhead, offset + pattern_width + 4);
1098 if let Some(cond_str) = cond_str {
1099 return Some(format!(" if {}", cond_str));
1103 // Not enough space to put the guard after the pattern, try a newline.
1104 let overhead = context.config.tab_spaces + 4 + 5;
1105 if overhead < width {
1106 let cond_str = guard.rewrite(context,
1108 offset.block_indent(context.config));
1109 if let Some(cond_str) = cond_str {
1110 return Some(format!("\n{}if {}",
1111 offset.block_indent(context.config).to_string(context.config),
1122 fn rewrite_pat_expr(context: &RewriteContext,
1123 pat: Option<&ast::Pat>,
1126 // Connecting piece between pattern and expression,
1127 // *without* trailing space.
1132 let pat_offset = offset + matcher.len();
1133 let mut result = match pat {
1135 let pat_budget = try_opt!(width.checked_sub(connector.len() + matcher.len()));
1136 let pat_string = try_opt!(pat.rewrite(context, pat_budget, pat_offset));
1137 format!("{}{}{}", matcher, pat_string, connector)
1139 None => String::new(),
1142 // Consider only the last line of the pat string.
1143 let extra_offset = extra_offset(&result, offset);
1145 // The expression may (partionally) fit on the current line.
1146 if width > extra_offset + 1 {
1147 let spacer = if pat.is_some() {
1153 let expr_rewrite = expr.rewrite(context,
1154 width - extra_offset - spacer.len(),
1155 offset + extra_offset + spacer.len());
1157 if let Some(expr_string) = expr_rewrite {
1158 result.push_str(spacer);
1159 result.push_str(&expr_string);
1160 return Some(result);
1164 // The expression won't fit on the current line, jump to next.
1166 result.push_str(&pat_offset.to_string(context.config));
1168 let expr_rewrite = expr.rewrite(context,
1169 context.config.max_width - pat_offset.width(),
1171 result.push_str(&&try_opt!(expr_rewrite));
1176 fn rewrite_string_lit(context: &RewriteContext,
1181 let string_lit = context.snippet(span);
1183 if !context.config.format_strings && !context.config.force_format_strings {
1184 return Some(string_lit);
1187 if !context.config.force_format_strings &&
1188 !string_requires_rewrite(context, span, &string_lit, width, offset) {
1189 return Some(string_lit);
1192 let fmt = StringFormat {
1200 config: context.config,
1203 // Remove the quote characters.
1204 let str_lit = &string_lit[1..string_lit.len() - 1];
1206 rewrite_string(str_lit, &fmt)
1209 fn string_requires_rewrite(context: &RewriteContext,
1215 if context.codemap.lookup_char_pos(span.lo).col.0 != offset.width() {
1219 for (i, line) in string.lines().enumerate() {
1221 if line.len() > width {
1225 if line.len() > width + offset.width() {
1234 pub fn rewrite_call<R>(context: &RewriteContext,
1236 args: &[ptr::P<ast::Expr>],
1243 let closure = |callee_max_width| {
1244 rewrite_call_inner(context, callee, callee_max_width, args, span, width, offset)
1248 let max_width = try_opt!(width.checked_sub(2));
1249 binary_search(1, max_width, closure)
1252 fn rewrite_call_inner<R>(context: &RewriteContext,
1254 max_callee_width: usize,
1255 args: &[ptr::P<ast::Expr>],
1259 -> Result<String, Ordering>
1262 let callee = callee.borrow();
1263 // FIXME using byte lens instead of char lens (and probably all over the
1265 let callee_str = match callee.rewrite(context, max_callee_width, offset) {
1267 if !string.contains('\n') && string.len() > max_callee_width {
1268 panic!("{:?} {}", string, max_callee_width);
1273 None => return Err(Ordering::Greater),
1276 let span_lo = context.codemap.span_after(span, "(");
1277 let span = mk_sp(span_lo, span.hi);
1279 let extra_offset = extra_offset(&callee_str, offset);
1281 let remaining_width = match width.checked_sub(extra_offset + 2) {
1283 None => return Err(Ordering::Greater),
1285 let offset = offset + extra_offset + 1;
1286 let arg_count = args.len();
1287 let block_indent = if arg_count == 1 {
1288 context.block_indent
1292 let inner_context = &RewriteContext { block_indent: block_indent, ..*context };
1294 let items = itemize_list(context.codemap,
1297 |item| item.span.lo,
1298 |item| item.span.hi,
1299 |item| item.rewrite(&inner_context, remaining_width, offset),
1302 let mut item_vec: Vec<_> = items.collect();
1304 // Try letting the last argument overflow to the next line with block
1305 // indentation. If its first line fits on one line with the other arguments,
1306 // we format the function arguments horizontally.
1307 let overflow_last = match args.last().map(|x| &x.node) {
1308 Some(&ast::ExprKind::Closure(..)) |
1309 Some(&ast::ExprKind::Block(..)) if arg_count > 1 => true,
1311 } && context.config.chains_overflow_last;
1313 let mut orig_last = None;
1314 let mut placeholder = None;
1316 // Replace the last item with its first line to see if it fits with
1319 let inner_context = &RewriteContext { block_indent: context.block_indent, ..*context };
1320 let rewrite = args.last().unwrap().rewrite(&inner_context, remaining_width, offset);
1322 if let Some(rewrite) = rewrite {
1323 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
1324 placeholder = Some(rewrite);
1326 swap(&mut item_vec[arg_count - 1].item, &mut orig_last);
1327 item_vec[arg_count - 1].item = rewrite_first_line;
1331 let tactic = definitive_tactic(&item_vec,
1332 ListTactic::LimitedHorizontalVertical(context.config
1336 // Replace the stub with the full overflowing last argument if the rewrite
1337 // succeeded and its first line fits with the other arguments.
1338 match (overflow_last, tactic, placeholder) {
1339 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
1340 item_vec[arg_count - 1].item = placeholder;
1343 item_vec[arg_count - 1].item = orig_last;
1348 let fmt = ListFormatting {
1351 trailing_separator: SeparatorTactic::Never,
1354 ends_with_newline: false,
1355 config: context.config,
1358 let list_str = match write_list(&item_vec, &fmt) {
1360 None => return Err(Ordering::Less),
1363 Ok(format!("{}({})", callee_str, list_str))
1366 fn rewrite_paren(context: &RewriteContext,
1367 subexpr: &ast::Expr,
1371 debug!("rewrite_paren, width: {}, offset: {:?}", width, offset);
1372 // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
1373 // paren on the same line as the subexpr.
1374 let subexpr_str = subexpr.rewrite(context, try_opt!(width.checked_sub(2)), offset + 1);
1375 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1376 subexpr_str.map(|s| format!("({})", s))
1379 fn rewrite_struct_lit<'a>(context: &RewriteContext,
1381 fields: &'a [ast::Field],
1382 base: Option<&'a ast::Expr>,
1387 debug!("rewrite_struct_lit: width {}, offset {:?}", width, offset);
1388 assert!(!fields.is_empty() || base.is_some());
1390 enum StructLitField<'a> {
1391 Regular(&'a ast::Field),
1392 Base(&'a ast::Expr),
1396 let path_budget = try_opt!(width.checked_sub(2));
1397 let path_str = try_opt!(rewrite_path(context, true, None, path, path_budget, offset));
1399 // Foo { a: Foo } - indent is +3, width is -5.
1400 let h_budget = width.checked_sub(path_str.len() + 5).unwrap_or(0);
1401 // The 1 taken from the v_budget is for the comma.
1402 let (indent, v_budget) = match context.config.struct_lit_style {
1403 StructLitStyle::Visual => (offset + path_str.len() + 3, h_budget),
1404 StructLitStyle::Block => {
1405 // If we are all on one line, then we'll ignore the indent, and we
1406 // have a smaller budget.
1407 let indent = context.block_indent.block_indent(context.config);
1408 let v_budget = context.config.max_width.checked_sub(indent.width()).unwrap_or(0);
1413 let field_iter = fields.into_iter()
1414 .map(StructLitField::Regular)
1415 .chain(base.into_iter().map(StructLitField::Base));
1417 let inner_context = &RewriteContext { block_indent: indent, ..*context };
1419 let items = itemize_list(context.codemap,
1424 StructLitField::Regular(ref field) => field.span.lo,
1425 StructLitField::Base(ref expr) => {
1426 let last_field_hi = fields.last().map_or(span.lo,
1430 let snippet = context.snippet(mk_sp(last_field_hi,
1432 let pos = snippet.find_uncommented("..").unwrap();
1433 last_field_hi + BytePos(pos as u32)
1439 StructLitField::Regular(ref field) => field.span.hi,
1440 StructLitField::Base(ref expr) => expr.span.hi,
1445 StructLitField::Regular(ref field) => {
1446 rewrite_field(inner_context,
1448 v_budget.checked_sub(1).unwrap_or(0),
1451 StructLitField::Base(ref expr) => {
1453 expr.rewrite(inner_context,
1454 try_opt!(v_budget.checked_sub(2)),
1456 .map(|s| format!("..{}", s))
1460 context.codemap.span_after(span, "{"),
1462 let item_vec = items.collect::<Vec<_>>();
1465 let mut prelim_tactic = match (context.config.struct_lit_style, fields.len()) {
1466 (StructLitStyle::Visual, 1) => ListTactic::HorizontalVertical,
1467 _ => context.config.struct_lit_multiline_style.to_list_tactic(),
1470 if prelim_tactic == ListTactic::HorizontalVertical && fields.len() > 1 {
1471 prelim_tactic = ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width);
1474 definitive_tactic(&item_vec, prelim_tactic, h_budget)
1477 let budget = match tactic {
1478 DefinitiveListTactic::Horizontal => h_budget,
1482 let ends_with_newline = context.config.struct_lit_style != StructLitStyle::Visual &&
1483 tactic == DefinitiveListTactic::Vertical;
1485 let fmt = ListFormatting {
1488 trailing_separator: if base.is_some() {
1489 SeparatorTactic::Never
1491 context.config.struct_lit_trailing_comma
1495 ends_with_newline: ends_with_newline,
1496 config: context.config,
1498 let fields_str = try_opt!(write_list(&item_vec, &fmt));
1500 let format_on_newline = || {
1501 let inner_indent = context.block_indent
1502 .block_indent(context.config)
1503 .to_string(context.config);
1504 let outer_indent = context.block_indent.to_string(context.config);
1505 Some(format!("{} {{\n{}{}\n{}}}",
1512 match (context.config.struct_lit_style, context.config.struct_lit_multiline_style) {
1513 (StructLitStyle::Block, _) if fields_str.contains('\n') || fields_str.len() > h_budget => {
1516 (StructLitStyle::Block, MultilineStyle::ForceMulti) => format_on_newline(),
1517 _ => Some(format!("{} {{ {} }}", path_str, fields_str)),
1520 // FIXME if context.config.struct_lit_style == Visual, but we run out
1521 // of space, we should fall back to BlockIndent.
1524 fn rewrite_field(context: &RewriteContext,
1529 let name = &field.ident.node.to_string();
1530 let overhead = name.len() + 2;
1531 let expr = field.expr.rewrite(context,
1532 try_opt!(width.checked_sub(overhead)),
1536 Some(e) => Some(format!("{}: {}", name, e)),
1538 let expr_offset = offset.block_indent(&context.config);
1539 let expr = field.expr.rewrite(context,
1540 try_opt!(context.config
1542 .checked_sub(expr_offset.width())),
1544 expr.map(|s| format!("{}:\n{}{}", name, expr_offset.to_string(&context.config), s))
1549 pub fn rewrite_tuple<'a, I>(context: &RewriteContext,
1555 where I: ExactSizeIterator,
1556 <I as Iterator>::Item: Deref,
1557 <I::Item as Deref>::Target: Rewrite + Spanned + 'a
1559 let indent = offset + 1;
1560 // In case of length 1, need a trailing comma
1561 if items.len() == 1 {
1563 let budget = try_opt!(width.checked_sub(3));
1564 return items.next().unwrap().rewrite(context, budget, indent).map(|s| format!("({},)", s));
1567 let list_lo = context.codemap.span_after(span, "(");
1568 let items = itemize_list(context.codemap,
1571 |item| item.span().lo,
1572 |item| item.span().hi,
1574 let inner_width = try_opt!(context.config
1576 .checked_sub(indent.width() +
1578 item.rewrite(context, inner_width, indent)
1581 span.hi - BytePos(1));
1582 let budget = try_opt!(width.checked_sub(2));
1583 let list_str = try_opt!(format_item_list(items, budget, indent, context.config));
1585 Some(format!("({})", list_str))
1588 fn rewrite_binary_op(context: &RewriteContext,
1595 // FIXME: format comments between operands and operator
1597 let operator_str = context.snippet(op.span);
1599 // Get "full width" rhs and see if it fits on the current line. This
1600 // usually works fairly well since it tends to place operands of
1601 // operations with high precendence close together.
1602 let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
1604 // Second condition is needed in case of line break not caused by a
1605 // shortage of space, but by end-of-line comments, for example.
1606 // Note that this is non-conservative, but its just to see if it's even
1607 // worth trying to put everything on one line.
1608 if rhs_result.len() + 2 + operator_str.len() < width && !rhs_result.contains('\n') {
1609 // 1 = space between lhs expr and operator
1610 if let Some(mut result) = lhs.rewrite(context, width - 1 - operator_str.len(), offset) {
1612 result.push_str(&operator_str);
1615 let remaining_width = width.checked_sub(last_line_width(&result)).unwrap_or(0);
1617 if rhs_result.len() <= remaining_width {
1618 result.push_str(&rhs_result);
1619 return Some(result);
1622 if let Some(rhs_result) = rhs.rewrite(context, remaining_width, offset + result.len()) {
1623 if rhs_result.len() <= remaining_width {
1624 result.push_str(&rhs_result);
1625 return Some(result);
1631 // We have to use multiple lines.
1633 // Re-evaluate the lhs because we have more space now:
1634 let budget = try_opt!(context.config
1636 .checked_sub(offset.width() + 1 + operator_str.len()));
1637 Some(format!("{} {}\n{}{}",
1638 try_opt!(lhs.rewrite(context, budget, offset)),
1640 offset.to_string(context.config),
1644 pub fn rewrite_unary_prefix<R: Rewrite>(context: &RewriteContext,
1650 rewrite.rewrite(context,
1651 try_opt!(width.checked_sub(prefix.len())),
1652 offset + prefix.len())
1653 .map(|r| format!("{}{}", prefix, r))
1656 fn rewrite_unary_op(context: &RewriteContext,
1662 // For some reason, an UnOp is not spanned like BinOp!
1663 let operator_str = match *op {
1664 ast::UnOp::Deref => "*",
1665 ast::UnOp::Not => "!",
1666 ast::UnOp::Neg => "-",
1668 rewrite_unary_prefix(context, operator_str, expr, width, offset)
1671 fn rewrite_assignment(context: &RewriteContext,
1674 op: Option<&ast::BinOp>,
1678 let operator_str = match op {
1679 Some(op) => context.snippet(op.span),
1680 None => "=".to_owned(),
1683 // 1 = space between lhs and operator.
1684 let max_width = try_opt!(width.checked_sub(operator_str.len() + 1));
1685 let lhs_str = format!("{} {}",
1686 try_opt!(lhs.rewrite(context, max_width, offset)),
1689 rewrite_assign_rhs(&context, lhs_str, rhs, width, offset)
1692 // The left hand side must contain everything up to, and including, the
1693 // assignment operator.
1694 pub fn rewrite_assign_rhs<S: Into<String>>(context: &RewriteContext,
1700 let mut result = lhs.into();
1701 let last_line_width = last_line_width(&result) -
1702 if result.contains('\n') {
1707 // 1 = space between operator and rhs.
1708 let max_width = try_opt!(width.checked_sub(last_line_width + 1));
1709 let rhs = ex.rewrite(&context, max_width, offset + last_line_width + 1);
1714 result.push_str(&new_str)
1717 // Expression did not fit on the same line as the identifier. Retry
1718 // on the next line.
1719 let new_offset = offset.block_indent(context.config);
1720 result.push_str(&format!("\n{}", new_offset.to_string(context.config)));
1722 // FIXME: we probably should related max_width to width instead of
1723 // config.max_width where is the 1 coming from anyway?
1724 let max_width = try_opt!(context.config.max_width.checked_sub(new_offset.width() + 1));
1725 let inner_context = context.nested_context();
1726 let rhs = ex.rewrite(&inner_context, max_width, new_offset);
1728 result.push_str(&&try_opt!(rhs));
1735 fn rewrite_expr_addrof(context: &RewriteContext,
1736 mutability: ast::Mutability,
1741 let operator_str = match mutability {
1742 ast::Mutability::Immutable => "&",
1743 ast::Mutability::Mutable => "&mut ",
1745 rewrite_unary_prefix(context, operator_str, expr, width, offset)