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};
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;
36 use syntax::visit::Visitor;
38 impl Rewrite for ast::Expr {
39 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
40 let result = match self.node {
41 ast::ExprKind::Vec(ref expr_vec) => {
42 rewrite_array(expr_vec.iter().map(|e| &**e),
43 mk_sp(context.codemap.span_after(self.span, "["), self.span.hi),
48 ast::ExprKind::Lit(ref l) => {
50 ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
51 rewrite_string_lit(context, l.span, width, offset)
54 wrap_str(context.snippet(self.span),
55 context.config.max_width,
61 ast::ExprKind::Call(ref callee, ref args) => {
62 let inner_span = mk_sp(callee.span.hi, self.span.hi);
63 rewrite_call(context, &**callee, args, inner_span, width, offset)
65 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, width, offset),
66 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
67 rewrite_binary_op(context, op, lhs, rhs, width, offset)
69 ast::ExprKind::Unary(ref op, ref subexpr) => {
70 rewrite_unary_op(context, op, subexpr, width, offset)
72 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
73 rewrite_struct_lit(context,
76 base.as_ref().map(|e| &**e),
81 ast::ExprKind::Tup(ref items) => {
82 rewrite_tuple(context,
83 items.iter().map(|x| &**x),
88 ast::ExprKind::While(ref cond, ref block, label) => {
89 Loop::new_while(None, cond, block, label).rewrite(context, width, offset)
91 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => {
92 Loop::new_while(Some(pat), cond, block, label).rewrite(context, width, offset)
94 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
95 Loop::new_for(pat, cond, block, label).rewrite(context, width, offset)
97 ast::ExprKind::Loop(ref block, label) => {
98 Loop::new_loop(block, label).rewrite(context, width, offset)
100 ast::ExprKind::Block(ref block) => block.rewrite(context, width, offset),
101 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
102 rewrite_if_else(context,
105 else_block.as_ref().map(|e| &**e),
112 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
113 rewrite_if_else(context,
116 else_block.as_ref().map(|e| &**e),
123 ast::ExprKind::Match(ref cond, ref arms) => {
124 rewrite_match(context, cond, arms, width, offset, self.span)
126 ast::ExprKind::Path(ref qself, ref path) => {
127 rewrite_path(context, true, qself.as_ref(), path, width, offset)
129 ast::ExprKind::Assign(ref lhs, ref rhs) => {
130 rewrite_assignment(context, lhs, rhs, None, width, offset)
132 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
133 rewrite_assignment(context, lhs, rhs, Some(op), width, offset)
135 ast::ExprKind::Again(ref opt_ident) => {
136 let id_str = match *opt_ident {
137 Some(ident) => format!(" {}", ident.node),
138 None => String::new(),
140 wrap_str(format!("continue{}", id_str), context.config.max_width, width, offset)
142 ast::ExprKind::Break(ref opt_ident) => {
143 let id_str = match *opt_ident {
144 Some(ident) => format!(" {}", ident.node),
145 None => String::new(),
147 wrap_str(format!("break{}", id_str), context.config.max_width, width, offset)
149 ast::ExprKind::Closure(capture, ref fn_decl, ref body) => {
150 rewrite_closure(capture, fn_decl, body, self.span, context, width, offset)
152 ast::ExprKind::Field(..) |
153 ast::ExprKind::TupField(..) |
154 ast::ExprKind::MethodCall(..) => rewrite_chain(self, context, width, offset),
155 ast::ExprKind::Mac(ref mac) => {
156 // Failure to rewrite a marco should not imply failure to
157 // rewrite the expression.
158 rewrite_macro(mac, None, context, width, offset).or_else(|| {
159 wrap_str(context.snippet(self.span),
160 context.config.max_width,
165 ast::ExprKind::Ret(None) => {
166 wrap_str("return".to_owned(), context.config.max_width, width, offset)
168 ast::ExprKind::Ret(Some(ref expr)) => {
169 rewrite_unary_prefix(context, "return ", &**expr, width, offset)
171 ast::ExprKind::Box(ref expr) => {
172 rewrite_unary_prefix(context, "box ", &**expr, width, offset)
174 ast::ExprKind::AddrOf(mutability, ref expr) => {
175 rewrite_expr_addrof(context, mutability, expr, width, offset)
177 ast::ExprKind::Cast(ref expr, ref ty) => {
178 rewrite_pair(&**expr, &**ty, "", " as ", "", context, width, offset)
180 ast::ExprKind::Index(ref expr, ref index) => {
181 rewrite_pair(&**expr, &**index, "", "[", "]", context, width, offset)
183 ast::ExprKind::Repeat(ref expr, ref repeats) => {
184 rewrite_pair(&**expr, &**repeats, "[", "; ", "]", context, width, offset)
186 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
187 let delim = match limits {
188 ast::RangeLimits::HalfOpen => "..",
189 ast::RangeLimits::Closed => "...",
192 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
193 (Some(ref lhs), Some(ref rhs)) => {
194 rewrite_pair(&**lhs, &**rhs, "", delim, "", context, width, offset)
196 (None, Some(ref rhs)) => {
197 rewrite_unary_prefix(context, delim, &**rhs, width, offset)
199 (Some(ref lhs), None) => {
201 try_opt!(lhs.rewrite(context,
202 try_opt!(width.checked_sub(delim.len())),
206 (None, None) => wrap_str(delim.into(), context.config.max_width, width, offset),
209 // We do not format these expressions yet, but they should still
210 // satisfy our width restrictions.
211 ast::ExprKind::InPlace(..) |
212 ast::ExprKind::InlineAsm(..) |
213 // TODO(#848): Handle type ascription
214 ast::ExprKind::Type(_, _) |
215 // TODO(#867): Handle try shorthand
216 ast::ExprKind::Try(_) => {
217 wrap_str(context.snippet(self.span),
218 context.config.max_width,
223 result.and_then(|res| recover_comment_removed(res, self.span, context, width, offset))
227 pub fn rewrite_pair<LHS, RHS>(lhs: &LHS,
232 context: &RewriteContext,
239 let max_width = try_opt!(width.checked_sub(prefix.len() + infix.len() + suffix.len()));
241 binary_search(1, max_width, |lhs_budget| {
242 let lhs_offset = offset + prefix.len();
243 let lhs_str = match lhs.rewrite(context, lhs_budget, lhs_offset) {
244 Some(result) => result,
245 None => return Err(Ordering::Greater),
248 let last_line_width = last_line_width(&lhs_str);
249 let rhs_budget = match max_width.checked_sub(last_line_width) {
251 None => return Err(Ordering::Less),
253 let rhs_indent = offset + last_line_width + prefix.len() + infix.len();
255 let rhs_str = match rhs.rewrite(context, rhs_budget, rhs_indent) {
256 Some(result) => result,
257 None => return Err(Ordering::Less),
260 Ok(format!("{}{}{}{}{}", prefix, lhs_str, infix, rhs_str, suffix))
264 pub fn rewrite_array<'a, I>(expr_iter: I,
266 context: &RewriteContext,
270 where I: Iterator<Item = &'a ast::Expr>
273 let offset = offset + 1;
274 let inner_context = &RewriteContext { block_indent: offset, ..*context };
275 let max_item_width = try_opt!(width.checked_sub(2));
276 let items = itemize_list(context.codemap,
282 |item| item.rewrite(&inner_context, max_item_width, offset),
285 .collect::<Vec<_>>();
287 let has_long_item = try_opt!(items.iter()
288 .map(|li| li.item.as_ref().map(|s| s.len() > 10))
290 |acc, x| acc.and_then(|y| x.map(|x| x || y))));
292 let tactic = if has_long_item || items.iter().any(ListItem::is_multiline) {
293 definitive_tactic(&items, ListTactic::HorizontalVertical, max_item_width)
295 DefinitiveListTactic::Mixed
298 let fmt = ListFormatting {
301 trailing_separator: SeparatorTactic::Never,
303 width: max_item_width,
304 ends_with_newline: false,
305 config: context.config,
307 let list_str = try_opt!(write_list(&items, &fmt));
309 Some(format!("[{}]", list_str))
312 // This functions is pretty messy because of the rules around closures and blocks:
313 // * the body of a closure is represented by an ast::Block, but that does not
314 // imply there are `{}` (unless the block is empty) (see rust issue #27872),
315 // * if there is a return type, then there must be braces,
316 // * given a closure with braces, whether that is parsed to give an inner block
317 // or not depends on if there is a return type and if there are statements
319 // * if the first expression in the body ends with a block (i.e., is a
320 // statement without needing a semi-colon), then adding or removing braces
321 // can change whether it is treated as an expression or statement.
322 fn rewrite_closure(capture: ast::CaptureBy,
323 fn_decl: &ast::FnDecl,
326 context: &RewriteContext,
330 let mover = if capture == ast::CaptureBy::Value {
335 let offset = offset + mover.len();
337 // 4 = "|| {".len(), which is overconservative when the closure consists of
338 // a single expression.
339 let budget = try_opt!(width.checked_sub(4 + mover.len()));
341 let argument_offset = offset + 1;
342 let ret_str = try_opt!(fn_decl.output.rewrite(context, budget, argument_offset));
343 let force_block = !ret_str.is_empty();
345 // 1 = space between arguments and return type.
346 let horizontal_budget = budget.checked_sub(ret_str.len() + 1).unwrap_or(0);
348 let arg_items = itemize_list(context.codemap,
349 fn_decl.inputs.iter(),
351 |arg| span_lo_for_arg(arg),
352 |arg| span_hi_for_arg(arg),
353 |arg| arg.rewrite(context, budget, argument_offset),
354 context.codemap.span_after(span, "|"),
356 let item_vec = arg_items.collect::<Vec<_>>();
357 let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
358 let budget = match tactic {
359 DefinitiveListTactic::Horizontal => horizontal_budget,
363 let fmt = ListFormatting {
366 trailing_separator: SeparatorTactic::Never,
367 indent: argument_offset,
369 ends_with_newline: false,
370 config: context.config,
372 let list_str = try_opt!(write_list(&item_vec, &fmt));
373 let mut prefix = format!("{}|{}|", mover, list_str);
375 if !ret_str.is_empty() {
376 if prefix.contains('\n') {
378 prefix.push_str(&argument_offset.to_string(context.config));
382 prefix.push_str(&ret_str);
385 if body.expr.is_none() && body.stmts.is_empty() {
386 return Some(format!("{} {{}}", prefix));
389 // 1 = space between `|...|` and body.
390 let extra_offset = extra_offset(&prefix, offset) + 1;
391 let budget = try_opt!(width.checked_sub(extra_offset));
393 // This is where we figure out whether to use braces or not.
394 let mut had_braces = true;
395 let mut inner_block = body;
397 // If there is an inner block and we can ignore it, do so.
398 if body.stmts.is_empty() {
399 if let ast::ExprKind::Block(ref inner) = inner_block.expr.as_ref().unwrap().node {
401 } else if !force_block {
406 let try_single_line = is_simple_block(inner_block, context.codemap) &&
407 inner_block.rules == ast::BlockCheckMode::Default;
409 if try_single_line && !force_block {
410 let must_preserve_braces =
411 !classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(inner_block.expr
414 if !(must_preserve_braces && had_braces) &&
415 (must_preserve_braces || !prefix.contains('\n')) {
416 // If we got here, then we can try to format without braces.
418 let inner_expr = inner_block.expr.as_ref().unwrap();
419 let mut rewrite = inner_expr.rewrite(context, budget, offset + extra_offset);
421 if must_preserve_braces {
422 // If we are here, then failure to rewrite is unacceptable.
423 if rewrite.is_none() {
427 // Checks if rewrite succeeded and fits on a single line.
428 rewrite = and_one_line(rewrite);
431 if let Some(rewrite) = rewrite {
432 return Some(format!("{} {}", prefix, rewrite));
437 // If we fell through the above block, then we need braces, but we might
438 // still prefer a one-liner (we might also have fallen through because of
440 if try_single_line && !prefix.contains('\n') {
441 let inner_expr = inner_block.expr.as_ref().unwrap();
442 // 4 = braces and spaces.
443 let mut rewrite = inner_expr.rewrite(context,
444 try_opt!(budget.checked_sub(4)),
445 offset + extra_offset);
447 // Checks if rewrite succeeded and fits on a single line.
448 rewrite = and_one_line(rewrite);
450 if let Some(rewrite) = rewrite {
451 return Some(format!("{} {{ {} }}", prefix, rewrite));
455 // We couldn't format the closure body as a single line expression; fall
456 // back to block formatting.
457 let body_rewrite = inner_block.rewrite(&context, budget, Indent::empty());
459 Some(format!("{} {}", prefix, try_opt!(body_rewrite)))
462 fn and_one_line(x: Option<String>) -> Option<String> {
463 x.and_then(|x| if x.contains('\n') {
470 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
471 block_str.map(|block_str| {
472 if block_str.starts_with("{") && budget >= 2 &&
473 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2) {
481 impl Rewrite for ast::Block {
482 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
483 let user_str = context.snippet(self.span);
484 if user_str == "{}" && width >= 2 {
485 return Some(user_str);
488 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
489 visitor.block_indent = context.block_indent;
491 let prefix = match self.rules {
492 ast::BlockCheckMode::Unsafe(..) => {
493 let snippet = context.snippet(self.span);
494 let open_pos = try_opt!(snippet.find_uncommented("{"));
495 visitor.last_pos = self.span.lo + BytePos(open_pos as u32);
497 // Extract comment between unsafe and block start.
498 let trimmed = &snippet[6..open_pos].trim();
500 let prefix = if !trimmed.is_empty() {
501 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
502 let budget = try_opt!(width.checked_sub(9));
503 format!("unsafe {} ",
504 try_opt!(rewrite_comment(trimmed,
513 if is_simple_block(self, context.codemap) && prefix.len() < width {
517 .rewrite(context, width - prefix.len(), offset);
518 if let Some(ref expr_str) = body {
519 let result = format!("{}{{ {} }}", prefix, expr_str);
520 if result.len() <= width && !result.contains('\n') {
528 ast::BlockCheckMode::Default => {
529 visitor.last_pos = self.span.lo;
535 visitor.visit_block(self);
537 Some(format!("{}{}", prefix, visitor.buffer))
541 impl Rewrite for ast::Stmt {
542 fn rewrite(&self, context: &RewriteContext, _width: usize, offset: Indent) -> Option<String> {
543 let result = match self.node {
544 ast::StmtKind::Decl(ref decl, _) => {
545 if let ast::DeclKind::Local(ref local) = decl.node {
546 local.rewrite(context, context.config.max_width, offset)
551 ast::StmtKind::Expr(ref ex, _) |
552 ast::StmtKind::Semi(ref ex, _) => {
553 let suffix = if semicolon_for_stmt(self) {
560 context.config.max_width - offset.width() - suffix.len(),
564 ast::StmtKind::Mac(..) => None,
566 result.and_then(|res| recover_comment_removed(res, self.span, context, _width, offset))
570 // Abstraction over for, while and loop expressions
572 cond: Option<&'a ast::Expr>,
573 block: &'a ast::Block,
574 label: Option<ast::Ident>,
575 pat: Option<&'a ast::Pat>,
582 fn new_loop(block: &'a ast::Block, label: Option<ast::Ident>) -> Loop<'a> {
594 fn new_while(pat: Option<&'a ast::Pat>,
596 block: &'a ast::Block,
597 label: Option<ast::Ident>)
613 fn new_for(pat: &'a ast::Pat,
615 block: &'a ast::Block,
616 label: Option<ast::Ident>)
630 impl<'a> Rewrite for Loop<'a> {
631 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
632 let label_string = rewrite_label(self.label);
634 let inner_width = try_opt!(width.checked_sub(self.keyword.len() + 2 + label_string.len()));
635 let inner_offset = offset + self.keyword.len() + label_string.len();
637 let pat_expr_string = match self.cond {
639 try_opt!(rewrite_pat_expr(context,
647 None => String::new(),
650 // FIXME: this drops any comment between "loop" and the block.
652 .rewrite(context, width, offset)
663 fn rewrite_label(label: Option<ast::Ident>) -> String {
665 Some(ident) => format!("{}: ", ident),
666 None => "".to_owned(),
670 fn extract_comment(span: Span,
671 context: &RewriteContext,
675 let comment_str = context.snippet(span);
676 if contains_comment(&comment_str) {
677 let comment = try_opt!(rewrite_comment(comment_str.trim(),
682 Some(format!("\n{indent}{}\n{indent}",
684 indent = offset.to_string(context.config)))
690 // Rewrites if-else blocks. If let Some(_) = pat, the expression is
691 // treated as an if-let-else expression.
692 fn rewrite_if_else(context: &RewriteContext,
694 if_block: &ast::Block,
695 else_block_opt: Option<&ast::Expr>,
697 pat: Option<&ast::Pat>,
700 allow_single_line: bool)
702 // 3 = "if ", 2 = " {"
703 let pat_expr_string = try_opt!(rewrite_pat_expr(context,
708 try_opt!(width.checked_sub(3 + 2)),
711 // Try to format if-else on single line.
712 if allow_single_line && context.config.single_line_if_else {
713 let trial = single_line_if_else(context, &pat_expr_string, if_block, else_block_opt, width);
720 let if_block_string = try_opt!(if_block.rewrite(context, width, offset));
722 let between_if_cond = mk_sp(context.codemap.span_after(span, "if"),
723 pat.map_or(cond.span.lo,
724 |_| context.codemap.span_before(span, "let")));
726 let between_if_cond_comment = extract_comment(between_if_cond, &context, offset, width);
728 let after_cond_comment = extract_comment(mk_sp(cond.span.hi, if_block.span.lo),
733 let mut result = format!("if{}{}{}{}",
734 between_if_cond_comment.as_ref().map_or(" ", |str| &**str),
736 after_cond_comment.as_ref().map_or(" ", |str| &**str),
739 if let Some(else_block) = else_block_opt {
740 let rewrite = match else_block.node {
741 // If the else expression is another if-else expression, prevent it
742 // from being formatted on a single line.
743 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
744 rewrite_if_else(context,
747 next_else_block.as_ref().map(|e| &**e),
748 mk_sp(else_block.span.lo, span.hi),
754 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
755 rewrite_if_else(context,
758 next_else_block.as_ref().map(|e| &**e),
759 mk_sp(else_block.span.lo, span.hi),
765 _ => else_block.rewrite(context, width, offset),
768 let between_if_else_block = mk_sp(if_block.span.hi,
769 context.codemap.span_before(mk_sp(if_block.span.hi,
772 let between_if_else_block_comment = extract_comment(between_if_else_block,
777 let after_else = mk_sp(context.codemap
778 .span_after(mk_sp(if_block.span.hi, else_block.span.lo),
781 let after_else_comment = extract_comment(after_else, &context, offset, width);
783 try_opt!(write!(&mut result,
785 between_if_else_block_comment.as_ref().map_or(" ", |str| &**str),
786 after_else_comment.as_ref().map_or(" ", |str| &**str))
788 result.push_str(&&try_opt!(rewrite));
794 fn single_line_if_else(context: &RewriteContext,
796 if_node: &ast::Block,
797 else_block_opt: Option<&ast::Expr>,
800 let else_block = try_opt!(else_block_opt);
801 let fixed_cost = "if { } else { }".len();
803 if let ast::ExprKind::Block(ref else_node) = else_block.node {
804 if !is_simple_block(if_node, context.codemap) ||
805 !is_simple_block(else_node, context.codemap) || pat_expr_str.contains('\n') {
809 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
810 let if_expr = if_node.expr.as_ref().unwrap();
811 let if_str = try_opt!(if_expr.rewrite(context, new_width, Indent::empty()));
813 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
814 let else_expr = else_node.expr.as_ref().unwrap();
815 let else_str = try_opt!(else_expr.rewrite(context, new_width, Indent::empty()));
817 // FIXME: this check shouldn't be necessary. Rewrites should either fail
818 // or wrap to a newline when the object does not fit the width.
819 let fits_line = fixed_cost + pat_expr_str.len() + if_str.len() + else_str.len() <= width;
821 if fits_line && !if_str.contains('\n') && !else_str.contains('\n') {
822 return Some(format!("if {} {{ {} }} else {{ {} }}",
832 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
833 let snippet = codemap.span_to_snippet(block.span).unwrap();
834 contains_comment(&snippet)
837 // Checks that a block contains no statements, an expression and no comments.
838 // FIXME: incorrectly returns false when comment is contained completely within
840 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
841 block.stmts.is_empty() && block.expr.is_some() && !block_contains_comment(block, codemap)
844 /// Checks whether a block contains at most one statement or expression, and no comments.
845 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
846 (block.stmts.is_empty() || (block.stmts.len() == 1 && block.expr.is_none())) &&
847 !block_contains_comment(block, codemap)
850 /// Checks whether a block contains no statements, expressions, or comments.
851 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
852 block.stmts.is_empty() && block.expr.is_none() && !block_contains_comment(block, codemap)
855 fn is_unsafe_block(block: &ast::Block) -> bool {
856 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
863 // inter-match-arm-comment-rules:
864 // - all comments following a match arm before the start of the next arm
865 // are about the second arm
866 fn rewrite_match_arm_comment(context: &RewriteContext,
870 arm_indent_str: &str)
872 // The leading "," is not part of the arm-comment
873 let missed_str = match missed_str.find_uncommented(",") {
874 Some(n) => &missed_str[n + 1..],
875 None => &missed_str[..],
878 let mut result = String::new();
879 // any text not preceeded by a newline is pushed unmodified to the block
880 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
881 result.push_str(&missed_str[..first_brk]);
882 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
884 let first = missed_str.find(|c: char| !c.is_whitespace()).unwrap_or(missed_str.len());
885 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
886 // Excessive vertical whitespace before comment should be preserved
887 // TODO handle vertical whitespace better
890 let missed_str = missed_str[first..].trim();
891 if !missed_str.is_empty() {
892 let comment = try_opt!(rewrite_comment(&missed_str,
898 result.push_str(arm_indent_str);
899 result.push_str(&comment);
905 fn rewrite_match(context: &RewriteContext,
917 let cond_budget = try_opt!(width.checked_sub(8));
918 let cond_str = try_opt!(cond.rewrite(context, cond_budget, offset + 6));
919 let mut result = format!("match {} {{", cond_str);
921 let nested_context = context.nested_context();
922 let arm_indent = nested_context.block_indent;
923 let arm_indent_str = arm_indent.to_string(context.config);
925 let open_brace_pos = context.codemap
926 .span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])), "{");
928 for (i, arm) in arms.iter().enumerate() {
929 // Make sure we get the stuff between arms.
930 let missed_str = if i == 0 {
931 context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
933 context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
935 let comment = try_opt!(rewrite_match_arm_comment(context,
940 result.push_str(&comment);
942 result.push_str(&arm_indent_str);
944 let arm_str = arm.rewrite(&nested_context,
945 context.config.max_width - arm_indent.width(),
947 if let Some(ref arm_str) = arm_str {
948 result.push_str(arm_str);
950 // We couldn't format the arm, just reproduce the source.
951 let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
952 result.push_str(&snippet);
953 result.push_str(arm_comma(&context.config, &arm, &arm.body));
956 // BytePos(1) = closing match brace.
957 let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
958 let last_comment = context.snippet(last_span);
959 let comment = try_opt!(rewrite_match_arm_comment(context,
964 result.push_str(&comment);
966 result.push_str(&context.block_indent.to_string(context.config));
971 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
972 let &ast::Arm { ref attrs, ref pats, .. } = arm;
973 if !attrs.is_empty() {
974 return attrs[0].span.lo;
980 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
984 fn arm_comma(config: &Config, arm: &ast::Arm, body: &ast::Expr) -> &'static str {
985 if !config.match_wildcard_trailing_comma {
986 if arm.pats.len() == 1 && arm.pats[0].node == ast::PatKind::Wild && arm.guard.is_none() {
991 if config.match_block_trailing_comma {
993 } else if let ast::ExprKind::Block(ref block) = body.node {
994 if let ast::BlockCheckMode::Default = block.rules {
1005 impl Rewrite for ast::Arm {
1006 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1007 let &ast::Arm { ref attrs, ref pats, ref guard, ref body } = self;
1009 // FIXME this is all a bit grotty, would be nice to abstract out the
1010 // treatment of attributes.
1011 let attr_str = if !attrs.is_empty() {
1012 // We only use this visitor for the attributes, should we use it for
1014 let mut attr_visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1015 attr_visitor.block_indent = context.block_indent;
1016 attr_visitor.last_pos = attrs[0].span.lo;
1017 if attr_visitor.visit_attrs(attrs) {
1018 // Attributes included a skip instruction.
1021 attr_visitor.format_missing(pats[0].span.lo);
1022 attr_visitor.buffer.to_string()
1029 let pat_budget = try_opt!(width.checked_sub(5));
1030 let pat_strs = try_opt!(pats.iter()
1031 .map(|p| p.rewrite(context, pat_budget, offset))
1032 .collect::<Option<Vec<_>>>());
1034 let all_simple = pat_strs.iter().all(|p| pat_is_simple(&p));
1035 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1036 let fmt = ListFormatting {
1037 tactic: if all_simple {
1038 DefinitiveListTactic::Mixed
1040 DefinitiveListTactic::Vertical
1043 trailing_separator: SeparatorTactic::Never,
1046 ends_with_newline: false,
1047 config: context.config,
1049 let pats_str = try_opt!(write_list(items, &fmt));
1051 let budget = if pats_str.contains('\n') {
1052 context.config.max_width - offset.width()
1057 let guard_str = try_opt!(rewrite_guard(context,
1061 trimmed_last_line_width(&pats_str)));
1063 let pats_str = format!("{}{}", pats_str, guard_str);
1064 // Where the next text can start.
1065 let mut line_start = last_line_width(&pats_str);
1066 if !pats_str.contains('\n') {
1067 line_start += offset.width();
1070 let body = match **body {
1071 ast::Expr { node: ast::ExprKind::Block(ref block), .. }
1072 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) &&
1073 context.config.wrap_match_arms => block.expr.as_ref().map(|e| &**e).unwrap(),
1077 let comma = arm_comma(&context.config, self, body);
1079 // Let's try and get the arm body on the same line as the condition.
1081 if context.config.max_width > line_start + comma.len() + 4 {
1082 let budget = context.config.max_width - line_start - comma.len() - 4;
1083 let offset = Indent::new(offset.block_indent, line_start + 4 - offset.block_indent);
1084 let rewrite = nop_block_collapse(body.rewrite(context, budget, offset), budget);
1085 let is_block = if let ast::ExprKind::Block(..) = body.node {
1092 Some(ref body_str) if !body_str.contains('\n') || !context.config.wrap_match_arms ||
1094 return Some(format!("{}{} => {}{}",
1095 attr_str.trim_left(),
1104 // FIXME: we're doing a second rewrite of the expr; This may not be
1106 let body_budget = try_opt!(width.checked_sub(context.config.tab_spaces));
1107 let indent = context.block_indent.block_indent(context.config);
1108 let inner_context = &RewriteContext { block_indent: indent, ..*context };
1109 let next_line_body = try_opt!(nop_block_collapse(body.rewrite(inner_context,
1113 let indent_str = offset.block_indent(context.config).to_string(context.config);
1114 let (body_prefix, body_suffix) = if context.config.wrap_match_arms {
1115 if context.config.match_block_trailing_comma {
1124 Some(format!("{}{} =>{}\n{}{}\n{}{}",
1125 attr_str.trim_left(),
1130 offset.to_string(context.config),
1135 // A pattern is simple if it is very short or it is short-ish and just a path.
1136 // E.g. `Foo::Bar` is simple, but `Foo(..)` is not.
1137 fn pat_is_simple(pat_str: &str) -> bool {
1138 pat_str.len() <= 16 ||
1139 (pat_str.len() <= 24 && pat_str.chars().all(|c| c.is_alphabetic() || c == ':'))
1142 // The `if ...` guard on a match arm.
1143 fn rewrite_guard(context: &RewriteContext,
1144 guard: &Option<ptr::P<ast::Expr>>,
1147 // The amount of space used up on this line for the pattern in
1148 // the arm (excludes offset).
1149 pattern_width: usize)
1151 if let Some(ref guard) = *guard {
1152 // First try to fit the guard string on the same line as the pattern.
1153 // 4 = ` if `, 5 = ` => {`
1154 let overhead = pattern_width + 4 + 5;
1155 if overhead < width {
1156 let cond_str = guard.rewrite(context, width - overhead, offset + pattern_width + 4);
1157 if let Some(cond_str) = cond_str {
1158 return Some(format!(" if {}", cond_str));
1162 // Not enough space to put the guard after the pattern, try a newline.
1163 let overhead = offset.block_indent(context.config).width() + 4 + 5;
1164 if overhead < width {
1165 let cond_str = guard.rewrite(context,
1168 offset.block_indent(context.config) + 3);
1169 if let Some(cond_str) = cond_str {
1170 return Some(format!("\n{}if {}",
1171 offset.block_indent(context.config).to_string(context.config),
1182 fn rewrite_pat_expr(context: &RewriteContext,
1183 pat: Option<&ast::Pat>,
1186 // Connecting piece between pattern and expression,
1187 // *without* trailing space.
1192 let pat_offset = offset + matcher.len();
1193 let mut result = match pat {
1195 let pat_budget = try_opt!(width.checked_sub(connector.len() + matcher.len()));
1196 let pat_string = try_opt!(pat.rewrite(context, pat_budget, pat_offset));
1197 format!("{}{}{}", matcher, pat_string, connector)
1199 None => String::new(),
1202 // Consider only the last line of the pat string.
1203 let extra_offset = extra_offset(&result, offset);
1205 // The expression may (partionally) fit on the current line.
1206 if width > extra_offset + 1 {
1207 let spacer = if pat.is_some() {
1213 let expr_rewrite = expr.rewrite(context,
1214 width - extra_offset - spacer.len(),
1215 offset + extra_offset + spacer.len());
1217 if let Some(expr_string) = expr_rewrite {
1218 result.push_str(spacer);
1219 result.push_str(&expr_string);
1220 return Some(result);
1224 // The expression won't fit on the current line, jump to next.
1226 result.push_str(&pat_offset.to_string(context.config));
1228 let expr_rewrite = expr.rewrite(context,
1229 context.config.max_width - pat_offset.width(),
1231 result.push_str(&&try_opt!(expr_rewrite));
1236 fn rewrite_string_lit(context: &RewriteContext,
1241 let string_lit = context.snippet(span);
1243 if !context.config.format_strings && !context.config.force_format_strings {
1244 return Some(string_lit);
1247 if !context.config.force_format_strings &&
1248 !string_requires_rewrite(context, span, &string_lit, width, offset) {
1249 return Some(string_lit);
1252 let fmt = StringFormat {
1260 config: context.config,
1263 // Remove the quote characters.
1264 let str_lit = &string_lit[1..string_lit.len() - 1];
1266 rewrite_string(str_lit, &fmt)
1269 fn string_requires_rewrite(context: &RewriteContext,
1275 if context.codemap.lookup_char_pos(span.lo).col.0 != offset.width() {
1279 for (i, line) in string.lines().enumerate() {
1281 if line.len() > width {
1285 if line.len() > width + offset.width() {
1294 pub fn rewrite_call<R>(context: &RewriteContext,
1296 args: &[ptr::P<ast::Expr>],
1303 let closure = |callee_max_width| {
1304 rewrite_call_inner(context, callee, callee_max_width, args, span, width, offset)
1308 let max_width = try_opt!(width.checked_sub(2));
1309 binary_search(1, max_width, closure)
1312 fn rewrite_call_inner<R>(context: &RewriteContext,
1314 max_callee_width: usize,
1315 args: &[ptr::P<ast::Expr>],
1319 -> Result<String, Ordering>
1322 let callee = callee.borrow();
1323 // FIXME using byte lens instead of char lens (and probably all over the
1325 let callee_str = match callee.rewrite(context, max_callee_width, offset) {
1327 if !string.contains('\n') && string.len() > max_callee_width {
1328 panic!("{:?} {}", string, max_callee_width);
1333 None => return Err(Ordering::Greater),
1336 let span_lo = context.codemap.span_after(span, "(");
1337 let span = mk_sp(span_lo, span.hi);
1339 let extra_offset = extra_offset(&callee_str, offset);
1341 let remaining_width = match width.checked_sub(extra_offset + 2) {
1343 None => return Err(Ordering::Greater),
1345 let offset = offset + extra_offset + 1;
1346 let arg_count = args.len();
1347 let block_indent = if arg_count == 1 {
1348 context.block_indent
1352 let inner_context = &RewriteContext { block_indent: block_indent, ..*context };
1354 let items = itemize_list(context.codemap,
1357 |item| item.span.lo,
1358 |item| item.span.hi,
1359 |item| item.rewrite(&inner_context, remaining_width, offset),
1362 let mut item_vec: Vec<_> = items.collect();
1364 // Try letting the last argument overflow to the next line with block
1365 // indentation. If its first line fits on one line with the other arguments,
1366 // we format the function arguments horizontally.
1367 let overflow_last = match args.last().map(|x| &x.node) {
1368 Some(&ast::ExprKind::Closure(..)) |
1369 Some(&ast::ExprKind::Block(..)) if arg_count > 1 => true,
1371 } && context.config.chains_overflow_last;
1373 let mut orig_last = None;
1374 let mut placeholder = None;
1376 // Replace the last item with its first line to see if it fits with
1379 let inner_context = &RewriteContext { block_indent: context.block_indent, ..*context };
1380 let rewrite = args.last().unwrap().rewrite(&inner_context, remaining_width, offset);
1382 if let Some(rewrite) = rewrite {
1383 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
1384 placeholder = Some(rewrite);
1386 swap(&mut item_vec[arg_count - 1].item, &mut orig_last);
1387 item_vec[arg_count - 1].item = rewrite_first_line;
1391 let tactic = definitive_tactic(&item_vec,
1392 ListTactic::LimitedHorizontalVertical(context.config
1396 // Replace the stub with the full overflowing last argument if the rewrite
1397 // succeeded and its first line fits with the other arguments.
1398 match (overflow_last, tactic, placeholder) {
1399 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
1400 item_vec[arg_count - 1].item = placeholder;
1403 item_vec[arg_count - 1].item = orig_last;
1408 let fmt = ListFormatting {
1411 trailing_separator: SeparatorTactic::Never,
1414 ends_with_newline: false,
1415 config: context.config,
1418 let list_str = match write_list(&item_vec, &fmt) {
1420 None => return Err(Ordering::Less),
1423 Ok(format!("{}({})", callee_str, list_str))
1426 fn rewrite_paren(context: &RewriteContext,
1427 subexpr: &ast::Expr,
1431 debug!("rewrite_paren, width: {}, offset: {:?}", width, offset);
1432 // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
1433 // paren on the same line as the subexpr.
1434 let subexpr_str = subexpr.rewrite(context, try_opt!(width.checked_sub(2)), offset + 1);
1435 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1436 subexpr_str.map(|s| format!("({})", s))
1439 fn rewrite_struct_lit<'a>(context: &RewriteContext,
1441 fields: &'a [ast::Field],
1442 base: Option<&'a ast::Expr>,
1447 debug!("rewrite_struct_lit: width {}, offset {:?}", width, offset);
1449 enum StructLitField<'a> {
1450 Regular(&'a ast::Field),
1451 Base(&'a ast::Expr),
1455 let path_budget = try_opt!(width.checked_sub(2));
1456 let path_str = try_opt!(rewrite_path(context, true, None, path, path_budget, offset));
1458 // Foo { a: Foo } - indent is +3, width is -5.
1459 let h_budget = width.checked_sub(path_str.len() + 5).unwrap_or(0);
1460 // The 1 taken from the v_budget is for the comma.
1461 let (indent, v_budget) = match context.config.struct_lit_style {
1462 StructLitStyle::Visual => (offset + path_str.len() + 3, h_budget),
1463 StructLitStyle::Block => {
1464 // If we are all on one line, then we'll ignore the indent, and we
1465 // have a smaller budget.
1466 let indent = context.block_indent.block_indent(context.config);
1467 let v_budget = context.config.max_width.checked_sub(indent.width()).unwrap_or(0);
1472 let field_iter = fields.into_iter()
1473 .map(StructLitField::Regular)
1474 .chain(base.into_iter().map(StructLitField::Base));
1476 let inner_context = &RewriteContext { block_indent: indent, ..*context };
1478 let items = itemize_list(context.codemap,
1483 StructLitField::Regular(ref field) => field.span.lo,
1484 StructLitField::Base(ref expr) => {
1485 let last_field_hi = fields.last().map_or(span.lo,
1489 let snippet = context.snippet(mk_sp(last_field_hi,
1491 let pos = snippet.find_uncommented("..").unwrap();
1492 last_field_hi + BytePos(pos as u32)
1498 StructLitField::Regular(ref field) => field.span.hi,
1499 StructLitField::Base(ref expr) => expr.span.hi,
1504 StructLitField::Regular(ref field) => {
1505 rewrite_field(inner_context,
1507 v_budget.checked_sub(1).unwrap_or(0),
1510 StructLitField::Base(ref expr) => {
1512 expr.rewrite(inner_context,
1513 try_opt!(v_budget.checked_sub(2)),
1515 .map(|s| format!("..{}", s))
1519 context.codemap.span_after(span, "{"),
1521 let item_vec = items.collect::<Vec<_>>();
1524 let mut prelim_tactic = match (context.config.struct_lit_style, fields.len()) {
1525 (StructLitStyle::Visual, 1) => ListTactic::HorizontalVertical,
1526 _ => context.config.struct_lit_multiline_style.to_list_tactic(),
1529 if prelim_tactic == ListTactic::HorizontalVertical && fields.len() > 1 {
1530 prelim_tactic = ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width);
1533 definitive_tactic(&item_vec, prelim_tactic, h_budget)
1536 let budget = match tactic {
1537 DefinitiveListTactic::Horizontal => h_budget,
1541 let ends_with_newline = context.config.struct_lit_style != StructLitStyle::Visual &&
1542 tactic == DefinitiveListTactic::Vertical;
1544 let fmt = ListFormatting {
1547 trailing_separator: if base.is_some() {
1548 SeparatorTactic::Never
1550 context.config.struct_lit_trailing_comma
1554 ends_with_newline: ends_with_newline,
1555 config: context.config,
1557 let fields_str = try_opt!(write_list(&item_vec, &fmt));
1559 if fields_str.is_empty() {
1560 return Some(format!("{} {{}}", path_str));
1563 let format_on_newline = || {
1564 let inner_indent = context.block_indent
1565 .block_indent(context.config)
1566 .to_string(context.config);
1567 let outer_indent = context.block_indent.to_string(context.config);
1568 Some(format!("{} {{\n{}{}\n{}}}",
1575 match (context.config.struct_lit_style, context.config.struct_lit_multiline_style) {
1576 (StructLitStyle::Block, _) if fields_str.contains('\n') || fields_str.len() > h_budget => {
1579 (StructLitStyle::Block, MultilineStyle::ForceMulti) => format_on_newline(),
1580 _ => Some(format!("{} {{ {} }}", path_str, fields_str)),
1583 // FIXME if context.config.struct_lit_style == Visual, but we run out
1584 // of space, we should fall back to BlockIndent.
1587 fn rewrite_field(context: &RewriteContext,
1592 let name = &field.ident.node.to_string();
1593 let overhead = name.len() + 2;
1594 let expr = field.expr.rewrite(context,
1595 try_opt!(width.checked_sub(overhead)),
1599 Some(e) => Some(format!("{}: {}", name, e)),
1601 let expr_offset = offset.block_indent(&context.config);
1602 let expr = field.expr.rewrite(context,
1603 try_opt!(context.config
1605 .checked_sub(expr_offset.width())),
1607 expr.map(|s| format!("{}:\n{}{}", name, expr_offset.to_string(&context.config), s))
1612 pub fn rewrite_tuple<'a, I>(context: &RewriteContext,
1618 where I: ExactSizeIterator,
1619 <I as Iterator>::Item: Deref,
1620 <I::Item as Deref>::Target: Rewrite + Spanned + 'a
1622 let indent = offset + 1;
1623 // In case of length 1, need a trailing comma
1624 if items.len() == 1 {
1626 let budget = try_opt!(width.checked_sub(3));
1627 return items.next().unwrap().rewrite(context, budget, indent).map(|s| format!("({},)", s));
1630 let list_lo = context.codemap.span_after(span, "(");
1631 let items = itemize_list(context.codemap,
1634 |item| item.span().lo,
1635 |item| item.span().hi,
1637 let inner_width = try_opt!(context.config
1639 .checked_sub(indent.width() +
1641 item.rewrite(context, inner_width, indent)
1644 span.hi - BytePos(1));
1645 let budget = try_opt!(width.checked_sub(2));
1646 let list_str = try_opt!(format_item_list(items, budget, indent, context.config));
1648 Some(format!("({})", list_str))
1651 fn rewrite_binary_op(context: &RewriteContext,
1658 // FIXME: format comments between operands and operator
1660 let operator_str = context.snippet(op.span);
1662 // Get "full width" rhs and see if it fits on the current line. This
1663 // usually works fairly well since it tends to place operands of
1664 // operations with high precendence close together.
1665 let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
1667 // Second condition is needed in case of line break not caused by a
1668 // shortage of space, but by end-of-line comments, for example.
1669 // Note that this is non-conservative, but its just to see if it's even
1670 // worth trying to put everything on one line.
1671 if rhs_result.len() + 2 + operator_str.len() < width && !rhs_result.contains('\n') {
1672 // 1 = space between lhs expr and operator
1673 if let Some(mut result) = lhs.rewrite(context, width - 1 - operator_str.len(), offset) {
1675 result.push_str(&operator_str);
1678 let remaining_width = width.checked_sub(last_line_width(&result)).unwrap_or(0);
1680 if rhs_result.len() <= remaining_width {
1681 result.push_str(&rhs_result);
1682 return Some(result);
1685 if let Some(rhs_result) = rhs.rewrite(context, remaining_width, offset + result.len()) {
1686 if rhs_result.len() <= remaining_width {
1687 result.push_str(&rhs_result);
1688 return Some(result);
1694 // We have to use multiple lines.
1696 // Re-evaluate the lhs because we have more space now:
1697 let budget = try_opt!(context.config
1699 .checked_sub(offset.width() + 1 + operator_str.len()));
1700 Some(format!("{} {}\n{}{}",
1701 try_opt!(lhs.rewrite(context, budget, offset)),
1703 offset.to_string(context.config),
1707 pub fn rewrite_unary_prefix<R: Rewrite>(context: &RewriteContext,
1713 rewrite.rewrite(context,
1714 try_opt!(width.checked_sub(prefix.len())),
1715 offset + prefix.len())
1716 .map(|r| format!("{}{}", prefix, r))
1719 fn rewrite_unary_op(context: &RewriteContext,
1725 // For some reason, an UnOp is not spanned like BinOp!
1726 let operator_str = match *op {
1727 ast::UnOp::Deref => "*",
1728 ast::UnOp::Not => "!",
1729 ast::UnOp::Neg => "-",
1731 rewrite_unary_prefix(context, operator_str, expr, width, offset)
1734 fn rewrite_assignment(context: &RewriteContext,
1737 op: Option<&ast::BinOp>,
1741 let operator_str = match op {
1742 Some(op) => context.snippet(op.span),
1743 None => "=".to_owned(),
1746 // 1 = space between lhs and operator.
1747 let max_width = try_opt!(width.checked_sub(operator_str.len() + 1));
1748 let lhs_str = format!("{} {}",
1749 try_opt!(lhs.rewrite(context, max_width, offset)),
1752 rewrite_assign_rhs(&context, lhs_str, rhs, width, offset)
1755 // The left hand side must contain everything up to, and including, the
1756 // assignment operator.
1757 pub fn rewrite_assign_rhs<S: Into<String>>(context: &RewriteContext,
1763 let mut result = lhs.into();
1764 let last_line_width = last_line_width(&result) -
1765 if result.contains('\n') {
1770 // 1 = space between operator and rhs.
1771 let max_width = try_opt!(width.checked_sub(last_line_width + 1));
1772 let rhs = ex.rewrite(&context, max_width, offset + last_line_width + 1);
1777 result.push_str(&new_str)
1780 // Expression did not fit on the same line as the identifier. Retry
1781 // on the next line.
1782 let new_offset = offset.block_indent(context.config);
1783 result.push_str(&format!("\n{}", new_offset.to_string(context.config)));
1785 // FIXME: we probably should related max_width to width instead of
1786 // config.max_width where is the 1 coming from anyway?
1787 let max_width = try_opt!(context.config.max_width.checked_sub(new_offset.width() + 1));
1788 let inner_context = context.nested_context();
1789 let rhs = ex.rewrite(&inner_context, max_width, new_offset);
1791 result.push_str(&&try_opt!(rhs));
1798 fn rewrite_expr_addrof(context: &RewriteContext,
1799 mutability: ast::Mutability,
1804 let operator_str = match mutability {
1805 ast::Mutability::Immutable => "&",
1806 ast::Mutability::Mutable => "&mut ",
1808 rewrite_unary_prefix(context, operator_str, expr, width, offset)