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