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