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, left_most_sub_expr};
25 use visitor::FmtVisitor;
26 use config::{Config, StructLitStyle, MultilineStyle, ElseIfBraceStyle, ControlBraceStyle};
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::parse::classify;
37 impl Rewrite for ast::Expr {
38 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
39 format_expr(self, ExprType::SubExpression, context, width, offset)
49 fn format_expr(expr: &ast::Expr,
51 context: &RewriteContext,
55 let result = match expr.node {
56 ast::ExprKind::Vec(ref expr_vec) => {
57 rewrite_array(expr_vec.iter().map(|e| &**e),
58 mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi),
63 ast::ExprKind::Lit(ref l) => {
65 ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
66 rewrite_string_lit(context, l.span, width, offset)
69 wrap_str(context.snippet(expr.span),
70 context.config.max_width,
76 ast::ExprKind::Call(ref callee, ref args) => {
77 let inner_span = mk_sp(callee.span.hi, expr.span.hi);
78 rewrite_call(context, &**callee, args, inner_span, width, offset)
80 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, width, offset),
81 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
82 rewrite_binary_op(context, op, lhs, rhs, width, offset)
84 ast::ExprKind::Unary(ref op, ref subexpr) => {
85 rewrite_unary_op(context, op, subexpr, width, offset)
87 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
88 rewrite_struct_lit(context,
91 base.as_ref().map(|e| &**e),
96 ast::ExprKind::Tup(ref items) => {
97 rewrite_tuple(context,
98 items.iter().map(|x| &**x),
103 ast::ExprKind::While(ref cond, ref block, label) => {
104 Loop::new_while(None, cond, block, label).rewrite(context, width, offset)
106 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => {
107 Loop::new_while(Some(pat), cond, block, label).rewrite(context, width, offset)
109 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
110 Loop::new_for(pat, cond, block, label).rewrite(context, width, offset)
112 ast::ExprKind::Loop(ref block, label) => {
113 Loop::new_loop(block, label).rewrite(context, width, offset)
115 ast::ExprKind::Block(ref block) => block.rewrite(context, width, offset),
116 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
117 rewrite_if_else(context,
121 else_block.as_ref().map(|e| &**e),
128 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
129 rewrite_if_else(context,
133 else_block.as_ref().map(|e| &**e),
140 ast::ExprKind::Match(ref cond, ref arms) => {
141 rewrite_match(context, cond, arms, width, offset, expr.span)
143 ast::ExprKind::Path(ref qself, ref path) => {
144 rewrite_path(context, true, qself.as_ref(), path, width, offset)
146 ast::ExprKind::Assign(ref lhs, ref rhs) => {
147 rewrite_assignment(context, lhs, rhs, None, width, offset)
149 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
150 rewrite_assignment(context, lhs, rhs, Some(op), width, offset)
152 ast::ExprKind::Again(ref opt_ident) => {
153 let id_str = match *opt_ident {
154 Some(ident) => format!(" {}", ident.node),
155 None => String::new(),
157 wrap_str(format!("continue{}", id_str),
158 context.config.max_width,
162 ast::ExprKind::Break(ref opt_ident) => {
163 let id_str = match *opt_ident {
164 Some(ident) => format!(" {}", ident.node),
165 None => String::new(),
167 wrap_str(format!("break{}", id_str),
168 context.config.max_width,
172 ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
173 rewrite_closure(capture, fn_decl, body, expr.span, context, width, offset)
175 ast::ExprKind::Try(..) |
176 ast::ExprKind::Field(..) |
177 ast::ExprKind::TupField(..) |
178 ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, width, offset),
179 ast::ExprKind::Mac(ref mac) => {
180 // Failure to rewrite a marco should not imply failure to
181 // rewrite the expression.
182 rewrite_macro(mac, None, context, width, offset).or_else(|| {
183 wrap_str(context.snippet(expr.span),
184 context.config.max_width,
189 ast::ExprKind::Ret(None) => {
190 wrap_str("return".to_owned(), context.config.max_width, width, offset)
192 ast::ExprKind::Ret(Some(ref expr)) => {
193 rewrite_unary_prefix(context, "return ", &**expr, width, offset)
195 ast::ExprKind::Box(ref expr) => {
196 rewrite_unary_prefix(context, "box ", &**expr, width, offset)
198 ast::ExprKind::AddrOf(mutability, ref expr) => {
199 rewrite_expr_addrof(context, mutability, expr, width, offset)
201 ast::ExprKind::Cast(ref expr, ref ty) => {
202 rewrite_pair(&**expr, &**ty, "", " as ", "", context, width, offset)
204 ast::ExprKind::Type(ref expr, ref ty) => {
205 rewrite_pair(&**expr, &**ty, "", ": ", "", context, width, offset)
207 ast::ExprKind::Index(ref expr, ref index) => {
208 rewrite_pair(&**expr, &**index, "", "[", "]", context, width, offset)
210 ast::ExprKind::Repeat(ref expr, ref repeats) => {
211 rewrite_pair(&**expr, &**repeats, "[", "; ", "]", context, width, offset)
213 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
214 let delim = match limits {
215 ast::RangeLimits::HalfOpen => "..",
216 ast::RangeLimits::Closed => "...",
219 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
220 (Some(ref lhs), Some(ref rhs)) => {
221 rewrite_pair(&**lhs, &**rhs, "", delim, "", context, width, offset)
223 (None, Some(ref rhs)) => {
224 rewrite_unary_prefix(context, delim, &**rhs, width, offset)
226 (Some(ref lhs), None) => {
227 rewrite_unary_suffix(context, delim, &**lhs, width, offset)
229 (None, None) => wrap_str(delim.into(), context.config.max_width, width, offset),
232 // We do not format these expressions yet, but they should still
233 // satisfy our width restrictions.
234 ast::ExprKind::InPlace(..) |
235 ast::ExprKind::InlineAsm(..) => {
236 wrap_str(context.snippet(expr.span),
237 context.config.max_width,
242 result.and_then(|res| recover_comment_removed(res, expr.span, context, width, offset))
245 pub fn rewrite_pair<LHS, RHS>(lhs: &LHS,
250 context: &RewriteContext,
257 let max_width = try_opt!(width.checked_sub(prefix.len() + infix.len() + suffix.len()));
259 binary_search(1, max_width, |lhs_budget| {
260 let lhs_offset = offset + prefix.len();
261 let lhs_str = match lhs.rewrite(context, lhs_budget, lhs_offset) {
262 Some(result) => result,
263 None => return Err(Ordering::Greater),
266 let last_line_width = last_line_width(&lhs_str);
267 let rhs_budget = match max_width.checked_sub(last_line_width) {
269 None => return Err(Ordering::Less),
271 let rhs_indent = offset + last_line_width + prefix.len() + infix.len();
273 let rhs_str = match rhs.rewrite(context, rhs_budget, rhs_indent) {
274 Some(result) => result,
275 None => return Err(Ordering::Less),
278 Ok(format!("{}{}{}{}{}", prefix, lhs_str, infix, rhs_str, suffix))
282 pub fn rewrite_array<'a, I>(expr_iter: I,
284 context: &RewriteContext,
288 where I: Iterator<Item = &'a ast::Expr>
291 let offset = offset + 1;
292 let inner_context = &RewriteContext { block_indent: offset, ..*context };
293 let max_item_width = try_opt!(width.checked_sub(2));
294 let items = itemize_list(context.codemap,
300 |item| item.rewrite(&inner_context, max_item_width, offset),
303 .collect::<Vec<_>>();
305 let has_long_item = try_opt!(items.iter()
306 .map(|li| li.item.as_ref().map(|s| s.len() > 10))
307 .fold(Some(false), |acc, x| acc.and_then(|y| x.map(|x| x || y))));
309 let tactic = if has_long_item || items.iter().any(ListItem::is_multiline) {
310 definitive_tactic(&items, ListTactic::HorizontalVertical, max_item_width)
312 DefinitiveListTactic::Mixed
315 let fmt = ListFormatting {
318 trailing_separator: SeparatorTactic::Never,
320 width: max_item_width,
321 ends_with_newline: false,
322 config: context.config,
324 let list_str = try_opt!(write_list(&items, &fmt));
326 Some(format!("[{}]", list_str))
329 // This functions is pretty messy because of the rules around closures and blocks:
330 // * the body of a closure is represented by an ast::Block, but that does not
331 // imply there are `{}` (unless the block is empty) (see rust issue #27872),
332 // * if there is a return type, then there must be braces,
333 // * given a closure with braces, whether that is parsed to give an inner block
334 // or not depends on if there is a return type and if there are statements
336 // * if the first expression in the body ends with a block (i.e., is a
337 // statement without needing a semi-colon), then adding or removing braces
338 // can change whether it is treated as an expression or statement.
339 fn rewrite_closure(capture: ast::CaptureBy,
340 fn_decl: &ast::FnDecl,
343 context: &RewriteContext,
347 let mover = if capture == ast::CaptureBy::Value {
352 let offset = offset + mover.len();
354 // 4 = "|| {".len(), which is overconservative when the closure consists of
355 // a single expression.
356 let budget = try_opt!(width.checked_sub(4 + mover.len()));
358 let argument_offset = offset + 1;
359 let ret_str = try_opt!(fn_decl.output.rewrite(context, budget, argument_offset));
360 let force_block = !ret_str.is_empty();
362 // 1 = space between arguments and return type.
363 let horizontal_budget = budget.checked_sub(ret_str.len() + 1).unwrap_or(0);
365 let arg_items = itemize_list(context.codemap,
366 fn_decl.inputs.iter(),
368 |arg| span_lo_for_arg(arg),
369 |arg| span_hi_for_arg(arg),
370 |arg| arg.rewrite(context, budget, argument_offset),
371 context.codemap.span_after(span, "|"),
373 let item_vec = arg_items.collect::<Vec<_>>();
374 let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
375 let budget = match tactic {
376 DefinitiveListTactic::Horizontal => horizontal_budget,
380 let fmt = ListFormatting {
383 trailing_separator: SeparatorTactic::Never,
384 indent: argument_offset,
386 ends_with_newline: false,
387 config: context.config,
389 let list_str = try_opt!(write_list(&item_vec, &fmt));
390 let mut prefix = format!("{}|{}|", mover, list_str);
392 if !ret_str.is_empty() {
393 if prefix.contains('\n') {
395 prefix.push_str(&argument_offset.to_string(context.config));
399 prefix.push_str(&ret_str);
402 if body.expr.is_none() && body.stmts.is_empty() {
403 return Some(format!("{} {{}}", prefix));
406 // 1 = space between `|...|` and body.
407 let extra_offset = extra_offset(&prefix, offset) + 1;
408 let budget = try_opt!(width.checked_sub(extra_offset));
410 // This is where we figure out whether to use braces or not.
411 let mut had_braces = true;
412 let mut inner_block = body;
414 // If there is an inner block and we can ignore it, do so.
415 if body.stmts.is_empty() {
416 if let ast::ExprKind::Block(ref inner) = inner_block.expr.as_ref().unwrap().node {
418 } else if !force_block {
423 let try_single_line = is_simple_block(inner_block, context.codemap) &&
424 inner_block.rules == ast::BlockCheckMode::Default;
426 if try_single_line && !force_block {
427 let must_preserve_braces =
428 !classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(inner_block.expr
431 if !(must_preserve_braces && had_braces) &&
432 (must_preserve_braces || !prefix.contains('\n')) {
433 // If we got here, then we can try to format without braces.
435 let inner_expr = inner_block.expr.as_ref().unwrap();
436 let mut rewrite = inner_expr.rewrite(context, budget, offset + extra_offset);
438 if must_preserve_braces {
439 // If we are here, then failure to rewrite is unacceptable.
440 if rewrite.is_none() {
444 // Checks if rewrite succeeded and fits on a single line.
445 rewrite = and_one_line(rewrite);
448 if let Some(rewrite) = rewrite {
449 return Some(format!("{} {}", prefix, rewrite));
454 // If we fell through the above block, then we need braces, but we might
455 // still prefer a one-liner (we might also have fallen through because of
457 if try_single_line && !prefix.contains('\n') {
458 let inner_expr = inner_block.expr.as_ref().unwrap();
459 // 4 = braces and spaces.
460 let mut rewrite = inner_expr.rewrite(context,
461 try_opt!(budget.checked_sub(4)),
462 offset + extra_offset);
464 // Checks if rewrite succeeded and fits on a single line.
465 rewrite = and_one_line(rewrite);
467 if let Some(rewrite) = rewrite {
468 return Some(format!("{} {{ {} }}", prefix, rewrite));
472 // We couldn't format the closure body as a single line expression; fall
473 // back to block formatting.
474 let body_rewrite = try_opt!(inner_block.rewrite(&context, budget, Indent::empty()));
476 let block_threshold = context.config.closure_block_indent_threshold;
477 if block_threshold < 0 || body_rewrite.matches('\n').count() <= block_threshold as usize {
478 return Some(format!("{} {}", prefix, body_rewrite));
481 // The body of the closure is big enough to be block indented, that means we
483 let mut context = context.clone();
484 context.block_indent.alignment = 0;
485 let body_rewrite = try_opt!(inner_block.rewrite(&context, budget, Indent::empty()));
486 Some(format!("{} {}", prefix, body_rewrite))
489 fn and_one_line(x: Option<String>) -> Option<String> {
490 x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
493 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
494 block_str.map(|block_str| {
495 if block_str.starts_with("{") && budget >= 2 &&
496 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2) {
504 impl Rewrite for ast::Block {
505 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
506 let user_str = context.snippet(self.span);
507 if user_str == "{}" && width >= 2 {
508 return Some(user_str);
511 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
512 visitor.block_indent = context.block_indent;
514 let prefix = match self.rules {
515 ast::BlockCheckMode::Unsafe(..) => {
516 let snippet = context.snippet(self.span);
517 let open_pos = try_opt!(snippet.find_uncommented("{"));
518 visitor.last_pos = self.span.lo + BytePos(open_pos as u32);
520 // Extract comment between unsafe and block start.
521 let trimmed = &snippet[6..open_pos].trim();
523 let prefix = if !trimmed.is_empty() {
524 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
525 let budget = try_opt!(width.checked_sub(9));
526 format!("unsafe {} ",
527 try_opt!(rewrite_comment(trimmed,
536 if is_simple_block(self, context.codemap) && prefix.len() < width {
540 .rewrite(context, width - prefix.len(), offset);
541 if let Some(ref expr_str) = body {
542 let result = format!("{}{{ {} }}", prefix, expr_str);
543 if result.len() <= width && !result.contains('\n') {
551 ast::BlockCheckMode::Default => {
552 visitor.last_pos = self.span.lo;
558 visitor.visit_block(self);
560 Some(format!("{}{}", prefix, visitor.buffer))
564 impl Rewrite for ast::Stmt {
565 fn rewrite(&self, context: &RewriteContext, _width: usize, offset: Indent) -> Option<String> {
566 let result = match self.node {
567 ast::StmtKind::Decl(ref decl, _) => {
568 if let ast::DeclKind::Local(ref local) = decl.node {
569 local.rewrite(context, context.config.max_width, offset)
574 ast::StmtKind::Expr(ref ex, _) |
575 ast::StmtKind::Semi(ref ex, _) => {
576 let suffix = if semicolon_for_stmt(self) { ";" } else { "" };
581 context.config.max_width - offset.width() - suffix.len(),
585 ast::StmtKind::Mac(..) => None,
587 result.and_then(|res| recover_comment_removed(res, self.span, context, _width, offset))
591 // Abstraction over for, while and loop expressions
593 cond: Option<&'a ast::Expr>,
594 block: &'a ast::Block,
595 label: Option<ast::SpannedIdent>,
596 pat: Option<&'a ast::Pat>,
603 fn new_loop(block: &'a ast::Block, label: Option<ast::SpannedIdent>) -> Loop<'a> {
615 fn new_while(pat: Option<&'a ast::Pat>,
617 block: &'a ast::Block,
618 label: Option<ast::SpannedIdent>)
634 fn new_for(pat: &'a ast::Pat,
636 block: &'a ast::Block,
637 label: Option<ast::SpannedIdent>)
651 impl<'a> Rewrite for Loop<'a> {
652 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
653 let label_string = rewrite_label(self.label);
655 let inner_width = try_opt!(width.checked_sub(self.keyword.len() + 2 + label_string.len()));
656 let inner_offset = offset + self.keyword.len() + label_string.len();
658 let pat_expr_string = match self.cond {
660 try_opt!(rewrite_pat_expr(context,
668 None => String::new(),
671 let alt_block_sep = String::from("\n") + &context.block_indent.to_string(context.config);
672 let block_sep = match context.config.control_brace_style {
673 ControlBraceStyle::AlwaysNextLine => alt_block_sep.as_str(),
674 ControlBraceStyle::AlwaysSameLine => " ",
676 // FIXME: this drops any comment between "loop" and the block.
678 .rewrite(context, width, offset)
680 format!("{}{}{}{}{}",
690 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
692 Some(ident) => format!("{}: ", ident.node),
693 None => "".to_owned(),
697 fn extract_comment(span: Span,
698 context: &RewriteContext,
702 let comment_str = context.snippet(span);
703 if contains_comment(&comment_str) {
705 try_opt!(rewrite_comment(comment_str.trim(), false, width, offset, context.config));
706 Some(format!("\n{indent}{}\n{indent}",
708 indent = offset.to_string(context.config)))
714 // Rewrites if-else blocks. If let Some(_) = pat, the expression is
715 // treated as an if-let-else expression.
716 fn rewrite_if_else(context: &RewriteContext,
719 if_block: &ast::Block,
720 else_block_opt: Option<&ast::Expr>,
722 pat: Option<&ast::Pat>,
725 allow_single_line: bool)
727 // 3 = "if ", 2 = " {"
728 let pat_penalty = match context.config.else_if_brace_style {
729 ElseIfBraceStyle::AlwaysNextLine => 3,
732 let pat_expr_string = try_opt!(rewrite_pat_expr(context,
737 try_opt!(width.checked_sub(pat_penalty)),
740 // Try to format if-else on single line.
741 if expr_type == ExprType::SubExpression && allow_single_line &&
742 context.config.single_line_if_else_max_width > 0 {
743 let trial = single_line_if_else(context, &pat_expr_string, if_block, else_block_opt, width);
745 if trial.is_some() &&
746 trial.as_ref().unwrap().len() <= context.config.single_line_if_else_max_width {
751 let if_block_string = try_opt!(if_block.rewrite(context, width, offset));
753 let between_if_cond = mk_sp(context.codemap.span_after(span, "if"),
754 pat.map_or(cond.span.lo,
755 |_| context.codemap.span_before(span, "let")));
757 let between_if_cond_comment = extract_comment(between_if_cond, &context, offset, width);
759 let after_cond_comment = extract_comment(mk_sp(cond.span.hi, if_block.span.lo),
764 let alt_block_sep = String::from("\n") + &context.block_indent.to_string(context.config);
765 let after_sep = match context.config.else_if_brace_style {
766 ElseIfBraceStyle::AlwaysNextLine => alt_block_sep.as_str(),
769 let mut result = format!("if{}{}{}{}",
770 between_if_cond_comment.as_ref().map_or(" ", |str| &**str),
772 after_cond_comment.as_ref().map_or(after_sep, |str| &**str),
775 if let Some(else_block) = else_block_opt {
776 let mut last_in_chain = false;
777 let rewrite = match else_block.node {
778 // If the else expression is another if-else expression, prevent it
779 // from being formatted on a single line.
780 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
781 rewrite_if_else(context,
785 next_else_block.as_ref().map(|e| &**e),
786 mk_sp(else_block.span.lo, span.hi),
792 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
793 rewrite_if_else(context,
797 next_else_block.as_ref().map(|e| &**e),
798 mk_sp(else_block.span.lo, span.hi),
805 last_in_chain = true;
806 else_block.rewrite(context, width, offset)
810 let between_if_else_block =
811 mk_sp(if_block.span.hi,
812 context.codemap.span_before(mk_sp(if_block.span.hi, else_block.span.lo), "else"));
813 let between_if_else_block_comment =
814 extract_comment(between_if_else_block, &context, offset, width);
816 let after_else = mk_sp(context.codemap
817 .span_after(mk_sp(if_block.span.hi, else_block.span.lo),
820 let after_else_comment = extract_comment(after_else, &context, offset, width);
822 let between_sep = match context.config.else_if_brace_style {
823 ElseIfBraceStyle::AlwaysNextLine |
824 ElseIfBraceStyle::ClosingNextLine => alt_block_sep.as_str(),
825 ElseIfBraceStyle::AlwaysSameLine => " ",
827 let after_sep = match context.config.else_if_brace_style {
828 ElseIfBraceStyle::AlwaysNextLine if last_in_chain => alt_block_sep.as_str(),
831 try_opt!(write!(&mut result,
833 between_if_else_block_comment.as_ref()
834 .map_or(between_sep, |str| &**str),
835 after_else_comment.as_ref().map_or(after_sep, |str| &**str))
837 result.push_str(&&try_opt!(rewrite));
843 fn single_line_if_else(context: &RewriteContext,
845 if_node: &ast::Block,
846 else_block_opt: Option<&ast::Expr>,
849 let else_block = try_opt!(else_block_opt);
850 let fixed_cost = "if { } else { }".len();
852 if let ast::ExprKind::Block(ref else_node) = else_block.node {
853 if !is_simple_block(if_node, context.codemap) ||
854 !is_simple_block(else_node, context.codemap) || pat_expr_str.contains('\n') {
858 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
859 let if_expr = if_node.expr.as_ref().unwrap();
860 let if_str = try_opt!(if_expr.rewrite(context, new_width, Indent::empty()));
862 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
863 let else_expr = else_node.expr.as_ref().unwrap();
864 let else_str = try_opt!(else_expr.rewrite(context, new_width, Indent::empty()));
866 // FIXME: this check shouldn't be necessary. Rewrites should either fail
867 // or wrap to a newline when the object does not fit the width.
868 let fits_line = fixed_cost + pat_expr_str.len() + if_str.len() + else_str.len() <= width;
870 if fits_line && !if_str.contains('\n') && !else_str.contains('\n') {
871 return Some(format!("if {} {{ {} }} else {{ {} }}",
881 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
882 let snippet = codemap.span_to_snippet(block.span).unwrap();
883 contains_comment(&snippet)
886 // Checks that a block contains no statements, an expression and no comments.
887 // FIXME: incorrectly returns false when comment is contained completely within
889 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
890 block.stmts.is_empty() && block.expr.is_some() && !block_contains_comment(block, codemap)
893 /// Checks whether a block contains at most one statement or expression, and no comments.
894 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
895 (block.stmts.is_empty() || (block.stmts.len() == 1 && block.expr.is_none())) &&
896 !block_contains_comment(block, codemap)
899 /// Checks whether a block contains no statements, expressions, or comments.
900 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
901 block.stmts.is_empty() && block.expr.is_none() && !block_contains_comment(block, codemap)
904 fn is_unsafe_block(block: &ast::Block) -> bool {
905 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
912 // inter-match-arm-comment-rules:
913 // - all comments following a match arm before the start of the next arm
914 // are about the second arm
915 fn rewrite_match_arm_comment(context: &RewriteContext,
919 arm_indent_str: &str)
921 // The leading "," is not part of the arm-comment
922 let missed_str = match missed_str.find_uncommented(",") {
923 Some(n) => &missed_str[n + 1..],
924 None => &missed_str[..],
927 let mut result = String::new();
928 // any text not preceeded by a newline is pushed unmodified to the block
929 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
930 result.push_str(&missed_str[..first_brk]);
931 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
933 let first = missed_str.find(|c: char| !c.is_whitespace()).unwrap_or(missed_str.len());
934 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
935 // Excessive vertical whitespace before comment should be preserved
936 // TODO handle vertical whitespace better
939 let missed_str = missed_str[first..].trim();
940 if !missed_str.is_empty() {
942 try_opt!(rewrite_comment(&missed_str, false, width, arm_indent, context.config));
944 result.push_str(arm_indent_str);
945 result.push_str(&comment);
951 fn rewrite_match(context: &RewriteContext,
963 let cond_budget = try_opt!(width.checked_sub(8));
964 let cond_str = try_opt!(cond.rewrite(context, cond_budget, offset + 6));
965 let alt_block_sep = String::from("\n") + &context.block_indent.to_string(context.config);
966 let block_sep = match context.config.control_brace_style {
967 ControlBraceStyle::AlwaysSameLine => " ",
968 ControlBraceStyle::AlwaysNextLine => alt_block_sep.as_str(),
970 let mut result = format!("match {}{}{{", cond_str, block_sep);
972 let nested_context = context.nested_context();
973 let arm_indent = nested_context.block_indent;
974 let arm_indent_str = arm_indent.to_string(context.config);
976 let open_brace_pos = context.codemap
977 .span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])), "{");
979 for (i, arm) in arms.iter().enumerate() {
980 // Make sure we get the stuff between arms.
981 let missed_str = if i == 0 {
982 context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
984 context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
986 let comment = try_opt!(rewrite_match_arm_comment(context,
991 result.push_str(&comment);
993 result.push_str(&arm_indent_str);
995 let arm_str = arm.rewrite(&nested_context,
996 context.config.max_width - arm_indent.width(),
998 if let Some(ref arm_str) = arm_str {
999 result.push_str(arm_str);
1001 // We couldn't format the arm, just reproduce the source.
1002 let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
1003 result.push_str(&snippet);
1004 result.push_str(arm_comma(&context.config, &arm, &arm.body));
1007 // BytePos(1) = closing match brace.
1008 let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
1009 let last_comment = context.snippet(last_span);
1010 let comment = try_opt!(rewrite_match_arm_comment(context,
1015 result.push_str(&comment);
1017 result.push_str(&context.block_indent.to_string(context.config));
1022 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
1023 let &ast::Arm { ref attrs, ref pats, .. } = arm;
1024 if !attrs.is_empty() {
1025 return attrs[0].span.lo;
1031 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
1035 fn arm_comma(config: &Config, arm: &ast::Arm, body: &ast::Expr) -> &'static str {
1036 if !config.match_wildcard_trailing_comma {
1037 if arm.pats.len() == 1 && arm.pats[0].node == ast::PatKind::Wild && arm.guard.is_none() {
1042 if config.match_block_trailing_comma {
1044 } else if let ast::ExprKind::Block(ref block) = body.node {
1045 if let ast::BlockCheckMode::Default = block.rules {
1056 impl Rewrite for ast::Arm {
1057 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1058 let &ast::Arm { ref attrs, ref pats, ref guard, ref body } = self;
1060 // FIXME this is all a bit grotty, would be nice to abstract out the
1061 // treatment of attributes.
1062 let attr_str = if !attrs.is_empty() {
1063 // We only use this visitor for the attributes, should we use it for
1065 let mut attr_visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1066 attr_visitor.block_indent = context.block_indent;
1067 attr_visitor.last_pos = attrs[0].span.lo;
1068 if attr_visitor.visit_attrs(attrs) {
1069 // Attributes included a skip instruction.
1072 attr_visitor.format_missing(pats[0].span.lo);
1073 attr_visitor.buffer.to_string()
1080 let pat_budget = try_opt!(width.checked_sub(5));
1081 let pat_strs = try_opt!(pats.iter()
1082 .map(|p| p.rewrite(context, pat_budget, offset))
1083 .collect::<Option<Vec<_>>>());
1085 let all_simple = pat_strs.iter().all(|p| pat_is_simple(&p));
1086 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1087 let fmt = ListFormatting {
1088 tactic: if all_simple {
1089 DefinitiveListTactic::Mixed
1091 DefinitiveListTactic::Vertical
1094 trailing_separator: SeparatorTactic::Never,
1097 ends_with_newline: false,
1098 config: context.config,
1100 let pats_str = try_opt!(write_list(items, &fmt));
1102 let budget = if pats_str.contains('\n') {
1103 context.config.max_width - offset.width()
1108 let guard_str = try_opt!(rewrite_guard(context,
1112 trimmed_last_line_width(&pats_str)));
1114 let pats_str = format!("{}{}", pats_str, guard_str);
1115 // Where the next text can start.
1116 let mut line_start = last_line_width(&pats_str);
1117 if !pats_str.contains('\n') {
1118 line_start += offset.width();
1121 let body = match **body {
1122 ast::Expr { node: ast::ExprKind::Block(ref block), .. }
1123 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) &&
1124 context.config.wrap_match_arms => block.expr.as_ref().map(|e| &**e).unwrap(),
1128 let comma = arm_comma(&context.config, self, body);
1129 let alt_block_sep = String::from("\n") + &context.block_indent.to_string(context.config);
1131 // Let's try and get the arm body on the same line as the condition.
1133 if context.config.max_width > line_start + comma.len() + 4 {
1134 let budget = context.config.max_width - line_start - comma.len() - 4;
1135 let offset = Indent::new(offset.block_indent, line_start + 4 - offset.block_indent);
1136 let rewrite = nop_block_collapse(body.rewrite(context, budget, offset), budget);
1137 let is_block = if let ast::ExprKind::Block(..) = body.node {
1143 let block_sep = match context.config.control_brace_style {
1144 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep.as_str(),
1148 Some(ref body_str) if !body_str.contains('\n') || !context.config.wrap_match_arms ||
1150 return Some(format!("{}{} =>{}{}{}",
1151 attr_str.trim_left(),
1161 // FIXME: we're doing a second rewrite of the expr; This may not be
1163 let body_budget = try_opt!(width.checked_sub(context.config.tab_spaces));
1164 let indent = context.block_indent.block_indent(context.config);
1165 let inner_context = &RewriteContext { block_indent: indent, ..*context };
1166 let next_line_body =
1167 try_opt!(nop_block_collapse(body.rewrite(inner_context, body_budget, indent),
1169 let indent_str = offset.block_indent(context.config).to_string(context.config);
1170 let (body_prefix, body_suffix) = if context.config.wrap_match_arms {
1171 if context.config.match_block_trailing_comma {
1180 let block_sep = match context.config.control_brace_style {
1181 ControlBraceStyle::AlwaysNextLine => alt_block_sep,
1182 ControlBraceStyle::AlwaysSameLine => String::from(body_prefix) + "\n",
1184 Some(format!("{}{} =>{}{}{}\n{}{}",
1185 attr_str.trim_left(),
1190 offset.to_string(context.config),
1195 // A pattern is simple if it is very short or it is short-ish and just a path.
1196 // E.g. `Foo::Bar` is simple, but `Foo(..)` is not.
1197 fn pat_is_simple(pat_str: &str) -> bool {
1198 pat_str.len() <= 16 ||
1199 (pat_str.len() <= 24 && pat_str.chars().all(|c| c.is_alphabetic() || c == ':'))
1202 // The `if ...` guard on a match arm.
1203 fn rewrite_guard(context: &RewriteContext,
1204 guard: &Option<ptr::P<ast::Expr>>,
1207 // The amount of space used up on this line for the pattern in
1208 // the arm (excludes offset).
1209 pattern_width: usize)
1211 if let Some(ref guard) = *guard {
1212 // First try to fit the guard string on the same line as the pattern.
1213 // 4 = ` if `, 5 = ` => {`
1214 let overhead = pattern_width + 4 + 5;
1215 if overhead < width {
1216 let cond_str = guard.rewrite(context, width - overhead, offset + pattern_width + 4);
1217 if let Some(cond_str) = cond_str {
1218 return Some(format!(" if {}", cond_str));
1222 // Not enough space to put the guard after the pattern, try a newline.
1223 let overhead = offset.block_indent(context.config).width() + 4 + 5;
1224 if overhead < width {
1225 let cond_str = guard.rewrite(context,
1228 offset.block_indent(context.config) + 3);
1229 if let Some(cond_str) = cond_str {
1230 return Some(format!("\n{}if {}",
1231 offset.block_indent(context.config).to_string(context.config),
1242 fn rewrite_pat_expr(context: &RewriteContext,
1243 pat: Option<&ast::Pat>,
1246 // Connecting piece between pattern and expression,
1247 // *without* trailing space.
1252 let pat_offset = offset + matcher.len();
1253 let mut result = match pat {
1255 let pat_budget = try_opt!(width.checked_sub(connector.len() + matcher.len()));
1256 let pat_string = try_opt!(pat.rewrite(context, pat_budget, pat_offset));
1257 format!("{}{}{}", matcher, pat_string, connector)
1259 None => String::new(),
1262 // Consider only the last line of the pat string.
1263 let extra_offset = extra_offset(&result, offset);
1265 // The expression may (partionally) fit on the current line.
1266 if width > extra_offset + 1 {
1267 let spacer = if pat.is_some() { " " } else { "" };
1269 let expr_rewrite = expr.rewrite(context,
1270 width - extra_offset - spacer.len(),
1271 offset + extra_offset + spacer.len());
1273 if let Some(expr_string) = expr_rewrite {
1274 result.push_str(spacer);
1275 result.push_str(&expr_string);
1276 return Some(result);
1280 // The expression won't fit on the current line, jump to next.
1282 result.push_str(&pat_offset.to_string(context.config));
1284 let expr_rewrite = expr.rewrite(context,
1285 context.config.max_width - pat_offset.width(),
1287 result.push_str(&&try_opt!(expr_rewrite));
1292 fn rewrite_string_lit(context: &RewriteContext,
1297 let string_lit = context.snippet(span);
1299 if !context.config.format_strings && !context.config.force_format_strings {
1300 return Some(string_lit);
1303 if !context.config.force_format_strings &&
1304 !string_requires_rewrite(context, span, &string_lit, width, offset) {
1305 return Some(string_lit);
1308 let fmt = StringFormat {
1316 config: context.config,
1319 // Remove the quote characters.
1320 let str_lit = &string_lit[1..string_lit.len() - 1];
1322 rewrite_string(str_lit, &fmt)
1325 fn string_requires_rewrite(context: &RewriteContext,
1331 if context.codemap.lookup_char_pos(span.lo).col.0 != offset.width() {
1335 for (i, line) in string.lines().enumerate() {
1337 if line.len() > width {
1341 if line.len() > width + offset.width() {
1350 pub fn rewrite_call<R>(context: &RewriteContext,
1352 args: &[ptr::P<ast::Expr>],
1359 let closure = |callee_max_width| {
1360 rewrite_call_inner(context, callee, callee_max_width, args, span, width, offset)
1364 let max_width = try_opt!(width.checked_sub(2));
1365 binary_search(1, max_width, closure)
1368 fn rewrite_call_inner<R>(context: &RewriteContext,
1370 max_callee_width: usize,
1371 args: &[ptr::P<ast::Expr>],
1375 -> Result<String, Ordering>
1378 let callee = callee.borrow();
1379 // FIXME using byte lens instead of char lens (and probably all over the
1381 let callee_str = match callee.rewrite(context, max_callee_width, offset) {
1383 if !string.contains('\n') && string.len() > max_callee_width {
1384 panic!("{:?} {}", string, max_callee_width);
1389 None => return Err(Ordering::Greater),
1392 let span_lo = context.codemap.span_after(span, "(");
1393 let span = mk_sp(span_lo, span.hi);
1395 let extra_offset = extra_offset(&callee_str, offset);
1397 let remaining_width = match width.checked_sub(extra_offset + 2) {
1399 None => return Err(Ordering::Greater),
1401 let offset = offset + extra_offset + 1;
1402 let arg_count = args.len();
1403 let block_indent = if arg_count == 1 {
1404 context.block_indent
1408 let inner_context = &RewriteContext { block_indent: block_indent, ..*context };
1410 let items = itemize_list(context.codemap,
1413 |item| item.span.lo,
1414 |item| item.span.hi,
1415 |item| item.rewrite(&inner_context, remaining_width, offset),
1418 let mut item_vec: Vec<_> = items.collect();
1420 // Try letting the last argument overflow to the next line with block
1421 // indentation. If its first line fits on one line with the other arguments,
1422 // we format the function arguments horizontally.
1423 let overflow_last = match args.last().map(|x| &x.node) {
1424 Some(&ast::ExprKind::Closure(..)) |
1425 Some(&ast::ExprKind::Block(..)) if arg_count > 1 => true,
1427 } && context.config.chains_overflow_last;
1429 let mut orig_last = None;
1430 let mut placeholder = None;
1432 // Replace the last item with its first line to see if it fits with
1435 let inner_context = &RewriteContext { block_indent: context.block_indent, ..*context };
1436 let rewrite = args.last().unwrap().rewrite(&inner_context, remaining_width, offset);
1438 if let Some(rewrite) = rewrite {
1439 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
1440 placeholder = Some(rewrite);
1442 swap(&mut item_vec[arg_count - 1].item, &mut orig_last);
1443 item_vec[arg_count - 1].item = rewrite_first_line;
1447 let tactic = definitive_tactic(&item_vec,
1448 ListTactic::LimitedHorizontalVertical(context.config
1452 // Replace the stub with the full overflowing last argument if the rewrite
1453 // succeeded and its first line fits with the other arguments.
1454 match (overflow_last, tactic, placeholder) {
1455 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
1456 item_vec[arg_count - 1].item = placeholder;
1459 item_vec[arg_count - 1].item = orig_last;
1464 let fmt = ListFormatting {
1467 trailing_separator: SeparatorTactic::Never,
1470 ends_with_newline: false,
1471 config: context.config,
1474 let list_str = match write_list(&item_vec, &fmt) {
1476 None => return Err(Ordering::Less),
1479 Ok(format!("{}({})", callee_str, list_str))
1482 fn rewrite_paren(context: &RewriteContext,
1483 subexpr: &ast::Expr,
1487 debug!("rewrite_paren, width: {}, offset: {:?}", width, offset);
1488 // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
1489 // paren on the same line as the subexpr.
1490 let subexpr_str = subexpr.rewrite(context, try_opt!(width.checked_sub(2)), offset + 1);
1491 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1492 subexpr_str.map(|s| format!("({})", s))
1495 fn rewrite_struct_lit<'a>(context: &RewriteContext,
1497 fields: &'a [ast::Field],
1498 base: Option<&'a ast::Expr>,
1503 debug!("rewrite_struct_lit: width {}, offset {:?}", width, offset);
1505 enum StructLitField<'a> {
1506 Regular(&'a ast::Field),
1507 Base(&'a ast::Expr),
1511 let path_budget = try_opt!(width.checked_sub(2));
1512 let path_str = try_opt!(rewrite_path(context, true, None, path, path_budget, offset));
1514 // Foo { a: Foo } - indent is +3, width is -5.
1515 let h_budget = width.checked_sub(path_str.len() + 5).unwrap_or(0);
1516 // The 1 taken from the v_budget is for the comma.
1517 let (indent, v_budget) = match context.config.struct_lit_style {
1518 StructLitStyle::Visual => (offset + path_str.len() + 3, h_budget),
1519 StructLitStyle::Block => {
1520 // If we are all on one line, then we'll ignore the indent, and we
1521 // have a smaller budget.
1522 let indent = context.block_indent.block_indent(context.config);
1523 let v_budget = context.config.max_width.checked_sub(indent.width()).unwrap_or(0);
1528 let field_iter = fields.into_iter()
1529 .map(StructLitField::Regular)
1530 .chain(base.into_iter().map(StructLitField::Base));
1532 let inner_context = &RewriteContext { block_indent: indent, ..*context };
1534 let items = itemize_list(context.codemap,
1539 StructLitField::Regular(ref field) => field.span.lo,
1540 StructLitField::Base(ref expr) => {
1541 let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
1542 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
1543 let pos = snippet.find_uncommented("..").unwrap();
1544 last_field_hi + BytePos(pos as u32)
1550 StructLitField::Regular(ref field) => field.span.hi,
1551 StructLitField::Base(ref expr) => expr.span.hi,
1556 StructLitField::Regular(ref field) => {
1557 rewrite_field(inner_context,
1559 v_budget.checked_sub(1).unwrap_or(0),
1562 StructLitField::Base(ref expr) => {
1564 expr.rewrite(inner_context, try_opt!(v_budget.checked_sub(2)), indent + 2)
1565 .map(|s| format!("..{}", s))
1569 context.codemap.span_after(span, "{"),
1571 let item_vec = items.collect::<Vec<_>>();
1574 let mut prelim_tactic = match (context.config.struct_lit_style, fields.len()) {
1575 (StructLitStyle::Visual, 1) => ListTactic::HorizontalVertical,
1576 _ => context.config.struct_lit_multiline_style.to_list_tactic(),
1579 if prelim_tactic == ListTactic::HorizontalVertical && fields.len() > 1 {
1580 prelim_tactic = ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width);
1583 definitive_tactic(&item_vec, prelim_tactic, h_budget)
1586 let budget = match tactic {
1587 DefinitiveListTactic::Horizontal => h_budget,
1591 let ends_with_newline = context.config.struct_lit_style != StructLitStyle::Visual &&
1592 tactic == DefinitiveListTactic::Vertical;
1594 let fmt = ListFormatting {
1597 trailing_separator: if base.is_some() {
1598 SeparatorTactic::Never
1600 context.config.struct_lit_trailing_comma
1604 ends_with_newline: ends_with_newline,
1605 config: context.config,
1607 let fields_str = try_opt!(write_list(&item_vec, &fmt));
1609 if fields_str.is_empty() {
1610 return Some(format!("{} {{}}", path_str));
1613 let format_on_newline = || {
1614 let inner_indent = context.block_indent
1615 .block_indent(context.config)
1616 .to_string(context.config);
1617 let outer_indent = context.block_indent.to_string(context.config);
1618 Some(format!("{} {{\n{}{}\n{}}}",
1625 match (context.config.struct_lit_style, context.config.struct_lit_multiline_style) {
1626 (StructLitStyle::Block, _) if fields_str.contains('\n') || fields_str.len() > h_budget => {
1629 (StructLitStyle::Block, MultilineStyle::ForceMulti) => format_on_newline(),
1630 _ => Some(format!("{} {{ {} }}", path_str, fields_str)),
1633 // FIXME if context.config.struct_lit_style == Visual, but we run out
1634 // of space, we should fall back to BlockIndent.
1637 fn rewrite_field(context: &RewriteContext,
1642 let name = &field.ident.node.to_string();
1643 let overhead = name.len() + 2;
1644 let expr = field.expr.rewrite(context,
1645 try_opt!(width.checked_sub(overhead)),
1649 Some(e) => Some(format!("{}: {}", name, e)),
1651 let expr_offset = offset.block_indent(&context.config);
1652 let expr = field.expr.rewrite(context,
1653 try_opt!(context.config
1655 .checked_sub(expr_offset.width())),
1657 expr.map(|s| format!("{}:\n{}{}", name, expr_offset.to_string(&context.config), s))
1662 pub fn rewrite_tuple<'a, I>(context: &RewriteContext,
1668 where I: ExactSizeIterator,
1669 <I as Iterator>::Item: Deref,
1670 <I::Item as Deref>::Target: Rewrite + Spanned + 'a
1672 let indent = offset + 1;
1673 // In case of length 1, need a trailing comma
1674 if items.len() == 1 {
1676 let budget = try_opt!(width.checked_sub(3));
1677 return items.next().unwrap().rewrite(context, budget, indent).map(|s| format!("({},)", s));
1680 let list_lo = context.codemap.span_after(span, "(");
1681 let items = itemize_list(context.codemap,
1684 |item| item.span().lo,
1685 |item| item.span().hi,
1687 let inner_width = try_opt!(context.config
1689 .checked_sub(indent.width() + 1));
1690 item.rewrite(context, inner_width, indent)
1693 span.hi - BytePos(1));
1694 let budget = try_opt!(width.checked_sub(2));
1695 let list_str = try_opt!(format_item_list(items, budget, indent, context.config));
1697 Some(format!("({})", list_str))
1700 fn rewrite_binary_op(context: &RewriteContext,
1707 // FIXME: format comments between operands and operator
1709 let operator_str = context.snippet(op.span);
1711 // Get "full width" rhs and see if it fits on the current line. This
1712 // usually works fairly well since it tends to place operands of
1713 // operations with high precendence close together.
1714 let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
1716 // Second condition is needed in case of line break not caused by a
1717 // shortage of space, but by end-of-line comments, for example.
1718 // Note that this is non-conservative, but its just to see if it's even
1719 // worth trying to put everything on one line.
1720 if rhs_result.len() + 2 + operator_str.len() < width && !rhs_result.contains('\n') {
1721 // 1 = space between lhs expr and operator
1722 if let Some(mut result) = lhs.rewrite(context, width - 1 - operator_str.len(), offset) {
1724 result.push_str(&operator_str);
1727 let remaining_width = width.checked_sub(last_line_width(&result)).unwrap_or(0);
1729 if rhs_result.len() <= remaining_width {
1730 result.push_str(&rhs_result);
1731 return Some(result);
1734 if let Some(rhs_result) = rhs.rewrite(context, remaining_width, offset + result.len()) {
1735 if rhs_result.len() <= remaining_width {
1736 result.push_str(&rhs_result);
1737 return Some(result);
1743 // We have to use multiple lines.
1745 // Re-evaluate the lhs because we have more space now:
1746 let budget = try_opt!(context.config
1748 .checked_sub(offset.width() + 1 + operator_str.len()));
1749 Some(format!("{} {}\n{}{}",
1750 try_opt!(lhs.rewrite(context, budget, offset)),
1752 offset.to_string(context.config),
1756 pub fn rewrite_unary_prefix<R: Rewrite>(context: &RewriteContext,
1762 rewrite.rewrite(context,
1763 try_opt!(width.checked_sub(prefix.len())),
1764 offset + prefix.len())
1765 .map(|r| format!("{}{}", prefix, r))
1768 // FIXME: this is probably not correct for multi-line Rewrites. we should
1769 // subtract suffix.len() from the last line budget, not the first!
1770 pub fn rewrite_unary_suffix<R: Rewrite>(context: &RewriteContext,
1776 rewrite.rewrite(context, try_opt!(width.checked_sub(suffix.len())), offset)
1783 fn rewrite_unary_op(context: &RewriteContext,
1789 // For some reason, an UnOp is not spanned like BinOp!
1790 let operator_str = match *op {
1791 ast::UnOp::Deref => "*",
1792 ast::UnOp::Not => "!",
1793 ast::UnOp::Neg => "-",
1795 rewrite_unary_prefix(context, operator_str, expr, width, offset)
1798 fn rewrite_assignment(context: &RewriteContext,
1801 op: Option<&ast::BinOp>,
1805 let operator_str = match op {
1806 Some(op) => context.snippet(op.span),
1807 None => "=".to_owned(),
1810 // 1 = space between lhs and operator.
1811 let max_width = try_opt!(width.checked_sub(operator_str.len() + 1));
1812 let lhs_str = format!("{} {}",
1813 try_opt!(lhs.rewrite(context, max_width, offset)),
1816 rewrite_assign_rhs(&context, lhs_str, rhs, width, offset)
1819 // The left hand side must contain everything up to, and including, the
1820 // assignment operator.
1821 pub fn rewrite_assign_rhs<S: Into<String>>(context: &RewriteContext,
1827 let mut result = lhs.into();
1828 let last_line_width = last_line_width(&result) -
1829 if result.contains('\n') {
1834 // 1 = space between operator and rhs.
1835 let max_width = try_opt!(width.checked_sub(last_line_width + 1));
1836 let rhs = ex.rewrite(&context, max_width, offset + last_line_width + 1);
1838 fn count_line_breaks(src: &str) -> usize {
1839 src.chars().filter(|&x| x == '\n').count()
1843 Some(ref new_str) if count_line_breaks(new_str) < 2 => {
1845 result.push_str(new_str);
1848 // Expression did not fit on the same line as the identifier or is
1849 // at least three lines big. Try splitting the line and see
1850 // if that works better.
1851 let new_offset = offset.block_indent(context.config);
1852 let max_width = try_opt!((width + offset.width()).checked_sub(new_offset.width()));
1853 let inner_context = context.nested_context();
1854 let new_rhs = ex.rewrite(&inner_context, max_width, new_offset);
1857 match (rhs, new_rhs) {
1858 (Some(ref orig_rhs), Some(ref replacement_rhs))
1859 if count_line_breaks(orig_rhs) >
1860 count_line_breaks(replacement_rhs) + 1 => {
1861 result.push_str(&format!("\n{}", new_offset.to_string(context.config)));
1862 result.push_str(replacement_rhs);
1864 (None, Some(ref final_rhs)) => {
1865 result.push_str(&format!("\n{}", new_offset.to_string(context.config)));
1866 result.push_str(final_rhs);
1868 (None, None) => return None,
1869 (Some(ref orig_rhs), _) => {
1871 result.push_str(orig_rhs);
1880 fn rewrite_expr_addrof(context: &RewriteContext,
1881 mutability: ast::Mutability,
1886 let operator_str = match mutability {
1887 ast::Mutability::Immutable => "&",
1888 ast::Mutability::Mutable => "&mut ",
1890 rewrite_unary_prefix(context, operator_str, expr, width, offset)