]> git.lizzy.rs Git - rust.git/blob - src/expr.rs
Remove spaces_within_parens_and_brackets
[rust.git] / src / expr.rs
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.
4 //
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.
10
11 use std::borrow::Cow;
12 use std::cmp::min;
13
14 use config::lists::*;
15 use syntax::codemap::{BytePos, CodeMap, Span};
16 use syntax::parse::token::DelimToken;
17 use syntax::{ast, ptr};
18
19 use chains::rewrite_chain;
20 use closures;
21 use codemap::{LineRangeUtils, SpanUtils};
22 use comment::{
23     combine_strs_with_missing_comments, contains_comment, recover_comment_removed, rewrite_comment,
24     rewrite_missing_comment, CharClasses, FindUncommented,
25 };
26 use config::{Config, ControlBraceStyle, IndentStyle};
27 use lists::{
28     definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
29     struct_lit_tactic, write_list, ListFormatting, ListItem, Separator,
30 };
31 use macros::{rewrite_macro, MacroArg, MacroPosition};
32 use matches::rewrite_match;
33 use overflow;
34 use patterns::{can_be_overflowed_pat, is_short_pattern, TuplePatField};
35 use rewrite::{Rewrite, RewriteContext};
36 use shape::{Indent, Shape};
37 use spanned::Spanned;
38 use string::{rewrite_string, StringFormat};
39 use types::{can_be_overflowed_type, rewrite_path, PathContext};
40 use utils::{
41     colon_spaces, contains_skip, count_newlines, first_line_width, inner_attributes,
42     last_line_extendable, last_line_width, mk_sp, outer_attributes, ptr_vec_to_ref_vec,
43     semicolon_for_stmt, wrap_str,
44 };
45 use vertical::rewrite_with_alignment;
46 use visitor::FmtVisitor;
47
48 impl Rewrite for ast::Expr {
49     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
50         format_expr(self, ExprType::SubExpression, context, shape)
51     }
52 }
53
54 #[derive(Copy, Clone, PartialEq)]
55 pub enum ExprType {
56     Statement,
57     SubExpression,
58 }
59
60 pub fn format_expr(
61     expr: &ast::Expr,
62     expr_type: ExprType,
63     context: &RewriteContext,
64     shape: Shape,
65 ) -> Option<String> {
66     skip_out_of_file_lines_range!(context, expr.span);
67
68     if contains_skip(&*expr.attrs) {
69         return Some(context.snippet(expr.span()).to_owned());
70     }
71
72     let expr_rw = match expr.node {
73         ast::ExprKind::Array(ref expr_vec) => rewrite_array(
74             "",
75             &ptr_vec_to_ref_vec(expr_vec),
76             expr.span,
77             context,
78             shape,
79             choose_separator_tactic(context, expr.span),
80             None,
81         ),
82         ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
83         ast::ExprKind::Call(ref callee, ref args) => {
84             let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
85             let callee_str = callee.rewrite(context, shape)?;
86             rewrite_call(context, &callee_str, args, inner_span, shape)
87         }
88         ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
89         ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
90             // FIXME: format comments between operands and operator
91             rewrite_simple_binaries(context, expr, shape, op).or_else(|| {
92                 rewrite_pair(
93                     &**lhs,
94                     &**rhs,
95                     PairParts::new("", &format!(" {} ", context.snippet(op.span)), ""),
96                     context,
97                     shape,
98                     context.config.binop_separator(),
99                 )
100             })
101         }
102         ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
103         ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
104             context,
105             path,
106             fields,
107             base.as_ref().map(|e| &**e),
108             expr.span,
109             shape,
110         ),
111         ast::ExprKind::Tup(ref items) => {
112             rewrite_tuple(context, &ptr_vec_to_ref_vec(items), expr.span, shape)
113         }
114         ast::ExprKind::If(..)
115         | ast::ExprKind::IfLet(..)
116         | ast::ExprKind::ForLoop(..)
117         | ast::ExprKind::Loop(..)
118         | ast::ExprKind::While(..)
119         | ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
120             .and_then(|control_flow| control_flow.rewrite(context, shape)),
121         ast::ExprKind::Block(ref block) => {
122             match expr_type {
123                 ExprType::Statement => {
124                     if is_unsafe_block(block) {
125                         rewrite_block(block, Some(&expr.attrs), context, shape)
126                     } else if let rw @ Some(_) =
127                         rewrite_empty_block(context, block, Some(&expr.attrs), "", shape)
128                     {
129                         // Rewrite block without trying to put it in a single line.
130                         rw
131                     } else {
132                         let prefix = block_prefix(context, block, shape)?;
133                         rewrite_block_with_visitor(
134                             context,
135                             &prefix,
136                             block,
137                             Some(&expr.attrs),
138                             shape,
139                             true,
140                         )
141                     }
142                 }
143                 ExprType::SubExpression => rewrite_block(block, Some(&expr.attrs), context, shape),
144             }
145         }
146         ast::ExprKind::Match(ref cond, ref arms) => {
147             rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
148         }
149         ast::ExprKind::Path(ref qself, ref path) => {
150             rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
151         }
152         ast::ExprKind::Assign(ref lhs, ref rhs) => {
153             rewrite_assignment(context, lhs, rhs, None, shape)
154         }
155         ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
156             rewrite_assignment(context, lhs, rhs, Some(op), shape)
157         }
158         ast::ExprKind::Continue(ref opt_label) => {
159             let id_str = match *opt_label {
160                 Some(label) => format!(" {}", label.ident),
161                 None => String::new(),
162             };
163             Some(format!("continue{}", id_str))
164         }
165         ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
166             let id_str = match *opt_label {
167                 Some(label) => format!(" {}", label.ident),
168                 None => String::new(),
169             };
170
171             if let Some(ref expr) = *opt_expr {
172                 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
173             } else {
174                 Some(format!("break{}", id_str))
175             }
176         }
177         ast::ExprKind::Yield(ref opt_expr) => if let Some(ref expr) = *opt_expr {
178             rewrite_unary_prefix(context, "yield ", &**expr, shape)
179         } else {
180             Some("yield".to_string())
181         },
182         ast::ExprKind::Closure(capture, movability, ref fn_decl, ref body, _) => {
183             closures::rewrite_closure(
184                 capture, movability, fn_decl, body, expr.span, context, shape,
185             )
186         }
187         ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => {
188             rewrite_chain(expr, context, shape)
189         }
190         ast::ExprKind::Mac(ref mac) => {
191             rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
192                 wrap_str(
193                     context.snippet(expr.span).to_owned(),
194                     context.config.max_width(),
195                     shape,
196                 )
197             })
198         }
199         ast::ExprKind::Ret(None) => Some("return".to_owned()),
200         ast::ExprKind::Ret(Some(ref expr)) => {
201             rewrite_unary_prefix(context, "return ", &**expr, shape)
202         }
203         ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
204         ast::ExprKind::AddrOf(mutability, ref expr) => {
205             rewrite_expr_addrof(context, mutability, expr, shape)
206         }
207         ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
208             &**expr,
209             &**ty,
210             PairParts::new("", " as ", ""),
211             context,
212             shape,
213             SeparatorPlace::Front,
214         ),
215         ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
216             &**expr,
217             &**ty,
218             PairParts::new("", ": ", ""),
219             context,
220             shape,
221             SeparatorPlace::Back,
222         ),
223         ast::ExprKind::Index(ref expr, ref index) => {
224             rewrite_index(&**expr, &**index, context, shape)
225         }
226         ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
227             &**expr,
228             &**repeats,
229             PairParts::new("[", "; ", "]"),
230             context,
231             shape,
232             SeparatorPlace::Back,
233         ),
234         ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
235             let delim = match limits {
236                 ast::RangeLimits::HalfOpen => "..",
237                 ast::RangeLimits::Closed => "..=",
238             };
239
240             fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
241                 match lhs.node {
242                     ast::ExprKind::Lit(ref lit) => match lit.node {
243                         ast::LitKind::FloatUnsuffixed(..) => {
244                             context.snippet(lit.span).ends_with('.')
245                         }
246                         _ => false,
247                     },
248                     _ => false,
249                 }
250             }
251
252             fn needs_space_after_range(rhs: &ast::Expr) -> bool {
253                 match rhs.node {
254                     // Don't format `.. ..` into `....`, which is invalid.
255                     //
256                     // This check is unnecessary for `lhs`, because a range
257                     // starting from another range needs parentheses as `(x ..) ..`
258                     // (`x .. ..` is a range from `x` to `..`).
259                     ast::ExprKind::Range(None, _, _) => true,
260                     _ => false,
261                 }
262             }
263
264             let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
265                 let space_if = |b: bool| if b { " " } else { "" };
266
267                 format!(
268                     "{}{}{}",
269                     lhs.map(|lhs| space_if(needs_space_before_range(context, lhs)))
270                         .unwrap_or(""),
271                     delim,
272                     rhs.map(|rhs| space_if(needs_space_after_range(rhs)))
273                         .unwrap_or(""),
274                 )
275             };
276
277             match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
278                 (Some(lhs), Some(rhs)) => {
279                     let sp_delim = if context.config.spaces_around_ranges() {
280                         format!(" {} ", delim)
281                     } else {
282                         default_sp_delim(Some(lhs), Some(rhs))
283                     };
284                     rewrite_pair(
285                         &*lhs,
286                         &*rhs,
287                         PairParts::new("", &sp_delim, ""),
288                         context,
289                         shape,
290                         context.config.binop_separator(),
291                     )
292                 }
293                 (None, Some(rhs)) => {
294                     let sp_delim = if context.config.spaces_around_ranges() {
295                         format!("{} ", delim)
296                     } else {
297                         default_sp_delim(None, Some(rhs))
298                     };
299                     rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
300                 }
301                 (Some(lhs), None) => {
302                     let sp_delim = if context.config.spaces_around_ranges() {
303                         format!(" {}", delim)
304                     } else {
305                         default_sp_delim(Some(lhs), None)
306                     };
307                     rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
308                 }
309                 (None, None) => Some(delim.to_owned()),
310             }
311         }
312         // We do not format these expressions yet, but they should still
313         // satisfy our width restrictions.
314         ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
315         ast::ExprKind::Catch(ref block) => {
316             if let rw @ Some(_) =
317                 rewrite_single_line_block(context, "do catch ", block, Some(&expr.attrs), shape)
318             {
319                 rw
320             } else {
321                 // 9 = `do catch `
322                 let budget = shape.width.saturating_sub(9);
323                 Some(format!(
324                     "{}{}",
325                     "do catch ",
326                     rewrite_block(
327                         block,
328                         Some(&expr.attrs),
329                         context,
330                         Shape::legacy(budget, shape.indent)
331                     )?
332                 ))
333             }
334         }
335     };
336
337     expr_rw
338         .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
339         .and_then(|expr_str| {
340             let attrs = outer_attributes(&expr.attrs);
341             let attrs_str = attrs.rewrite(context, shape)?;
342             let span = mk_sp(
343                 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
344                 expr.span.lo(),
345             );
346             combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
347         })
348 }
349
350 /// Collect operands that appears in the given binary operator in the opposite order.
351 /// e.g. `collect_binary_items(e, ||)` for `a && b || c || d` returns `[d, c, a && b]`.
352 fn collect_binary_items<'a>(mut expr: &'a ast::Expr, binop: ast::BinOp) -> Vec<&'a ast::Expr> {
353     let mut result = vec![];
354     let mut prev_lhs = None;
355     loop {
356         match expr.node {
357             ast::ExprKind::Binary(inner_binop, ref lhs, ref rhs)
358                 if inner_binop.node == binop.node =>
359             {
360                 result.push(&**rhs);
361                 expr = lhs;
362                 prev_lhs = Some(lhs);
363             }
364             _ => {
365                 if let Some(lhs) = prev_lhs {
366                     result.push(lhs);
367                 }
368                 break;
369             }
370         }
371     }
372     result
373 }
374
375 /// Rewrites a binary expression whose operands fits within a single line.
376 fn rewrite_simple_binaries(
377     context: &RewriteContext,
378     expr: &ast::Expr,
379     shape: Shape,
380     op: ast::BinOp,
381 ) -> Option<String> {
382     let op_str = context.snippet(op.span);
383
384     // 2 = spaces around a binary operator.
385     let sep_overhead = op_str.len() + 2;
386     let nested_overhead = sep_overhead - 1;
387
388     let nested_shape = (match context.config.indent_style() {
389         IndentStyle::Visual => shape.visual_indent(0),
390         IndentStyle::Block => shape.block_indent(context.config.tab_spaces()),
391     }).with_max_width(context.config);
392     let nested_shape = match context.config.binop_separator() {
393         SeparatorPlace::Back => nested_shape.sub_width(nested_overhead)?,
394         SeparatorPlace::Front => nested_shape.offset_left(nested_overhead)?,
395     };
396
397     let opt_rewrites: Option<Vec<_>> = collect_binary_items(expr, op)
398         .iter()
399         .rev()
400         .map(|e| e.rewrite(context, nested_shape))
401         .collect();
402     if let Some(rewrites) = opt_rewrites {
403         if rewrites.iter().all(|e| ::utils::is_single_line(e)) {
404             let total_width = rewrites.iter().map(|s| s.len()).sum::<usize>()
405                 + sep_overhead * (rewrites.len() - 1);
406
407             let sep_str = if total_width <= shape.width {
408                 format!(" {} ", op_str)
409             } else {
410                 let indent_str = nested_shape.indent.to_string_with_newline(context.config);
411                 match context.config.binop_separator() {
412                     SeparatorPlace::Back => format!(" {}{}", op_str.trim_right(), indent_str),
413                     SeparatorPlace::Front => format!("{}{} ", indent_str, op_str.trim_left()),
414                 }
415             };
416
417             return wrap_str(rewrites.join(&sep_str), context.config.max_width(), shape);
418         }
419     }
420
421     None
422 }
423
424 #[derive(new, Clone, Copy)]
425 pub struct PairParts<'a> {
426     prefix: &'a str,
427     infix: &'a str,
428     suffix: &'a str,
429 }
430
431 pub fn rewrite_pair<LHS, RHS>(
432     lhs: &LHS,
433     rhs: &RHS,
434     pp: PairParts,
435     context: &RewriteContext,
436     shape: Shape,
437     separator_place: SeparatorPlace,
438 ) -> Option<String>
439 where
440     LHS: Rewrite,
441     RHS: Rewrite,
442 {
443     let lhs_overhead = match separator_place {
444         SeparatorPlace::Back => shape.used_width() + pp.prefix.len() + pp.infix.trim_right().len(),
445         SeparatorPlace::Front => shape.used_width(),
446     };
447     let lhs_shape = Shape {
448         width: context.budget(lhs_overhead),
449         ..shape
450     };
451     let lhs_result = lhs
452         .rewrite(context, lhs_shape)
453         .map(|lhs_str| format!("{}{}", pp.prefix, lhs_str))?;
454
455     // Try to put both lhs and rhs on the same line.
456     let rhs_orig_result = shape
457         .offset_left(last_line_width(&lhs_result) + pp.infix.len())
458         .and_then(|s| s.sub_width(pp.suffix.len()))
459         .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
460     if let Some(ref rhs_result) = rhs_orig_result {
461         // If the length of the lhs is equal to or shorter than the tab width or
462         // the rhs looks like block expression, we put the rhs on the same
463         // line with the lhs even if the rhs is multi-lined.
464         let allow_same_line = lhs_result.len() <= context.config.tab_spaces()
465             || rhs_result
466                 .lines()
467                 .next()
468                 .map(|first_line| first_line.ends_with('{'))
469                 .unwrap_or(false);
470         if !rhs_result.contains('\n') || allow_same_line {
471             let one_line_width = last_line_width(&lhs_result)
472                 + pp.infix.len()
473                 + first_line_width(rhs_result)
474                 + pp.suffix.len();
475             if one_line_width <= shape.width {
476                 return Some(format!(
477                     "{}{}{}{}",
478                     lhs_result, pp.infix, rhs_result, pp.suffix
479                 ));
480             }
481         }
482     }
483
484     // We have to use multiple lines.
485     // Re-evaluate the rhs because we have more space now:
486     let mut rhs_shape = match context.config.indent_style() {
487         IndentStyle::Visual => shape
488             .sub_width(pp.suffix.len() + pp.prefix.len())?
489             .visual_indent(pp.prefix.len()),
490         IndentStyle::Block => {
491             // Try to calculate the initial constraint on the right hand side.
492             let rhs_overhead = shape.rhs_overhead(context.config);
493             Shape::indented(shape.indent.block_indent(context.config), context.config)
494                 .sub_width(rhs_overhead)?
495         }
496     };
497     let infix = match separator_place {
498         SeparatorPlace::Back => pp.infix.trim_right(),
499         SeparatorPlace::Front => pp.infix.trim_left(),
500     };
501     if separator_place == SeparatorPlace::Front {
502         rhs_shape = rhs_shape.offset_left(infix.len())?;
503     }
504     let rhs_result = rhs.rewrite(context, rhs_shape)?;
505     let indent_str = rhs_shape.indent.to_string_with_newline(context.config);
506     let infix_with_sep = match separator_place {
507         SeparatorPlace::Back => format!("{}{}", infix, indent_str),
508         SeparatorPlace::Front => format!("{}{}", indent_str, infix),
509     };
510     Some(format!(
511         "{}{}{}{}",
512         lhs_result, infix_with_sep, rhs_result, pp.suffix
513     ))
514 }
515
516 pub fn rewrite_array<T: Rewrite + Spanned + ToExpr>(
517     name: &str,
518     exprs: &[&T],
519     span: Span,
520     context: &RewriteContext,
521     shape: Shape,
522     force_separator_tactic: Option<SeparatorTactic>,
523     delim_token: Option<DelimToken>,
524 ) -> Option<String> {
525     overflow::rewrite_with_square_brackets(
526         context,
527         name,
528         exprs,
529         shape,
530         span,
531         force_separator_tactic,
532         delim_token,
533     )
534 }
535
536 fn rewrite_empty_block(
537     context: &RewriteContext,
538     block: &ast::Block,
539     attrs: Option<&[ast::Attribute]>,
540     prefix: &str,
541     shape: Shape,
542 ) -> Option<String> {
543     if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
544         return None;
545     }
546
547     if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
548     {
549         return Some(format!("{}{{}}", prefix));
550     }
551
552     // If a block contains only a single-line comment, then leave it on one line.
553     let user_str = context.snippet(block.span);
554     let user_str = user_str.trim();
555     if user_str.starts_with('{') && user_str.ends_with('}') {
556         let comment_str = user_str[1..user_str.len() - 1].trim();
557         if block.stmts.is_empty()
558             && !comment_str.contains('\n')
559             && !comment_str.starts_with("//")
560             && comment_str.len() + 4 <= shape.width
561         {
562             return Some(format!("{}{{ {} }}", prefix, comment_str));
563         }
564     }
565
566     None
567 }
568
569 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
570     Some(match block.rules {
571         ast::BlockCheckMode::Unsafe(..) => {
572             let snippet = context.snippet(block.span);
573             let open_pos = snippet.find_uncommented("{")?;
574             // Extract comment between unsafe and block start.
575             let trimmed = &snippet[6..open_pos].trim();
576
577             if !trimmed.is_empty() {
578                 // 9 = "unsafe  {".len(), 7 = "unsafe ".len()
579                 let budget = shape.width.checked_sub(9)?;
580                 format!(
581                     "unsafe {} ",
582                     rewrite_comment(
583                         trimmed,
584                         true,
585                         Shape::legacy(budget, shape.indent + 7),
586                         context.config,
587                     )?
588                 )
589             } else {
590                 "unsafe ".to_owned()
591             }
592         }
593         ast::BlockCheckMode::Default => String::new(),
594     })
595 }
596
597 fn rewrite_single_line_block(
598     context: &RewriteContext,
599     prefix: &str,
600     block: &ast::Block,
601     attrs: Option<&[ast::Attribute]>,
602     shape: Shape,
603 ) -> Option<String> {
604     if is_simple_block(block, attrs, context.codemap) {
605         let expr_shape = shape.offset_left(last_line_width(prefix))?;
606         let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
607         let result = format!("{}{{ {} }}", prefix, expr_str);
608         if result.len() <= shape.width && !result.contains('\n') {
609             return Some(result);
610         }
611     }
612     None
613 }
614
615 pub fn rewrite_block_with_visitor(
616     context: &RewriteContext,
617     prefix: &str,
618     block: &ast::Block,
619     attrs: Option<&[ast::Attribute]>,
620     shape: Shape,
621     has_braces: bool,
622 ) -> Option<String> {
623     if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, prefix, shape) {
624         return rw;
625     }
626
627     let mut visitor = FmtVisitor::from_context(context);
628     visitor.block_indent = shape.indent;
629     visitor.is_if_else_block = context.is_if_else_block();
630     match block.rules {
631         ast::BlockCheckMode::Unsafe(..) => {
632             let snippet = context.snippet(block.span);
633             let open_pos = snippet.find_uncommented("{")?;
634             visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
635         }
636         ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo(),
637     }
638
639     let inner_attrs = attrs.map(inner_attributes);
640     visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
641     Some(format!("{}{}", prefix, visitor.buffer))
642 }
643
644 impl Rewrite for ast::Block {
645     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
646         rewrite_block(self, None, context, shape)
647     }
648 }
649
650 fn rewrite_block(
651     block: &ast::Block,
652     attrs: Option<&[ast::Attribute]>,
653     context: &RewriteContext,
654     shape: Shape,
655 ) -> Option<String> {
656     let prefix = block_prefix(context, block, shape)?;
657
658     // shape.width is used only for the single line case: either the empty block `{}`,
659     // or an unsafe expression `unsafe { e }`.
660     if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, &prefix, shape) {
661         return rw;
662     }
663
664     let result = rewrite_block_with_visitor(context, &prefix, block, attrs, shape, true);
665     if let Some(ref result_str) = result {
666         if result_str.lines().count() <= 3 {
667             if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, block, attrs, shape) {
668                 return rw;
669             }
670         }
671     }
672
673     result
674 }
675
676 impl Rewrite for ast::Stmt {
677     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
678         skip_out_of_file_lines_range!(context, self.span());
679
680         let result = match self.node {
681             ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
682             ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
683                 let suffix = if semicolon_for_stmt(context, self) {
684                     ";"
685                 } else {
686                     ""
687                 };
688
689                 let shape = shape.sub_width(suffix.len())?;
690                 format_expr(ex, ExprType::Statement, context, shape).map(|s| s + suffix)
691             }
692             ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
693         };
694         result.and_then(|res| recover_comment_removed(res, self.span(), context))
695     }
696 }
697
698 // Rewrite condition if the given expression has one.
699 pub fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
700     match expr.node {
701         ast::ExprKind::Match(ref cond, _) => {
702             // `match `cond` {`
703             let cond_shape = match context.config.indent_style() {
704                 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
705                 IndentStyle::Block => shape.offset_left(8)?,
706             };
707             cond.rewrite(context, cond_shape)
708         }
709         _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
710             let alt_block_sep =
711                 String::from("\n") + &shape.indent.block_only().to_string(context.config);
712             control_flow
713                 .rewrite_cond(context, shape, &alt_block_sep)
714                 .and_then(|rw| Some(rw.0))
715         }),
716     }
717 }
718
719 // Abstraction over control flow expressions
720 #[derive(Debug)]
721 struct ControlFlow<'a> {
722     cond: Option<&'a ast::Expr>,
723     block: &'a ast::Block,
724     else_block: Option<&'a ast::Expr>,
725     label: Option<ast::Label>,
726     pats: Vec<&'a ast::Pat>,
727     keyword: &'a str,
728     matcher: &'a str,
729     connector: &'a str,
730     allow_single_line: bool,
731     // True if this is an `if` expression in an `else if` :-( hacky
732     nested_if: bool,
733     span: Span,
734 }
735
736 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow> {
737     match expr.node {
738         ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
739             cond,
740             vec![],
741             if_block,
742             else_block.as_ref().map(|e| &**e),
743             expr_type == ExprType::SubExpression,
744             false,
745             expr.span,
746         )),
747         ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
748             Some(ControlFlow::new_if(
749                 cond,
750                 ptr_vec_to_ref_vec(pat),
751                 if_block,
752                 else_block.as_ref().map(|e| &**e),
753                 expr_type == ExprType::SubExpression,
754                 false,
755                 expr.span,
756             ))
757         }
758         ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
759             Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
760         }
761         ast::ExprKind::Loop(ref block, label) => {
762             Some(ControlFlow::new_loop(block, label, expr.span))
763         }
764         ast::ExprKind::While(ref cond, ref block, label) => Some(ControlFlow::new_while(
765             vec![],
766             cond,
767             block,
768             label,
769             expr.span,
770         )),
771         ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
772             ControlFlow::new_while(ptr_vec_to_ref_vec(pat), cond, block, label, expr.span),
773         ),
774         _ => None,
775     }
776 }
777
778 fn choose_matcher(pats: &[&ast::Pat]) -> &'static str {
779     if pats.is_empty() {
780         ""
781     } else {
782         "let"
783     }
784 }
785
786 impl<'a> ControlFlow<'a> {
787     fn new_if(
788         cond: &'a ast::Expr,
789         pats: Vec<&'a ast::Pat>,
790         block: &'a ast::Block,
791         else_block: Option<&'a ast::Expr>,
792         allow_single_line: bool,
793         nested_if: bool,
794         span: Span,
795     ) -> ControlFlow<'a> {
796         let matcher = choose_matcher(&pats);
797         ControlFlow {
798             cond: Some(cond),
799             block,
800             else_block,
801             label: None,
802             pats,
803             keyword: "if",
804             matcher,
805             connector: " =",
806             allow_single_line,
807             nested_if,
808             span,
809         }
810     }
811
812     fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
813         ControlFlow {
814             cond: None,
815             block,
816             else_block: None,
817             label,
818             pats: vec![],
819             keyword: "loop",
820             matcher: "",
821             connector: "",
822             allow_single_line: false,
823             nested_if: false,
824             span,
825         }
826     }
827
828     fn new_while(
829         pats: Vec<&'a ast::Pat>,
830         cond: &'a ast::Expr,
831         block: &'a ast::Block,
832         label: Option<ast::Label>,
833         span: Span,
834     ) -> ControlFlow<'a> {
835         let matcher = choose_matcher(&pats);
836         ControlFlow {
837             cond: Some(cond),
838             block,
839             else_block: None,
840             label,
841             pats,
842             keyword: "while",
843             matcher,
844             connector: " =",
845             allow_single_line: false,
846             nested_if: false,
847             span,
848         }
849     }
850
851     fn new_for(
852         pat: &'a ast::Pat,
853         cond: &'a ast::Expr,
854         block: &'a ast::Block,
855         label: Option<ast::Label>,
856         span: Span,
857     ) -> ControlFlow<'a> {
858         ControlFlow {
859             cond: Some(cond),
860             block,
861             else_block: None,
862             label,
863             pats: vec![pat],
864             keyword: "for",
865             matcher: "",
866             connector: " in",
867             allow_single_line: false,
868             nested_if: false,
869             span,
870         }
871     }
872
873     fn rewrite_single_line(
874         &self,
875         pat_expr_str: &str,
876         context: &RewriteContext,
877         width: usize,
878     ) -> Option<String> {
879         assert!(self.allow_single_line);
880         let else_block = self.else_block?;
881         let fixed_cost = self.keyword.len() + "  {  } else {  }".len();
882
883         if let ast::ExprKind::Block(ref else_node) = else_block.node {
884             if !is_simple_block(self.block, None, context.codemap)
885                 || !is_simple_block(else_node, None, context.codemap)
886                 || pat_expr_str.contains('\n')
887             {
888                 return None;
889             }
890
891             let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
892             let expr = &self.block.stmts[0];
893             let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
894
895             let new_width = new_width.checked_sub(if_str.len())?;
896             let else_expr = &else_node.stmts[0];
897             let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
898
899             if if_str.contains('\n') || else_str.contains('\n') {
900                 return None;
901             }
902
903             let result = format!(
904                 "{} {} {{ {} }} else {{ {} }}",
905                 self.keyword, pat_expr_str, if_str, else_str
906             );
907
908             if result.len() <= width {
909                 return Some(result);
910             }
911         }
912
913         None
914     }
915 }
916
917 impl<'a> ControlFlow<'a> {
918     fn rewrite_pat_expr(
919         &self,
920         context: &RewriteContext,
921         expr: &ast::Expr,
922         shape: Shape,
923         offset: usize,
924     ) -> Option<String> {
925         debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pats, expr);
926
927         let cond_shape = shape.offset_left(offset)?;
928         if !self.pats.is_empty() {
929             let matcher = if self.matcher.is_empty() {
930                 self.matcher.to_owned()
931             } else {
932                 format!("{} ", self.matcher)
933             };
934             let pat_shape = cond_shape
935                 .offset_left(matcher.len())?
936                 .sub_width(self.connector.len())?;
937             let pat_string = rewrite_multiple_patterns(context, &self.pats, pat_shape)?;
938             let result = format!("{}{}{}", matcher, pat_string, self.connector);
939             return rewrite_assign_rhs(context, result, expr, cond_shape);
940         }
941
942         let expr_rw = expr.rewrite(context, cond_shape);
943         // The expression may (partially) fit on the current line.
944         // We do not allow splitting between `if` and condition.
945         if self.keyword == "if" || expr_rw.is_some() {
946             return expr_rw;
947         }
948
949         // The expression won't fit on the current line, jump to next.
950         let nested_shape = shape
951             .block_indent(context.config.tab_spaces())
952             .with_max_width(context.config);
953         let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
954         expr.rewrite(context, nested_shape)
955             .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
956     }
957
958     fn rewrite_cond(
959         &self,
960         context: &RewriteContext,
961         shape: Shape,
962         alt_block_sep: &str,
963     ) -> Option<(String, usize)> {
964         // Do not take the rhs overhead from the upper expressions into account
965         // when rewriting pattern.
966         let new_width = context.budget(shape.used_width());
967         let fresh_shape = Shape {
968             width: new_width,
969             ..shape
970         };
971         let constr_shape = if self.nested_if {
972             // We are part of an if-elseif-else chain. Our constraints are tightened.
973             // 7 = "} else " .len()
974             fresh_shape.offset_left(7)?
975         } else {
976             fresh_shape
977         };
978
979         let label_string = rewrite_label(self.label);
980         // 1 = space after keyword.
981         let offset = self.keyword.len() + label_string.len() + 1;
982
983         let pat_expr_string = match self.cond {
984             Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
985             None => String::new(),
986         };
987
988         let brace_overhead =
989             if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
990                 // 2 = ` {`
991                 2
992             } else {
993                 0
994             };
995         let one_line_budget = context
996             .config
997             .max_width()
998             .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
999         let force_newline_brace = (pat_expr_string.contains('\n')
1000             || pat_expr_string.len() > one_line_budget)
1001             && !last_line_extendable(&pat_expr_string);
1002
1003         // Try to format if-else on single line.
1004         if self.allow_single_line
1005             && context
1006                 .config
1007                 .width_heuristics()
1008                 .single_line_if_else_max_width > 0
1009         {
1010             let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1011
1012             if let Some(cond_str) = trial {
1013                 if cond_str.len()
1014                     <= context
1015                         .config
1016                         .width_heuristics()
1017                         .single_line_if_else_max_width
1018                 {
1019                     return Some((cond_str, 0));
1020                 }
1021             }
1022         }
1023
1024         let cond_span = if let Some(cond) = self.cond {
1025             cond.span
1026         } else {
1027             mk_sp(self.block.span.lo(), self.block.span.lo())
1028         };
1029
1030         // `for event in event`
1031         // Do not include label in the span.
1032         let lo = self
1033             .label
1034             .map_or(self.span.lo(), |label| label.ident.span.hi());
1035         let between_kwd_cond = mk_sp(
1036             context
1037                 .snippet_provider
1038                 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
1039             if self.pats.is_empty() {
1040                 cond_span.lo()
1041             } else if self.matcher.is_empty() {
1042                 self.pats[0].span.lo()
1043             } else {
1044                 context
1045                     .snippet_provider
1046                     .span_before(self.span, self.matcher.trim())
1047             },
1048         );
1049
1050         let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1051
1052         let after_cond_comment =
1053             extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
1054
1055         let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1056             ""
1057         } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
1058             || force_newline_brace
1059         {
1060             alt_block_sep
1061         } else {
1062             " "
1063         };
1064
1065         let used_width = if pat_expr_string.contains('\n') {
1066             last_line_width(&pat_expr_string)
1067         } else {
1068             // 2 = spaces after keyword and condition.
1069             label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1070         };
1071
1072         Some((
1073             format!(
1074                 "{}{}{}{}{}",
1075                 label_string,
1076                 self.keyword,
1077                 between_kwd_cond_comment.as_ref().map_or(
1078                     if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1079                         ""
1080                     } else {
1081                         " "
1082                     },
1083                     |s| &**s,
1084                 ),
1085                 pat_expr_string,
1086                 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1087             ),
1088             used_width,
1089         ))
1090     }
1091 }
1092
1093 impl<'a> Rewrite for ControlFlow<'a> {
1094     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1095         debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1096
1097         let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1098         let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1099         // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1100         if used_width == 0 {
1101             return Some(cond_str);
1102         }
1103
1104         let block_width = shape.width.saturating_sub(used_width);
1105         // This is used only for the empty block case: `{}`. So, we use 1 if we know
1106         // we should avoid the single line case.
1107         let block_width = if self.else_block.is_some() || self.nested_if {
1108             min(1, block_width)
1109         } else {
1110             block_width
1111         };
1112         let block_shape = Shape {
1113             width: block_width,
1114             ..shape
1115         };
1116         let block_str = {
1117             let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1118             let result =
1119                 rewrite_block_with_visitor(context, "", self.block, None, block_shape, true);
1120             context.is_if_else_block.replace(old_val);
1121             result?
1122         };
1123
1124         let mut result = format!("{}{}", cond_str, block_str);
1125
1126         if let Some(else_block) = self.else_block {
1127             let shape = Shape::indented(shape.indent, context.config);
1128             let mut last_in_chain = false;
1129             let rewrite = match else_block.node {
1130                 // If the else expression is another if-else expression, prevent it
1131                 // from being formatted on a single line.
1132                 // Note how we're passing the original shape, as the
1133                 // cost of "else" should not cascade.
1134                 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1135                     ControlFlow::new_if(
1136                         cond,
1137                         ptr_vec_to_ref_vec(pat),
1138                         if_block,
1139                         next_else_block.as_ref().map(|e| &**e),
1140                         false,
1141                         true,
1142                         mk_sp(else_block.span.lo(), self.span.hi()),
1143                     ).rewrite(context, shape)
1144                 }
1145                 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1146                     ControlFlow::new_if(
1147                         cond,
1148                         vec![],
1149                         if_block,
1150                         next_else_block.as_ref().map(|e| &**e),
1151                         false,
1152                         true,
1153                         mk_sp(else_block.span.lo(), self.span.hi()),
1154                     ).rewrite(context, shape)
1155                 }
1156                 _ => {
1157                     last_in_chain = true;
1158                     // When rewriting a block, the width is only used for single line
1159                     // blocks, passing 1 lets us avoid that.
1160                     let else_shape = Shape {
1161                         width: min(1, shape.width),
1162                         ..shape
1163                     };
1164                     format_expr(else_block, ExprType::Statement, context, else_shape)
1165                 }
1166             };
1167
1168             let between_kwd_else_block = mk_sp(
1169                 self.block.span.hi(),
1170                 context
1171                     .snippet_provider
1172                     .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1173             );
1174             let between_kwd_else_block_comment =
1175                 extract_comment(between_kwd_else_block, context, shape);
1176
1177             let after_else = mk_sp(
1178                 context
1179                     .snippet_provider
1180                     .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1181                 else_block.span.lo(),
1182             );
1183             let after_else_comment = extract_comment(after_else, context, shape);
1184
1185             let between_sep = match context.config.control_brace_style() {
1186                 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1187                     &*alt_block_sep
1188                 }
1189                 ControlBraceStyle::AlwaysSameLine => " ",
1190             };
1191             let after_sep = match context.config.control_brace_style() {
1192                 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1193                 _ => " ",
1194             };
1195
1196             result.push_str(&format!(
1197                 "{}else{}",
1198                 between_kwd_else_block_comment
1199                     .as_ref()
1200                     .map_or(between_sep, |s| &**s),
1201                 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1202             ));
1203             result.push_str(&rewrite?);
1204         }
1205
1206         Some(result)
1207     }
1208 }
1209
1210 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1211     match opt_label {
1212         Some(label) => Cow::from(format!("{}: ", label.ident)),
1213         None => Cow::from(""),
1214     }
1215 }
1216
1217 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1218     match rewrite_missing_comment(span, shape, context) {
1219         Some(ref comment) if !comment.is_empty() => Some(format!(
1220             "{indent}{}{indent}",
1221             comment,
1222             indent = shape.indent.to_string_with_newline(context.config)
1223         )),
1224         _ => None,
1225     }
1226 }
1227
1228 pub fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1229     let snippet = codemap.span_to_snippet(block.span).unwrap();
1230     contains_comment(&snippet)
1231 }
1232
1233 // Checks that a block contains no statements, an expression and no comments or
1234 // attributes.
1235 // FIXME: incorrectly returns false when comment is contained completely within
1236 // the expression.
1237 pub fn is_simple_block(
1238     block: &ast::Block,
1239     attrs: Option<&[ast::Attribute]>,
1240     codemap: &CodeMap,
1241 ) -> bool {
1242     (block.stmts.len() == 1
1243         && stmt_is_expr(&block.stmts[0])
1244         && !block_contains_comment(block, codemap)
1245         && attrs.map_or(true, |a| a.is_empty()))
1246 }
1247
1248 /// Checks whether a block contains at most one statement or expression, and no
1249 /// comments or attributes.
1250 pub fn is_simple_block_stmt(
1251     block: &ast::Block,
1252     attrs: Option<&[ast::Attribute]>,
1253     codemap: &CodeMap,
1254 ) -> bool {
1255     block.stmts.len() <= 1
1256         && !block_contains_comment(block, codemap)
1257         && attrs.map_or(true, |a| a.is_empty())
1258 }
1259
1260 /// Checks whether a block contains no statements, expressions, comments, or
1261 /// inner attributes.
1262 pub fn is_empty_block(
1263     block: &ast::Block,
1264     attrs: Option<&[ast::Attribute]>,
1265     codemap: &CodeMap,
1266 ) -> bool {
1267     block.stmts.is_empty()
1268         && !block_contains_comment(block, codemap)
1269         && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1270 }
1271
1272 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1273     match stmt.node {
1274         ast::StmtKind::Expr(..) => true,
1275         _ => false,
1276     }
1277 }
1278
1279 pub fn is_unsafe_block(block: &ast::Block) -> bool {
1280     if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1281         true
1282     } else {
1283         false
1284     }
1285 }
1286
1287 pub fn rewrite_multiple_patterns(
1288     context: &RewriteContext,
1289     pats: &[&ast::Pat],
1290     shape: Shape,
1291 ) -> Option<String> {
1292     let pat_strs = pats
1293         .iter()
1294         .map(|p| p.rewrite(context, shape))
1295         .collect::<Option<Vec<_>>>()?;
1296
1297     let use_mixed_layout = pats
1298         .iter()
1299         .zip(pat_strs.iter())
1300         .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
1301     let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1302     let tactic = if use_mixed_layout {
1303         DefinitiveListTactic::Mixed
1304     } else {
1305         definitive_tactic(
1306             &items,
1307             ListTactic::HorizontalVertical,
1308             Separator::VerticalBar,
1309             shape.width,
1310         )
1311     };
1312     let fmt = ListFormatting {
1313         tactic,
1314         separator: " |",
1315         trailing_separator: SeparatorTactic::Never,
1316         separator_place: context.config.binop_separator(),
1317         shape,
1318         ends_with_newline: false,
1319         preserve_newline: false,
1320         config: context.config,
1321     };
1322     write_list(&items, &fmt)
1323 }
1324
1325 pub fn rewrite_literal(context: &RewriteContext, l: &ast::Lit, shape: Shape) -> Option<String> {
1326     match l.node {
1327         ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1328         _ => wrap_str(
1329             context.snippet(l.span).to_owned(),
1330             context.config.max_width(),
1331             shape,
1332         ),
1333     }
1334 }
1335
1336 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1337     let string_lit = context.snippet(span);
1338
1339     if !context.config.format_strings() {
1340         if string_lit
1341             .lines()
1342             .rev()
1343             .skip(1)
1344             .all(|line| line.ends_with('\\'))
1345         {
1346             let new_indent = shape.visual_indent(1).indent;
1347             let indented_string_lit = String::from(
1348                 string_lit
1349                     .lines()
1350                     .map(|line| {
1351                         format!(
1352                             "{}{}",
1353                             new_indent.to_string(context.config),
1354                             line.trim_left()
1355                         )
1356                     })
1357                     .collect::<Vec<_>>()
1358                     .join("\n")
1359                     .trim_left(),
1360             );
1361             return wrap_str(indented_string_lit, context.config.max_width(), shape);
1362         } else {
1363             return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1364         }
1365     }
1366
1367     // Remove the quote characters.
1368     let str_lit = &string_lit[1..string_lit.len() - 1];
1369
1370     rewrite_string(
1371         str_lit,
1372         &StringFormat::new(shape.visual_indent(0), context.config),
1373         None,
1374     )
1375 }
1376
1377 /// In case special-case style is required, returns an offset from which we start horizontal layout.
1378 pub fn maybe_get_args_offset<T: ToExpr>(callee_str: &str, args: &[&T]) -> Option<(bool, usize)> {
1379     if let Some(&(_, num_args_before)) = SPECIAL_MACRO_WHITELIST
1380         .iter()
1381         .find(|&&(s, _)| s == callee_str)
1382     {
1383         let all_simple = args.len() > num_args_before && is_every_expr_simple(args);
1384
1385         Some((all_simple, num_args_before))
1386     } else {
1387         None
1388     }
1389 }
1390
1391 /// A list of `format!`-like macros, that take a long format string and a list of arguments to
1392 /// format.
1393 ///
1394 /// Organized as a list of `(&str, usize)` tuples, giving the name of the macro and the number of
1395 /// arguments before the format string (none for `format!("format", ...)`, one for `assert!(result,
1396 /// "format", ...)`, two for `assert_eq!(left, right, "format", ...)`).
1397 const SPECIAL_MACRO_WHITELIST: &[(&str, usize)] = &[
1398     // format! like macros
1399     // From the Rust Standard Library.
1400     ("eprint!", 0),
1401     ("eprintln!", 0),
1402     ("format!", 0),
1403     ("format_args!", 0),
1404     ("print!", 0),
1405     ("println!", 0),
1406     ("panic!", 0),
1407     ("unreachable!", 0),
1408     // From the `log` crate.
1409     ("debug!", 0),
1410     ("error!", 0),
1411     ("info!", 0),
1412     ("warn!", 0),
1413     // write! like macros
1414     ("assert!", 1),
1415     ("debug_assert!", 1),
1416     ("write!", 1),
1417     ("writeln!", 1),
1418     // assert_eq! like macros
1419     ("assert_eq!", 2),
1420     ("assert_ne!", 2),
1421     ("debug_assert_eq!", 2),
1422     ("debug_assert_ne!", 2),
1423 ];
1424
1425 fn choose_separator_tactic(context: &RewriteContext, span: Span) -> Option<SeparatorTactic> {
1426     if context.inside_macro() {
1427         if span_ends_with_comma(context, span) {
1428             Some(SeparatorTactic::Always)
1429         } else {
1430             Some(SeparatorTactic::Never)
1431         }
1432     } else {
1433         None
1434     }
1435 }
1436
1437 pub fn rewrite_call(
1438     context: &RewriteContext,
1439     callee: &str,
1440     args: &[ptr::P<ast::Expr>],
1441     span: Span,
1442     shape: Shape,
1443 ) -> Option<String> {
1444     overflow::rewrite_with_parens(
1445         context,
1446         callee,
1447         &ptr_vec_to_ref_vec(args),
1448         shape,
1449         span,
1450         context.config.width_heuristics().fn_call_width,
1451         choose_separator_tactic(context, span),
1452     )
1453 }
1454
1455 fn is_simple_expr(expr: &ast::Expr) -> bool {
1456     match expr.node {
1457         ast::ExprKind::Lit(..) => true,
1458         ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1459         ast::ExprKind::AddrOf(_, ref expr)
1460         | ast::ExprKind::Box(ref expr)
1461         | ast::ExprKind::Cast(ref expr, _)
1462         | ast::ExprKind::Field(ref expr, _)
1463         | ast::ExprKind::Try(ref expr)
1464         | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1465         ast::ExprKind::Index(ref lhs, ref rhs) | ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1466             is_simple_expr(lhs) && is_simple_expr(rhs)
1467         }
1468         _ => false,
1469     }
1470 }
1471
1472 pub fn is_every_expr_simple<T: ToExpr>(lists: &[&T]) -> bool {
1473     lists
1474         .iter()
1475         .all(|arg| arg.to_expr().map_or(false, is_simple_expr))
1476 }
1477
1478 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
1479     match expr.node {
1480         ast::ExprKind::Match(..) => {
1481             (context.use_block_indent() && args_len == 1)
1482                 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1483         }
1484         ast::ExprKind::If(..)
1485         | ast::ExprKind::IfLet(..)
1486         | ast::ExprKind::ForLoop(..)
1487         | ast::ExprKind::Loop(..)
1488         | ast::ExprKind::While(..)
1489         | ast::ExprKind::WhileLet(..) => {
1490             context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1491         }
1492         ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
1493             context.use_block_indent()
1494                 || context.config.indent_style() == IndentStyle::Visual && args_len > 1
1495         }
1496         ast::ExprKind::Array(..)
1497         | ast::ExprKind::Call(..)
1498         | ast::ExprKind::Mac(..)
1499         | ast::ExprKind::MethodCall(..)
1500         | ast::ExprKind::Struct(..)
1501         | ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
1502         ast::ExprKind::AddrOf(_, ref expr)
1503         | ast::ExprKind::Box(ref expr)
1504         | ast::ExprKind::Try(ref expr)
1505         | ast::ExprKind::Unary(_, ref expr)
1506         | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1507         _ => false,
1508     }
1509 }
1510
1511 pub fn is_nested_call(expr: &ast::Expr) -> bool {
1512     match expr.node {
1513         ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
1514         ast::ExprKind::AddrOf(_, ref expr)
1515         | ast::ExprKind::Box(ref expr)
1516         | ast::ExprKind::Try(ref expr)
1517         | ast::ExprKind::Unary(_, ref expr)
1518         | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1519         _ => false,
1520     }
1521 }
1522
1523 /// Return true if a function call or a method call represented by the given span ends with a
1524 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1525 /// comma from macro can potentially break the code.
1526 pub fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
1527     let mut result: bool = Default::default();
1528     let mut prev_char: char = Default::default();
1529     let closing_delimiters = &[')', '}', ']'];
1530
1531     for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1532         match c {
1533             _ if kind.is_comment() || c.is_whitespace() => continue,
1534             c if closing_delimiters.contains(&c) => {
1535                 result &= !closing_delimiters.contains(&prev_char);
1536             }
1537             ',' => result = true,
1538             _ => result = false,
1539         }
1540         prev_char = c;
1541     }
1542
1543     result
1544 }
1545
1546 fn rewrite_paren(
1547     context: &RewriteContext,
1548     mut subexpr: &ast::Expr,
1549     shape: Shape,
1550     mut span: Span,
1551 ) -> Option<String> {
1552     debug!("rewrite_paren, shape: {:?}", shape);
1553
1554     // Extract comments within parens.
1555     let mut pre_comment;
1556     let mut post_comment;
1557     let remove_nested_parens = context.config.remove_nested_parens();
1558     loop {
1559         // 1 = "(" or ")"
1560         let pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1561         let post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1562         pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1563         post_comment = rewrite_missing_comment(post_span, shape, context)?;
1564
1565         // Remove nested parens if there are no comments.
1566         if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.node {
1567             if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1568                 span = subexpr.span;
1569                 subexpr = subsubexpr;
1570                 continue;
1571             }
1572         }
1573
1574         break;
1575     }
1576
1577     // 1 `(`
1578     let sub_shape = shape.offset_left(1).and_then(|s| s.sub_width(1))?;
1579
1580     let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1581     debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1582
1583     // 2 = `()`
1584     if subexpr_str.contains('\n') || first_line_width(&subexpr_str) + 2 <= shape.width {
1585         Some(format!("({}{}{})", pre_comment, &subexpr_str, post_comment))
1586     } else {
1587         None
1588     }
1589 }
1590
1591 fn rewrite_index(
1592     expr: &ast::Expr,
1593     index: &ast::Expr,
1594     context: &RewriteContext,
1595     shape: Shape,
1596 ) -> Option<String> {
1597     let expr_str = expr.rewrite(context, shape)?;
1598
1599     let offset = last_line_width(&expr_str) + 1;
1600     let rhs_overhead = shape.rhs_overhead(context.config);
1601     let index_shape = if expr_str.contains('\n') {
1602         Shape::legacy(context.config.max_width(), shape.indent)
1603             .offset_left(offset)
1604             .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1605     } else {
1606         shape.visual_indent(offset).sub_width(offset + 1)
1607     };
1608     let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1609
1610     // Return if index fits in a single line.
1611     match orig_index_rw {
1612         Some(ref index_str) if !index_str.contains('\n') => {
1613             return Some(format!("{}[{}]", expr_str, index_str));
1614         }
1615         _ => (),
1616     }
1617
1618     // Try putting index on the next line and see if it fits in a single line.
1619     let indent = shape.indent.block_indent(context.config);
1620     let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1621     let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1622     let new_index_rw = index.rewrite(context, index_shape);
1623     match (orig_index_rw, new_index_rw) {
1624         (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1625             "{}{}[{}]",
1626             expr_str,
1627             indent.to_string_with_newline(context.config),
1628             new_index_str,
1629         )),
1630         (None, Some(ref new_index_str)) => Some(format!(
1631             "{}{}[{}]",
1632             expr_str,
1633             indent.to_string_with_newline(context.config),
1634             new_index_str,
1635         )),
1636         (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1637         _ => None,
1638     }
1639 }
1640
1641 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
1642     if base.is_some() {
1643         return false;
1644     }
1645
1646     fields.iter().all(|field| !field.is_shorthand)
1647 }
1648
1649 fn rewrite_struct_lit<'a>(
1650     context: &RewriteContext,
1651     path: &ast::Path,
1652     fields: &'a [ast::Field],
1653     base: Option<&'a ast::Expr>,
1654     span: Span,
1655     shape: Shape,
1656 ) -> Option<String> {
1657     debug!("rewrite_struct_lit: shape {:?}", shape);
1658
1659     enum StructLitField<'a> {
1660         Regular(&'a ast::Field),
1661         Base(&'a ast::Expr),
1662     }
1663
1664     // 2 = " {".len()
1665     let path_shape = shape.sub_width(2)?;
1666     let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
1667
1668     if fields.is_empty() && base.is_none() {
1669         return Some(format!("{} {{}}", path_str));
1670     }
1671
1672     // Foo { a: Foo } - indent is +3, width is -5.
1673     let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1674
1675     let one_line_width = h_shape.map_or(0, |shape| shape.width);
1676     let body_lo = context.snippet_provider.span_after(span, "{");
1677     let fields_str = if struct_lit_can_be_aligned(fields, &base)
1678         && context.config.struct_field_align_threshold() > 0
1679     {
1680         rewrite_with_alignment(
1681             fields,
1682             context,
1683             shape,
1684             mk_sp(body_lo, span.hi()),
1685             one_line_width,
1686         )?
1687     } else {
1688         let field_iter = fields
1689             .into_iter()
1690             .map(StructLitField::Regular)
1691             .chain(base.into_iter().map(StructLitField::Base));
1692
1693         let span_lo = |item: &StructLitField| match *item {
1694             StructLitField::Regular(field) => field.span().lo(),
1695             StructLitField::Base(expr) => {
1696                 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1697                 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1698                 let pos = snippet.find_uncommented("..").unwrap();
1699                 last_field_hi + BytePos(pos as u32)
1700             }
1701         };
1702         let span_hi = |item: &StructLitField| match *item {
1703             StructLitField::Regular(field) => field.span().hi(),
1704             StructLitField::Base(expr) => expr.span.hi(),
1705         };
1706         let rewrite = |item: &StructLitField| match *item {
1707             StructLitField::Regular(field) => {
1708                 // The 1 taken from the v_budget is for the comma.
1709                 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1710             }
1711             StructLitField::Base(expr) => {
1712                 // 2 = ..
1713                 expr.rewrite(context, v_shape.offset_left(2)?)
1714                     .map(|s| format!("..{}", s))
1715             }
1716         };
1717
1718         let items = itemize_list(
1719             context.snippet_provider,
1720             field_iter,
1721             "}",
1722             ",",
1723             span_lo,
1724             span_hi,
1725             rewrite,
1726             body_lo,
1727             span.hi(),
1728             false,
1729         );
1730         let item_vec = items.collect::<Vec<_>>();
1731
1732         let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1733         let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1734
1735         let ends_with_comma = span_ends_with_comma(context, span);
1736         let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1737
1738         let fmt = struct_lit_formatting(
1739             nested_shape,
1740             tactic,
1741             context,
1742             force_no_trailing_comma || base.is_some(),
1743         );
1744
1745         write_list(&item_vec, &fmt)?
1746     };
1747
1748     let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
1749     Some(format!("{} {{{}}}", path_str, fields_str))
1750
1751     // FIXME if context.config.indent_style() == Visual, but we run out
1752     // of space, we should fall back to BlockIndent.
1753 }
1754
1755 pub fn wrap_struct_field(
1756     context: &RewriteContext,
1757     fields_str: &str,
1758     shape: Shape,
1759     nested_shape: Shape,
1760     one_line_width: usize,
1761 ) -> String {
1762     if context.config.indent_style() == IndentStyle::Block
1763         && (fields_str.contains('\n')
1764             || !context.config.struct_lit_single_line()
1765             || fields_str.len() > one_line_width)
1766     {
1767         format!(
1768             "{}{}{}",
1769             nested_shape.indent.to_string_with_newline(context.config),
1770             fields_str,
1771             shape.indent.to_string_with_newline(context.config)
1772         )
1773     } else {
1774         // One liner or visual indent.
1775         format!(" {} ", fields_str)
1776     }
1777 }
1778
1779 pub fn struct_lit_field_separator(config: &Config) -> &str {
1780     colon_spaces(config.space_before_colon(), config.space_after_colon())
1781 }
1782
1783 pub fn rewrite_field(
1784     context: &RewriteContext,
1785     field: &ast::Field,
1786     shape: Shape,
1787     prefix_max_width: usize,
1788 ) -> Option<String> {
1789     if contains_skip(&field.attrs) {
1790         return Some(context.snippet(field.span()).to_owned());
1791     }
1792     let mut attrs_str = field.attrs.rewrite(context, shape)?;
1793     if !attrs_str.is_empty() {
1794         attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1795     };
1796     let name = &field.ident.name.to_string();
1797     if field.is_shorthand {
1798         Some(attrs_str + &name)
1799     } else {
1800         let mut separator = String::from(struct_lit_field_separator(context.config));
1801         for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1802             separator.push(' ');
1803         }
1804         let overhead = name.len() + separator.len();
1805         let expr_shape = shape.offset_left(overhead)?;
1806         let expr = field.expr.rewrite(context, expr_shape);
1807
1808         match expr {
1809             Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1810                 Some(attrs_str + &name)
1811             }
1812             Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1813             None => {
1814                 let expr_offset = shape.indent.block_indent(context.config);
1815                 let expr = field
1816                     .expr
1817                     .rewrite(context, Shape::indented(expr_offset, context.config));
1818                 expr.map(|s| {
1819                     format!(
1820                         "{}{}:\n{}{}",
1821                         attrs_str,
1822                         name,
1823                         expr_offset.to_string(context.config),
1824                         s
1825                     )
1826                 })
1827             }
1828         }
1829     }
1830 }
1831
1832 fn rewrite_tuple_in_visual_indent_style<'a, T>(
1833     context: &RewriteContext,
1834     items: &[&T],
1835     span: Span,
1836     shape: Shape,
1837 ) -> Option<String>
1838 where
1839     T: Rewrite + Spanned + ToExpr + 'a,
1840 {
1841     let mut items = items.iter();
1842     // In case of length 1, need a trailing comma
1843     debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1844     if items.len() == 1 {
1845         // 3 = "(" + ",)"
1846         let nested_shape = shape.sub_width(3)?.visual_indent(1);
1847         return items
1848             .next()
1849             .unwrap()
1850             .rewrite(context, nested_shape)
1851             .map(|s| format!("({},)", s));
1852     }
1853
1854     let list_lo = context.snippet_provider.span_after(span, "(");
1855     let nested_shape = shape.sub_width(2)?.visual_indent(1);
1856     let items = itemize_list(
1857         context.snippet_provider,
1858         items,
1859         ")",
1860         ",",
1861         |item| item.span().lo(),
1862         |item| item.span().hi(),
1863         |item| item.rewrite(context, nested_shape),
1864         list_lo,
1865         span.hi() - BytePos(1),
1866         false,
1867     );
1868     let item_vec: Vec<_> = items.collect();
1869     let tactic = definitive_tactic(
1870         &item_vec,
1871         ListTactic::HorizontalVertical,
1872         Separator::Comma,
1873         nested_shape.width,
1874     );
1875     let fmt = ListFormatting {
1876         tactic,
1877         separator: ",",
1878         trailing_separator: SeparatorTactic::Never,
1879         separator_place: SeparatorPlace::Back,
1880         shape,
1881         ends_with_newline: false,
1882         preserve_newline: false,
1883         config: context.config,
1884     };
1885     let list_str = write_list(&item_vec, &fmt)?;
1886
1887     Some(format!("({})", list_str))
1888 }
1889
1890 pub fn rewrite_tuple<'a, T>(
1891     context: &RewriteContext,
1892     items: &[&T],
1893     span: Span,
1894     shape: Shape,
1895 ) -> Option<String>
1896 where
1897     T: Rewrite + Spanned + ToExpr + 'a,
1898 {
1899     debug!("rewrite_tuple {:?}", shape);
1900     if context.use_block_indent() {
1901         // We use the same rule as function calls for rewriting tuples.
1902         let force_tactic = if context.inside_macro() {
1903             if span_ends_with_comma(context, span) {
1904                 Some(SeparatorTactic::Always)
1905             } else {
1906                 Some(SeparatorTactic::Never)
1907             }
1908         } else if items.len() == 1 {
1909             Some(SeparatorTactic::Always)
1910         } else {
1911             None
1912         };
1913         overflow::rewrite_with_parens(
1914             context,
1915             "",
1916             items,
1917             shape,
1918             span,
1919             context.config.width_heuristics().fn_call_width,
1920             force_tactic,
1921         )
1922     } else {
1923         rewrite_tuple_in_visual_indent_style(context, items, span, shape)
1924     }
1925 }
1926
1927 pub fn rewrite_unary_prefix<R: Rewrite>(
1928     context: &RewriteContext,
1929     prefix: &str,
1930     rewrite: &R,
1931     shape: Shape,
1932 ) -> Option<String> {
1933     rewrite
1934         .rewrite(context, shape.offset_left(prefix.len())?)
1935         .map(|r| format!("{}{}", prefix, r))
1936 }
1937
1938 // FIXME: this is probably not correct for multi-line Rewrites. we should
1939 // subtract suffix.len() from the last line budget, not the first!
1940 pub fn rewrite_unary_suffix<R: Rewrite>(
1941     context: &RewriteContext,
1942     suffix: &str,
1943     rewrite: &R,
1944     shape: Shape,
1945 ) -> Option<String> {
1946     rewrite
1947         .rewrite(context, shape.sub_width(suffix.len())?)
1948         .map(|mut r| {
1949             r.push_str(suffix);
1950             r
1951         })
1952 }
1953
1954 fn rewrite_unary_op(
1955     context: &RewriteContext,
1956     op: &ast::UnOp,
1957     expr: &ast::Expr,
1958     shape: Shape,
1959 ) -> Option<String> {
1960     // For some reason, an UnOp is not spanned like BinOp!
1961     let operator_str = match *op {
1962         ast::UnOp::Deref => "*",
1963         ast::UnOp::Not => "!",
1964         ast::UnOp::Neg => "-",
1965     };
1966     rewrite_unary_prefix(context, operator_str, expr, shape)
1967 }
1968
1969 fn rewrite_assignment(
1970     context: &RewriteContext,
1971     lhs: &ast::Expr,
1972     rhs: &ast::Expr,
1973     op: Option<&ast::BinOp>,
1974     shape: Shape,
1975 ) -> Option<String> {
1976     let operator_str = match op {
1977         Some(op) => context.snippet(op.span),
1978         None => "=",
1979     };
1980
1981     // 1 = space between lhs and operator.
1982     let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1983     let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1984
1985     rewrite_assign_rhs(context, lhs_str, rhs, shape)
1986 }
1987
1988 /// Controls where to put the rhs.
1989 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1990 pub enum RhsTactics {
1991     /// Use heuristics.
1992     Default,
1993     /// Put the rhs on the next line if it uses multiple line.
1994     ForceNextLine,
1995 }
1996
1997 // The left hand side must contain everything up to, and including, the
1998 // assignment operator.
1999 pub fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
2000     context: &RewriteContext,
2001     lhs: S,
2002     ex: &R,
2003     shape: Shape,
2004 ) -> Option<String> {
2005     rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
2006 }
2007
2008 pub fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
2009     context: &RewriteContext,
2010     lhs: S,
2011     ex: &R,
2012     shape: Shape,
2013     rhs_tactics: RhsTactics,
2014 ) -> Option<String> {
2015     let lhs = lhs.into();
2016     let last_line_width = last_line_width(&lhs).saturating_sub(if lhs.contains('\n') {
2017         shape.indent.width()
2018     } else {
2019         0
2020     });
2021     // 1 = space between operator and rhs.
2022     let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
2023         width: 0,
2024         offset: shape.offset + last_line_width + 1,
2025         ..shape
2026     });
2027     let rhs = choose_rhs(
2028         context,
2029         ex,
2030         orig_shape,
2031         ex.rewrite(context, orig_shape),
2032         rhs_tactics,
2033     )?;
2034     Some(lhs + &rhs)
2035 }
2036
2037 fn choose_rhs<R: Rewrite>(
2038     context: &RewriteContext,
2039     expr: &R,
2040     shape: Shape,
2041     orig_rhs: Option<String>,
2042     rhs_tactics: RhsTactics,
2043 ) -> Option<String> {
2044     match orig_rhs {
2045         Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
2046             Some(format!(" {}", new_str))
2047         }
2048         _ => {
2049             // Expression did not fit on the same line as the identifier.
2050             // Try splitting the line and see if that works better.
2051             let new_shape =
2052                 Shape::indented(shape.indent.block_indent(context.config), context.config)
2053                     .sub_width(shape.rhs_overhead(context.config))?;
2054             let new_rhs = expr.rewrite(context, new_shape);
2055             let new_indent_str = &new_shape.indent.to_string_with_newline(context.config);
2056
2057             match (orig_rhs, new_rhs) {
2058                 (Some(ref orig_rhs), Some(ref new_rhs))
2059                     if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
2060                         .is_none() =>
2061                 {
2062                     Some(format!(" {}", orig_rhs))
2063                 }
2064                 (Some(ref orig_rhs), Some(ref new_rhs))
2065                     if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
2066                 {
2067                     Some(format!("{}{}", new_indent_str, new_rhs))
2068                 }
2069                 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
2070                 (None, None) => None,
2071                 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2072             }
2073         }
2074     }
2075 }
2076
2077 pub fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str, rhs_tactics: RhsTactics) -> bool {
2078     rhs_tactics == RhsTactics::ForceNextLine
2079         || !next_line_rhs.contains('\n')
2080         || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2081 }
2082
2083 fn rewrite_expr_addrof(
2084     context: &RewriteContext,
2085     mutability: ast::Mutability,
2086     expr: &ast::Expr,
2087     shape: Shape,
2088 ) -> Option<String> {
2089     let operator_str = match mutability {
2090         ast::Mutability::Immutable => "&",
2091         ast::Mutability::Mutable => "&mut ",
2092     };
2093     rewrite_unary_prefix(context, operator_str, expr, shape)
2094 }
2095
2096 pub trait ToExpr {
2097     fn to_expr(&self) -> Option<&ast::Expr>;
2098     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2099 }
2100
2101 impl ToExpr for ast::Expr {
2102     fn to_expr(&self) -> Option<&ast::Expr> {
2103         Some(self)
2104     }
2105
2106     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2107         can_be_overflowed_expr(context, self, len)
2108     }
2109 }
2110
2111 impl ToExpr for ast::Ty {
2112     fn to_expr(&self) -> Option<&ast::Expr> {
2113         None
2114     }
2115
2116     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2117         can_be_overflowed_type(context, self, len)
2118     }
2119 }
2120
2121 impl<'a> ToExpr for TuplePatField<'a> {
2122     fn to_expr(&self) -> Option<&ast::Expr> {
2123         None
2124     }
2125
2126     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2127         can_be_overflowed_pat(context, self, len)
2128     }
2129 }
2130
2131 impl<'a> ToExpr for ast::StructField {
2132     fn to_expr(&self) -> Option<&ast::Expr> {
2133         None
2134     }
2135
2136     fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
2137         false
2138     }
2139 }
2140
2141 impl<'a> ToExpr for MacroArg {
2142     fn to_expr(&self) -> Option<&ast::Expr> {
2143         match *self {
2144             MacroArg::Expr(ref expr) => Some(expr),
2145             _ => None,
2146         }
2147     }
2148
2149     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2150         match *self {
2151             MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
2152             MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
2153             MacroArg::Pat(..) => false,
2154             MacroArg::Item(..) => len == 1,
2155         }
2156     }
2157 }
2158
2159 impl ToExpr for ast::GenericParam {
2160     fn to_expr(&self) -> Option<&ast::Expr> {
2161         None
2162     }
2163
2164     fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
2165         false
2166     }
2167 }