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