]> git.lizzy.rs Git - rust.git/blob - src/expr.rs
cd8bfa8a72bad6e1b7880fcaf558f01c71b68d58
[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             None,
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 pub fn rewrite_call(
1340     context: &RewriteContext,
1341     callee: &str,
1342     args: &[ptr::P<ast::Expr>],
1343     span: Span,
1344     shape: Shape,
1345 ) -> Option<String> {
1346     overflow::rewrite_with_parens(
1347         context,
1348         callee,
1349         &ptr_vec_to_ref_vec(args),
1350         shape,
1351         span,
1352         context.config.width_heuristics().fn_call_width,
1353         if context.inside_macro() {
1354             if span_ends_with_comma(context, span) {
1355                 Some(SeparatorTactic::Always)
1356             } else {
1357                 Some(SeparatorTactic::Never)
1358             }
1359         } else {
1360             None
1361         },
1362     )
1363 }
1364
1365 fn is_simple_expr(expr: &ast::Expr) -> bool {
1366     match expr.node {
1367         ast::ExprKind::Lit(..) => true,
1368         ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1369         ast::ExprKind::AddrOf(_, ref expr)
1370         | ast::ExprKind::Box(ref expr)
1371         | ast::ExprKind::Cast(ref expr, _)
1372         | ast::ExprKind::Field(ref expr, _)
1373         | ast::ExprKind::Try(ref expr)
1374         | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1375         ast::ExprKind::Index(ref lhs, ref rhs) | ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1376             is_simple_expr(lhs) && is_simple_expr(rhs)
1377         }
1378         _ => false,
1379     }
1380 }
1381
1382 pub fn is_every_expr_simple<T: ToExpr>(lists: &[&T]) -> bool {
1383     lists
1384         .iter()
1385         .all(|arg| arg.to_expr().map_or(false, is_simple_expr))
1386 }
1387
1388 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
1389     match expr.node {
1390         ast::ExprKind::Match(..) => {
1391             (context.use_block_indent() && args_len == 1)
1392                 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1393         }
1394         ast::ExprKind::If(..)
1395         | ast::ExprKind::IfLet(..)
1396         | ast::ExprKind::ForLoop(..)
1397         | ast::ExprKind::Loop(..)
1398         | ast::ExprKind::While(..)
1399         | ast::ExprKind::WhileLet(..) => {
1400             context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1401         }
1402         ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
1403             context.use_block_indent()
1404                 || context.config.indent_style() == IndentStyle::Visual && args_len > 1
1405         }
1406         ast::ExprKind::Array(..)
1407         | ast::ExprKind::Call(..)
1408         | ast::ExprKind::Mac(..)
1409         | ast::ExprKind::MethodCall(..)
1410         | ast::ExprKind::Struct(..)
1411         | ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
1412         ast::ExprKind::AddrOf(_, ref expr)
1413         | ast::ExprKind::Box(ref expr)
1414         | ast::ExprKind::Try(ref expr)
1415         | ast::ExprKind::Unary(_, ref expr)
1416         | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1417         _ => false,
1418     }
1419 }
1420
1421 pub fn is_nested_call(expr: &ast::Expr) -> bool {
1422     match expr.node {
1423         ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
1424         ast::ExprKind::AddrOf(_, ref expr)
1425         | ast::ExprKind::Box(ref expr)
1426         | ast::ExprKind::Try(ref expr)
1427         | ast::ExprKind::Unary(_, ref expr)
1428         | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1429         _ => false,
1430     }
1431 }
1432
1433 /// Return true if a function call or a method call represented by the given span ends with a
1434 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1435 /// comma from macro can potentially break the code.
1436 pub fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
1437     let mut result: bool = Default::default();
1438     let mut prev_char: char = Default::default();
1439
1440     for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1441         match c {
1442             _ if kind.is_comment() || c.is_whitespace() => continue,
1443             ')' | '}' => result = result && prev_char != ')' && prev_char != '}',
1444             ',' => result = true,
1445             _ => result = false,
1446         }
1447         prev_char = c;
1448     }
1449
1450     result
1451 }
1452
1453 fn rewrite_paren(
1454     context: &RewriteContext,
1455     mut subexpr: &ast::Expr,
1456     shape: Shape,
1457     mut span: Span,
1458 ) -> Option<String> {
1459     debug!("rewrite_paren, shape: {:?}", shape);
1460
1461     // Extract comments within parens.
1462     let mut pre_comment;
1463     let mut post_comment;
1464     loop {
1465         // 1 = "(" or ")"
1466         let pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1467         let post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1468         pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1469         post_comment = rewrite_missing_comment(post_span, shape, context)?;
1470
1471         // Remove nested parens if there are no comments.
1472         if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.node {
1473             if pre_comment.is_empty() && post_comment.is_empty() {
1474                 span = subexpr.span;
1475                 subexpr = subsubexpr;
1476                 continue;
1477             }
1478         }
1479
1480         break;
1481     }
1482
1483     let total_paren_overhead = paren_overhead(context);
1484     let paren_overhead = total_paren_overhead / 2;
1485     let sub_shape = shape
1486         .offset_left(paren_overhead)
1487         .and_then(|s| s.sub_width(paren_overhead))?;
1488
1489     let paren_wrapper = |s: &str| {
1490         if context.config.spaces_within_parens_and_brackets() && !s.is_empty() {
1491             format!("( {}{}{} )", pre_comment, s, post_comment)
1492         } else {
1493             format!("({}{}{})", pre_comment, s, post_comment)
1494         }
1495     };
1496
1497     let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1498     debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1499
1500     if subexpr_str.contains('\n')
1501         || first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
1502     {
1503         Some(paren_wrapper(&subexpr_str))
1504     } else {
1505         None
1506     }
1507 }
1508
1509 fn rewrite_index(
1510     expr: &ast::Expr,
1511     index: &ast::Expr,
1512     context: &RewriteContext,
1513     shape: Shape,
1514 ) -> Option<String> {
1515     let expr_str = expr.rewrite(context, shape)?;
1516
1517     let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
1518         ("[ ", " ]")
1519     } else {
1520         ("[", "]")
1521     };
1522
1523     let offset = last_line_width(&expr_str) + lbr.len();
1524     let rhs_overhead = shape.rhs_overhead(context.config);
1525     let index_shape = if expr_str.contains('\n') {
1526         Shape::legacy(context.config.max_width(), shape.indent)
1527             .offset_left(offset)
1528             .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
1529     } else {
1530         shape.visual_indent(offset).sub_width(offset + rbr.len())
1531     };
1532     let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1533
1534     // Return if index fits in a single line.
1535     match orig_index_rw {
1536         Some(ref index_str) if !index_str.contains('\n') => {
1537             return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
1538         }
1539         _ => (),
1540     }
1541
1542     // Try putting index on the next line and see if it fits in a single line.
1543     let indent = shape.indent.block_indent(context.config);
1544     let index_shape = Shape::indented(indent, context.config).offset_left(lbr.len())?;
1545     let index_shape = index_shape.sub_width(rbr.len() + rhs_overhead)?;
1546     let new_index_rw = index.rewrite(context, index_shape);
1547     match (orig_index_rw, new_index_rw) {
1548         (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1549             "{}{}{}{}{}",
1550             expr_str,
1551             indent.to_string_with_newline(context.config),
1552             lbr,
1553             new_index_str,
1554             rbr
1555         )),
1556         (None, Some(ref new_index_str)) => Some(format!(
1557             "{}{}{}{}{}",
1558             expr_str,
1559             indent.to_string_with_newline(context.config),
1560             lbr,
1561             new_index_str,
1562             rbr
1563         )),
1564         (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
1565         _ => None,
1566     }
1567 }
1568
1569 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
1570     if base.is_some() {
1571         return false;
1572     }
1573
1574     fields.iter().all(|field| !field.is_shorthand)
1575 }
1576
1577 fn rewrite_struct_lit<'a>(
1578     context: &RewriteContext,
1579     path: &ast::Path,
1580     fields: &'a [ast::Field],
1581     base: Option<&'a ast::Expr>,
1582     span: Span,
1583     shape: Shape,
1584 ) -> Option<String> {
1585     debug!("rewrite_struct_lit: shape {:?}", shape);
1586
1587     enum StructLitField<'a> {
1588         Regular(&'a ast::Field),
1589         Base(&'a ast::Expr),
1590     }
1591
1592     // 2 = " {".len()
1593     let path_shape = shape.sub_width(2)?;
1594     let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
1595
1596     if fields.is_empty() && base.is_none() {
1597         return Some(format!("{} {{}}", path_str));
1598     }
1599
1600     // Foo { a: Foo } - indent is +3, width is -5.
1601     let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1602
1603     let one_line_width = h_shape.map_or(0, |shape| shape.width);
1604     let body_lo = context.snippet_provider.span_after(span, "{");
1605     let fields_str = if struct_lit_can_be_aligned(fields, &base)
1606         && context.config.struct_field_align_threshold() > 0
1607     {
1608         rewrite_with_alignment(
1609             fields,
1610             context,
1611             shape,
1612             mk_sp(body_lo, span.hi()),
1613             one_line_width,
1614         )?
1615     } else {
1616         let field_iter = fields
1617             .into_iter()
1618             .map(StructLitField::Regular)
1619             .chain(base.into_iter().map(StructLitField::Base));
1620
1621         let span_lo = |item: &StructLitField| match *item {
1622             StructLitField::Regular(field) => field.span().lo(),
1623             StructLitField::Base(expr) => {
1624                 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1625                 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1626                 let pos = snippet.find_uncommented("..").unwrap();
1627                 last_field_hi + BytePos(pos as u32)
1628             }
1629         };
1630         let span_hi = |item: &StructLitField| match *item {
1631             StructLitField::Regular(field) => field.span().hi(),
1632             StructLitField::Base(expr) => expr.span.hi(),
1633         };
1634         let rewrite = |item: &StructLitField| match *item {
1635             StructLitField::Regular(field) => {
1636                 // The 1 taken from the v_budget is for the comma.
1637                 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1638             }
1639             StructLitField::Base(expr) => {
1640                 // 2 = ..
1641                 expr.rewrite(context, v_shape.offset_left(2)?)
1642                     .map(|s| format!("..{}", s))
1643             }
1644         };
1645
1646         let items = itemize_list(
1647             context.snippet_provider,
1648             field_iter,
1649             "}",
1650             ",",
1651             span_lo,
1652             span_hi,
1653             rewrite,
1654             body_lo,
1655             span.hi(),
1656             false,
1657         );
1658         let item_vec = items.collect::<Vec<_>>();
1659
1660         let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1661         let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1662
1663         let ends_with_comma = span_ends_with_comma(context, span);
1664         let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1665
1666         let fmt = struct_lit_formatting(
1667             nested_shape,
1668             tactic,
1669             context,
1670             force_no_trailing_comma || base.is_some(),
1671         );
1672
1673         write_list(&item_vec, &fmt)?
1674     };
1675
1676     let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
1677     Some(format!("{} {{{}}}", path_str, fields_str))
1678
1679     // FIXME if context.config.indent_style() == Visual, but we run out
1680     // of space, we should fall back to BlockIndent.
1681 }
1682
1683 pub fn wrap_struct_field(
1684     context: &RewriteContext,
1685     fields_str: &str,
1686     shape: Shape,
1687     nested_shape: Shape,
1688     one_line_width: usize,
1689 ) -> String {
1690     if context.config.indent_style() == IndentStyle::Block
1691         && (fields_str.contains('\n') || !context.config.struct_lit_single_line()
1692             || fields_str.len() > one_line_width)
1693     {
1694         format!(
1695             "{}{}{}",
1696             nested_shape.indent.to_string_with_newline(context.config),
1697             fields_str,
1698             shape.indent.to_string_with_newline(context.config)
1699         )
1700     } else {
1701         // One liner or visual indent.
1702         format!(" {} ", fields_str)
1703     }
1704 }
1705
1706 pub fn struct_lit_field_separator(config: &Config) -> &str {
1707     colon_spaces(config.space_before_colon(), config.space_after_colon())
1708 }
1709
1710 pub fn rewrite_field(
1711     context: &RewriteContext,
1712     field: &ast::Field,
1713     shape: Shape,
1714     prefix_max_width: usize,
1715 ) -> Option<String> {
1716     if contains_skip(&field.attrs) {
1717         return Some(context.snippet(field.span()).to_owned());
1718     }
1719     let mut attrs_str = field.attrs.rewrite(context, shape)?;
1720     if !attrs_str.is_empty() {
1721         attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1722     };
1723     let name = &field.ident.name.to_string();
1724     if field.is_shorthand {
1725         Some(attrs_str + &name)
1726     } else {
1727         let mut separator = String::from(struct_lit_field_separator(context.config));
1728         for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
1729             separator.push(' ');
1730         }
1731         let overhead = name.len() + separator.len();
1732         let expr_shape = shape.offset_left(overhead)?;
1733         let expr = field.expr.rewrite(context, expr_shape);
1734
1735         match expr {
1736             Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1737                 Some(attrs_str + &name)
1738             }
1739             Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1740             None => {
1741                 let expr_offset = shape.indent.block_indent(context.config);
1742                 let expr = field
1743                     .expr
1744                     .rewrite(context, Shape::indented(expr_offset, context.config));
1745                 expr.map(|s| {
1746                     format!(
1747                         "{}{}:\n{}{}",
1748                         attrs_str,
1749                         name,
1750                         expr_offset.to_string(context.config),
1751                         s
1752                     )
1753                 })
1754             }
1755         }
1756     }
1757 }
1758
1759 fn rewrite_tuple_in_visual_indent_style<'a, T>(
1760     context: &RewriteContext,
1761     items: &[&T],
1762     span: Span,
1763     shape: Shape,
1764 ) -> Option<String>
1765 where
1766     T: Rewrite + Spanned + ToExpr + 'a,
1767 {
1768     let mut items = items.iter();
1769     // In case of length 1, need a trailing comma
1770     debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1771     if items.len() == 1 {
1772         // 3 = "(" + ",)"
1773         let nested_shape = shape.sub_width(3)?.visual_indent(1);
1774         return items
1775             .next()
1776             .unwrap()
1777             .rewrite(context, nested_shape)
1778             .map(|s| {
1779                 if context.config.spaces_within_parens_and_brackets() {
1780                     format!("( {}, )", s)
1781                 } else {
1782                     format!("({},)", s)
1783                 }
1784             });
1785     }
1786
1787     let list_lo = context.snippet_provider.span_after(span, "(");
1788     let nested_shape = shape.sub_width(2)?.visual_indent(1);
1789     let items = itemize_list(
1790         context.snippet_provider,
1791         items,
1792         ")",
1793         ",",
1794         |item| item.span().lo(),
1795         |item| item.span().hi(),
1796         |item| item.rewrite(context, nested_shape),
1797         list_lo,
1798         span.hi() - BytePos(1),
1799         false,
1800     );
1801     let item_vec: Vec<_> = items.collect();
1802     let tactic = definitive_tactic(
1803         &item_vec,
1804         ListTactic::HorizontalVertical,
1805         Separator::Comma,
1806         nested_shape.width,
1807     );
1808     let fmt = ListFormatting {
1809         tactic,
1810         separator: ",",
1811         trailing_separator: SeparatorTactic::Never,
1812         separator_place: SeparatorPlace::Back,
1813         shape,
1814         ends_with_newline: false,
1815         preserve_newline: false,
1816         config: context.config,
1817     };
1818     let list_str = write_list(&item_vec, &fmt)?;
1819
1820     if context.config.spaces_within_parens_and_brackets() && !list_str.is_empty() {
1821         Some(format!("( {} )", list_str))
1822     } else {
1823         Some(format!("({})", list_str))
1824     }
1825 }
1826
1827 pub fn rewrite_tuple<'a, T>(
1828     context: &RewriteContext,
1829     items: &[&T],
1830     span: Span,
1831     shape: Shape,
1832 ) -> Option<String>
1833 where
1834     T: Rewrite + Spanned + ToExpr + 'a,
1835 {
1836     debug!("rewrite_tuple {:?}", shape);
1837     if context.use_block_indent() {
1838         // We use the same rule as function calls for rewriting tuples.
1839         let force_tactic = if context.inside_macro() {
1840             if span_ends_with_comma(context, span) {
1841                 Some(SeparatorTactic::Always)
1842             } else {
1843                 Some(SeparatorTactic::Never)
1844             }
1845         } else if items.len() == 1 {
1846             Some(SeparatorTactic::Always)
1847         } else {
1848             None
1849         };
1850         overflow::rewrite_with_parens(
1851             context,
1852             "",
1853             items,
1854             shape,
1855             span,
1856             context.config.width_heuristics().fn_call_width,
1857             force_tactic,
1858         )
1859     } else {
1860         rewrite_tuple_in_visual_indent_style(context, items, span, shape)
1861     }
1862 }
1863
1864 pub fn rewrite_unary_prefix<R: Rewrite>(
1865     context: &RewriteContext,
1866     prefix: &str,
1867     rewrite: &R,
1868     shape: Shape,
1869 ) -> Option<String> {
1870     rewrite
1871         .rewrite(context, shape.offset_left(prefix.len())?)
1872         .map(|r| format!("{}{}", prefix, r))
1873 }
1874
1875 // FIXME: this is probably not correct for multi-line Rewrites. we should
1876 // subtract suffix.len() from the last line budget, not the first!
1877 pub fn rewrite_unary_suffix<R: Rewrite>(
1878     context: &RewriteContext,
1879     suffix: &str,
1880     rewrite: &R,
1881     shape: Shape,
1882 ) -> Option<String> {
1883     rewrite
1884         .rewrite(context, shape.sub_width(suffix.len())?)
1885         .map(|mut r| {
1886             r.push_str(suffix);
1887             r
1888         })
1889 }
1890
1891 fn rewrite_unary_op(
1892     context: &RewriteContext,
1893     op: &ast::UnOp,
1894     expr: &ast::Expr,
1895     shape: Shape,
1896 ) -> Option<String> {
1897     // For some reason, an UnOp is not spanned like BinOp!
1898     let operator_str = match *op {
1899         ast::UnOp::Deref => "*",
1900         ast::UnOp::Not => "!",
1901         ast::UnOp::Neg => "-",
1902     };
1903     rewrite_unary_prefix(context, operator_str, expr, shape)
1904 }
1905
1906 fn rewrite_assignment(
1907     context: &RewriteContext,
1908     lhs: &ast::Expr,
1909     rhs: &ast::Expr,
1910     op: Option<&ast::BinOp>,
1911     shape: Shape,
1912 ) -> Option<String> {
1913     let operator_str = match op {
1914         Some(op) => context.snippet(op.span),
1915         None => "=",
1916     };
1917
1918     // 1 = space between lhs and operator.
1919     let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1920     let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1921
1922     rewrite_assign_rhs(context, lhs_str, rhs, shape)
1923 }
1924
1925 /// Controls where to put the rhs.
1926 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1927 pub enum RhsTactics {
1928     /// Use heuristics.
1929     Default,
1930     /// Put the rhs on the next line if it uses multiple line.
1931     ForceNextLine,
1932 }
1933
1934 // The left hand side must contain everything up to, and including, the
1935 // assignment operator.
1936 pub fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1937     context: &RewriteContext,
1938     lhs: S,
1939     ex: &R,
1940     shape: Shape,
1941 ) -> Option<String> {
1942     rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
1943 }
1944
1945 pub fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1946     context: &RewriteContext,
1947     lhs: S,
1948     ex: &R,
1949     shape: Shape,
1950     rhs_tactics: RhsTactics,
1951 ) -> Option<String> {
1952     let lhs = lhs.into();
1953     let last_line_width = last_line_width(&lhs)
1954         .checked_sub(if lhs.contains('\n') {
1955             shape.indent.width()
1956         } else {
1957             0
1958         })
1959         .unwrap_or(0);
1960     // 1 = space between operator and rhs.
1961     let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1962         width: 0,
1963         offset: shape.offset + last_line_width + 1,
1964         ..shape
1965     });
1966     let rhs = choose_rhs(
1967         context,
1968         ex,
1969         orig_shape,
1970         ex.rewrite(context, orig_shape),
1971         rhs_tactics,
1972     )?;
1973     Some(lhs + &rhs)
1974 }
1975
1976 fn choose_rhs<R: Rewrite>(
1977     context: &RewriteContext,
1978     expr: &R,
1979     shape: Shape,
1980     orig_rhs: Option<String>,
1981     rhs_tactics: RhsTactics,
1982 ) -> Option<String> {
1983     match orig_rhs {
1984         Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
1985             Some(format!(" {}", new_str))
1986         }
1987         _ => {
1988             // Expression did not fit on the same line as the identifier.
1989             // Try splitting the line and see if that works better.
1990             let new_shape =
1991                 Shape::indented(shape.indent.block_indent(context.config), context.config)
1992                     .sub_width(shape.rhs_overhead(context.config))?;
1993             let new_rhs = expr.rewrite(context, new_shape);
1994             let new_indent_str = &new_shape.indent.to_string_with_newline(context.config);
1995
1996             match (orig_rhs, new_rhs) {
1997                 (Some(ref orig_rhs), Some(ref new_rhs))
1998                     if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
1999                         .is_none() =>
2000                 {
2001                     Some(format!(" {}", orig_rhs))
2002                 }
2003                 (Some(ref orig_rhs), Some(ref new_rhs))
2004                     if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
2005                 {
2006                     Some(format!("{}{}", new_indent_str, new_rhs))
2007                 }
2008                 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
2009                 (None, None) => None,
2010                 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2011             }
2012         }
2013     }
2014 }
2015
2016 pub fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str, rhs_tactics: RhsTactics) -> bool {
2017     rhs_tactics == RhsTactics::ForceNextLine || !next_line_rhs.contains('\n')
2018         || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2019 }
2020
2021 fn rewrite_expr_addrof(
2022     context: &RewriteContext,
2023     mutability: ast::Mutability,
2024     expr: &ast::Expr,
2025     shape: Shape,
2026 ) -> Option<String> {
2027     let operator_str = match mutability {
2028         ast::Mutability::Immutable => "&",
2029         ast::Mutability::Mutable => "&mut ",
2030     };
2031     rewrite_unary_prefix(context, operator_str, expr, shape)
2032 }
2033
2034 pub trait ToExpr {
2035     fn to_expr(&self) -> Option<&ast::Expr>;
2036     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2037 }
2038
2039 impl ToExpr for ast::Expr {
2040     fn to_expr(&self) -> Option<&ast::Expr> {
2041         Some(self)
2042     }
2043
2044     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2045         can_be_overflowed_expr(context, self, len)
2046     }
2047 }
2048
2049 impl ToExpr for ast::Ty {
2050     fn to_expr(&self) -> Option<&ast::Expr> {
2051         None
2052     }
2053
2054     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2055         can_be_overflowed_type(context, self, len)
2056     }
2057 }
2058
2059 impl<'a> ToExpr for TuplePatField<'a> {
2060     fn to_expr(&self) -> Option<&ast::Expr> {
2061         None
2062     }
2063
2064     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2065         can_be_overflowed_pat(context, self, len)
2066     }
2067 }
2068
2069 impl<'a> ToExpr for ast::StructField {
2070     fn to_expr(&self) -> Option<&ast::Expr> {
2071         None
2072     }
2073
2074     fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
2075         false
2076     }
2077 }
2078
2079 impl<'a> ToExpr for MacroArg {
2080     fn to_expr(&self) -> Option<&ast::Expr> {
2081         match *self {
2082             MacroArg::Expr(ref expr) => Some(expr),
2083             _ => None,
2084         }
2085     }
2086
2087     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2088         match *self {
2089             MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
2090             MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
2091             MacroArg::Pat(..) => false,
2092             MacroArg::Item(..) => len == 1,
2093         }
2094     }
2095 }
2096
2097 impl ToExpr for ast::GenericParam {
2098     fn to_expr(&self) -> Option<&ast::Expr> {
2099         None
2100     }
2101
2102     fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
2103         false
2104     }
2105 }