]> git.lizzy.rs Git - rust.git/blob - src/expr.rs
Merge pull request #1017 from marcusklaas/tweak-if-else
[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::cmp::Ordering;
12 use std::borrow::Borrow;
13 use std::mem::swap;
14 use std::ops::Deref;
15 use std::iter::ExactSizeIterator;
16 use std::fmt::Write;
17
18 use {Indent, Spanned};
19 use rewrite::{Rewrite, RewriteContext};
20 use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic,
21             DefinitiveListTactic, definitive_tactic, ListItem, format_item_list};
22 use string::{StringFormat, rewrite_string};
23 use utils::{CodeMapSpanUtils, extra_offset, last_line_width, wrap_str, binary_search,
24             first_line_width, semicolon_for_stmt, trimmed_last_line_width, left_most_sub_expr};
25 use visitor::FmtVisitor;
26 use config::{Config, StructLitStyle, MultilineStyle, ElseIfBraceStyle, ControlBraceStyle};
27 use comment::{FindUncommented, rewrite_comment, contains_comment, recover_comment_removed};
28 use types::rewrite_path;
29 use items::{span_lo_for_arg, span_hi_for_arg};
30 use chains::rewrite_chain;
31 use macros::rewrite_macro;
32
33 use syntax::{ast, ptr};
34 use syntax::codemap::{CodeMap, Span, BytePos, mk_sp};
35 use syntax::parse::classify;
36
37 impl Rewrite for ast::Expr {
38     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
39         format_expr(self, ExprType::SubExpression, context, width, offset)
40     }
41 }
42
43 #[derive(PartialEq)]
44 enum ExprType {
45     Statement,
46     SubExpression,
47 }
48
49 fn format_expr(expr: &ast::Expr,
50                expr_type: ExprType,
51                context: &RewriteContext,
52                width: usize,
53                offset: Indent)
54                -> Option<String> {
55     let result = match expr.node {
56         ast::ExprKind::Vec(ref expr_vec) => {
57             rewrite_array(expr_vec.iter().map(|e| &**e),
58                           mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi),
59                           context,
60                           width,
61                           offset)
62         }
63         ast::ExprKind::Lit(ref l) => {
64             match l.node {
65                 ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
66                     rewrite_string_lit(context, l.span, width, offset)
67                 }
68                 _ => {
69                     wrap_str(context.snippet(expr.span),
70                              context.config.max_width,
71                              width,
72                              offset)
73                 }
74             }
75         }
76         ast::ExprKind::Call(ref callee, ref args) => {
77             let inner_span = mk_sp(callee.span.hi, expr.span.hi);
78             rewrite_call(context, &**callee, args, inner_span, width, offset)
79         }
80         ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, width, offset),
81         ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
82             rewrite_binary_op(context, op, lhs, rhs, width, offset)
83         }
84         ast::ExprKind::Unary(ref op, ref subexpr) => {
85             rewrite_unary_op(context, op, subexpr, width, offset)
86         }
87         ast::ExprKind::Struct(ref path, ref fields, ref base) => {
88             rewrite_struct_lit(context,
89                                path,
90                                fields,
91                                base.as_ref().map(|e| &**e),
92                                expr.span,
93                                width,
94                                offset)
95         }
96         ast::ExprKind::Tup(ref items) => {
97             rewrite_tuple(context,
98                           items.iter().map(|x| &**x),
99                           expr.span,
100                           width,
101                           offset)
102         }
103         ast::ExprKind::While(ref cond, ref block, label) => {
104             Loop::new_while(None, cond, block, label).rewrite(context, width, offset)
105         }
106         ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => {
107             Loop::new_while(Some(pat), cond, block, label).rewrite(context, width, offset)
108         }
109         ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
110             Loop::new_for(pat, cond, block, label).rewrite(context, width, offset)
111         }
112         ast::ExprKind::Loop(ref block, label) => {
113             Loop::new_loop(block, label).rewrite(context, width, offset)
114         }
115         ast::ExprKind::Block(ref block) => block.rewrite(context, width, offset),
116         ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
117             rewrite_if_else(context,
118                             cond,
119                             expr_type,
120                             if_block,
121                             else_block.as_ref().map(|e| &**e),
122                             expr.span,
123                             None,
124                             width,
125                             offset,
126                             true)
127         }
128         ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
129             rewrite_if_else(context,
130                             cond,
131                             expr_type,
132                             if_block,
133                             else_block.as_ref().map(|e| &**e),
134                             expr.span,
135                             Some(pat),
136                             width,
137                             offset,
138                             true)
139         }
140         ast::ExprKind::Match(ref cond, ref arms) => {
141             rewrite_match(context, cond, arms, width, offset, expr.span)
142         }
143         ast::ExprKind::Path(ref qself, ref path) => {
144             rewrite_path(context, true, qself.as_ref(), path, width, offset)
145         }
146         ast::ExprKind::Assign(ref lhs, ref rhs) => {
147             rewrite_assignment(context, lhs, rhs, None, width, offset)
148         }
149         ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
150             rewrite_assignment(context, lhs, rhs, Some(op), width, offset)
151         }
152         ast::ExprKind::Again(ref opt_ident) => {
153             let id_str = match *opt_ident {
154                 Some(ident) => format!(" {}", ident.node),
155                 None => String::new(),
156             };
157             wrap_str(format!("continue{}", id_str),
158                      context.config.max_width,
159                      width,
160                      offset)
161         }
162         ast::ExprKind::Break(ref opt_ident) => {
163             let id_str = match *opt_ident {
164                 Some(ident) => format!(" {}", ident.node),
165                 None => String::new(),
166             };
167             wrap_str(format!("break{}", id_str),
168                      context.config.max_width,
169                      width,
170                      offset)
171         }
172         ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
173             rewrite_closure(capture, fn_decl, body, expr.span, context, width, offset)
174         }
175         ast::ExprKind::Try(..) |
176         ast::ExprKind::Field(..) |
177         ast::ExprKind::TupField(..) |
178         ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, width, offset),
179         ast::ExprKind::Mac(ref mac) => {
180             // Failure to rewrite a marco should not imply failure to
181             // rewrite the expression.
182             rewrite_macro(mac, None, context, width, offset).or_else(|| {
183                 wrap_str(context.snippet(expr.span),
184                          context.config.max_width,
185                          width,
186                          offset)
187             })
188         }
189         ast::ExprKind::Ret(None) => {
190             wrap_str("return".to_owned(), context.config.max_width, width, offset)
191         }
192         ast::ExprKind::Ret(Some(ref expr)) => {
193             rewrite_unary_prefix(context, "return ", &**expr, width, offset)
194         }
195         ast::ExprKind::Box(ref expr) => {
196             rewrite_unary_prefix(context, "box ", &**expr, width, offset)
197         }
198         ast::ExprKind::AddrOf(mutability, ref expr) => {
199             rewrite_expr_addrof(context, mutability, expr, width, offset)
200         }
201         ast::ExprKind::Cast(ref expr, ref ty) => {
202             rewrite_pair(&**expr, &**ty, "", " as ", "", context, width, offset)
203         }
204         ast::ExprKind::Type(ref expr, ref ty) => {
205             rewrite_pair(&**expr, &**ty, "", ": ", "", context, width, offset)
206         }
207         ast::ExprKind::Index(ref expr, ref index) => {
208             rewrite_pair(&**expr, &**index, "", "[", "]", context, width, offset)
209         }
210         ast::ExprKind::Repeat(ref expr, ref repeats) => {
211             rewrite_pair(&**expr, &**repeats, "[", "; ", "]", context, width, offset)
212         }
213         ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
214             let delim = match limits {
215                 ast::RangeLimits::HalfOpen => "..",
216                 ast::RangeLimits::Closed => "...",
217             };
218
219             match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
220                 (Some(ref lhs), Some(ref rhs)) => {
221                     rewrite_pair(&**lhs, &**rhs, "", delim, "", context, width, offset)
222                 }
223                 (None, Some(ref rhs)) => {
224                     rewrite_unary_prefix(context, delim, &**rhs, width, offset)
225                 }
226                 (Some(ref lhs), None) => {
227                     rewrite_unary_suffix(context, delim, &**lhs, width, offset)
228                 }
229                 (None, None) => wrap_str(delim.into(), context.config.max_width, width, offset),
230             }
231         }
232         // We do not format these expressions yet, but they should still
233         // satisfy our width restrictions.
234         ast::ExprKind::InPlace(..) |
235         ast::ExprKind::InlineAsm(..) => {
236             wrap_str(context.snippet(expr.span),
237                      context.config.max_width,
238                      width,
239                      offset)
240         }
241     };
242     result.and_then(|res| recover_comment_removed(res, expr.span, context, width, offset))
243 }
244
245 pub fn rewrite_pair<LHS, RHS>(lhs: &LHS,
246                               rhs: &RHS,
247                               prefix: &str,
248                               infix: &str,
249                               suffix: &str,
250                               context: &RewriteContext,
251                               width: usize,
252                               offset: Indent)
253                               -> Option<String>
254     where LHS: Rewrite,
255           RHS: Rewrite
256 {
257     let max_width = try_opt!(width.checked_sub(prefix.len() + infix.len() + suffix.len()));
258
259     binary_search(1, max_width, |lhs_budget| {
260         let lhs_offset = offset + prefix.len();
261         let lhs_str = match lhs.rewrite(context, lhs_budget, lhs_offset) {
262             Some(result) => result,
263             None => return Err(Ordering::Greater),
264         };
265
266         let last_line_width = last_line_width(&lhs_str);
267         let rhs_budget = match max_width.checked_sub(last_line_width) {
268             Some(b) => b,
269             None => return Err(Ordering::Less),
270         };
271         let rhs_indent = offset + last_line_width + prefix.len() + infix.len();
272
273         let rhs_str = match rhs.rewrite(context, rhs_budget, rhs_indent) {
274             Some(result) => result,
275             None => return Err(Ordering::Less),
276         };
277
278         Ok(format!("{}{}{}{}{}", prefix, lhs_str, infix, rhs_str, suffix))
279     })
280 }
281
282 pub fn rewrite_array<'a, I>(expr_iter: I,
283                             span: Span,
284                             context: &RewriteContext,
285                             width: usize,
286                             offset: Indent)
287                             -> Option<String>
288     where I: Iterator<Item = &'a ast::Expr>
289 {
290     // 2 for brackets;
291     let offset = offset + 1;
292     let inner_context = &RewriteContext { block_indent: offset, ..*context };
293     let max_item_width = try_opt!(width.checked_sub(2));
294     let items = itemize_list(context.codemap,
295                              expr_iter,
296                              "]",
297                              |item| item.span.lo,
298                              |item| item.span.hi,
299                              // 1 = [
300                              |item| item.rewrite(&inner_context, max_item_width, offset),
301                              span.lo,
302                              span.hi)
303         .collect::<Vec<_>>();
304
305     let has_long_item = try_opt!(items.iter()
306         .map(|li| li.item.as_ref().map(|s| s.len() > 10))
307         .fold(Some(false), |acc, x| acc.and_then(|y| x.map(|x| x || y))));
308
309     let tactic = if has_long_item || items.iter().any(ListItem::is_multiline) {
310         definitive_tactic(&items, ListTactic::HorizontalVertical, max_item_width)
311     } else {
312         DefinitiveListTactic::Mixed
313     };
314
315     let fmt = ListFormatting {
316         tactic: tactic,
317         separator: ",",
318         trailing_separator: SeparatorTactic::Never,
319         indent: offset,
320         width: max_item_width,
321         ends_with_newline: false,
322         config: context.config,
323     };
324     let list_str = try_opt!(write_list(&items, &fmt));
325
326     Some(format!("[{}]", list_str))
327 }
328
329 // This functions is pretty messy because of the rules around closures and blocks:
330 //   * the body of a closure is represented by an ast::Block, but that does not
331 //     imply there are `{}` (unless the block is empty) (see rust issue #27872),
332 //   * if there is a return type, then there must be braces,
333 //   * given a closure with braces, whether that is parsed to give an inner block
334 //     or not depends on if there is a return type and if there are statements
335 //     in that block,
336 //   * if the first expression in the body ends with a block (i.e., is a
337 //     statement without needing a semi-colon), then adding or removing braces
338 //     can change whether it is treated as an expression or statement.
339 fn rewrite_closure(capture: ast::CaptureBy,
340                    fn_decl: &ast::FnDecl,
341                    body: &ast::Block,
342                    span: Span,
343                    context: &RewriteContext,
344                    width: usize,
345                    offset: Indent)
346                    -> Option<String> {
347     let mover = if capture == ast::CaptureBy::Value {
348         "move "
349     } else {
350         ""
351     };
352     let offset = offset + mover.len();
353
354     // 4 = "|| {".len(), which is overconservative when the closure consists of
355     // a single expression.
356     let budget = try_opt!(width.checked_sub(4 + mover.len()));
357     // 1 = |
358     let argument_offset = offset + 1;
359     let ret_str = try_opt!(fn_decl.output.rewrite(context, budget, argument_offset));
360     let force_block = !ret_str.is_empty();
361
362     // 1 = space between arguments and return type.
363     let horizontal_budget = budget.checked_sub(ret_str.len() + 1).unwrap_or(0);
364
365     let arg_items = itemize_list(context.codemap,
366                                  fn_decl.inputs.iter(),
367                                  "|",
368                                  |arg| span_lo_for_arg(arg),
369                                  |arg| span_hi_for_arg(arg),
370                                  |arg| arg.rewrite(context, budget, argument_offset),
371                                  context.codemap.span_after(span, "|"),
372                                  body.span.lo);
373     let item_vec = arg_items.collect::<Vec<_>>();
374     let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
375     let budget = match tactic {
376         DefinitiveListTactic::Horizontal => horizontal_budget,
377         _ => budget,
378     };
379
380     let fmt = ListFormatting {
381         tactic: tactic,
382         separator: ",",
383         trailing_separator: SeparatorTactic::Never,
384         indent: argument_offset,
385         width: budget,
386         ends_with_newline: false,
387         config: context.config,
388     };
389     let list_str = try_opt!(write_list(&item_vec, &fmt));
390     let mut prefix = format!("{}|{}|", mover, list_str);
391
392     if !ret_str.is_empty() {
393         if prefix.contains('\n') {
394             prefix.push('\n');
395             prefix.push_str(&argument_offset.to_string(context.config));
396         } else {
397             prefix.push(' ');
398         }
399         prefix.push_str(&ret_str);
400     }
401
402     if body.expr.is_none() && body.stmts.is_empty() {
403         return Some(format!("{} {{}}", prefix));
404     }
405
406     // 1 = space between `|...|` and body.
407     let extra_offset = extra_offset(&prefix, offset) + 1;
408     let budget = try_opt!(width.checked_sub(extra_offset));
409
410     // This is where we figure out whether to use braces or not.
411     let mut had_braces = true;
412     let mut inner_block = body;
413
414     // If there is an inner block and we can ignore it, do so.
415     if body.stmts.is_empty() {
416         if let ast::ExprKind::Block(ref inner) = inner_block.expr.as_ref().unwrap().node {
417             inner_block = inner;
418         } else if !force_block {
419             had_braces = false;
420         }
421     }
422
423     let try_single_line = is_simple_block(inner_block, context.codemap) &&
424                           inner_block.rules == ast::BlockCheckMode::Default;
425
426     if try_single_line && !force_block {
427         let must_preserve_braces =
428             !classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(inner_block.expr
429                 .as_ref()
430                 .unwrap()));
431         if !(must_preserve_braces && had_braces) &&
432            (must_preserve_braces || !prefix.contains('\n')) {
433             // If we got here, then we can try to format without braces.
434
435             let inner_expr = inner_block.expr.as_ref().unwrap();
436             let mut rewrite = inner_expr.rewrite(context, budget, offset + extra_offset);
437
438             if must_preserve_braces {
439                 // If we are here, then failure to rewrite is unacceptable.
440                 if rewrite.is_none() {
441                     return None;
442                 }
443             } else {
444                 // Checks if rewrite succeeded and fits on a single line.
445                 rewrite = and_one_line(rewrite);
446             }
447
448             if let Some(rewrite) = rewrite {
449                 return Some(format!("{} {}", prefix, rewrite));
450             }
451         }
452     }
453
454     // If we fell through the above block, then we need braces, but we might
455     // still prefer a one-liner (we might also have fallen through because of
456     // lack of space).
457     if try_single_line && !prefix.contains('\n') {
458         let inner_expr = inner_block.expr.as_ref().unwrap();
459         // 4 = braces and spaces.
460         let mut rewrite = inner_expr.rewrite(context,
461                                              try_opt!(budget.checked_sub(4)),
462                                              offset + extra_offset);
463
464         // Checks if rewrite succeeded and fits on a single line.
465         rewrite = and_one_line(rewrite);
466
467         if let Some(rewrite) = rewrite {
468             return Some(format!("{} {{ {} }}", prefix, rewrite));
469         }
470     }
471
472     // We couldn't format the closure body as a single line expression; fall
473     // back to block formatting.
474     let body_rewrite = try_opt!(inner_block.rewrite(&context, budget, Indent::empty()));
475
476     let block_threshold = context.config.closure_block_indent_threshold;
477     if block_threshold < 0 || body_rewrite.matches('\n').count() <= block_threshold as usize {
478         return Some(format!("{} {}", prefix, body_rewrite));
479     }
480
481     // The body of the closure is big enough to be block indented, that means we
482     // must re-format.
483     let mut context = context.clone();
484     context.block_indent.alignment = 0;
485     let body_rewrite = try_opt!(inner_block.rewrite(&context, budget, Indent::empty()));
486     Some(format!("{} {}", prefix, body_rewrite))
487 }
488
489 fn and_one_line(x: Option<String>) -> Option<String> {
490     x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
491 }
492
493 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
494     block_str.map(|block_str| {
495         if block_str.starts_with("{") && budget >= 2 &&
496            (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2) {
497             "{}".to_owned()
498         } else {
499             block_str.to_owned()
500         }
501     })
502 }
503
504 impl Rewrite for ast::Block {
505     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
506         let user_str = context.snippet(self.span);
507         if user_str == "{}" && width >= 2 {
508             return Some(user_str);
509         }
510
511         let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
512         visitor.block_indent = context.block_indent;
513
514         let prefix = match self.rules {
515             ast::BlockCheckMode::Unsafe(..) => {
516                 let snippet = context.snippet(self.span);
517                 let open_pos = try_opt!(snippet.find_uncommented("{"));
518                 visitor.last_pos = self.span.lo + BytePos(open_pos as u32);
519
520                 // Extract comment between unsafe and block start.
521                 let trimmed = &snippet[6..open_pos].trim();
522
523                 let prefix = if !trimmed.is_empty() {
524                     // 9 = "unsafe  {".len(), 7 = "unsafe ".len()
525                     let budget = try_opt!(width.checked_sub(9));
526                     format!("unsafe {} ",
527                             try_opt!(rewrite_comment(trimmed,
528                                                      true,
529                                                      budget,
530                                                      offset + 7,
531                                                      context.config)))
532                 } else {
533                     "unsafe ".to_owned()
534                 };
535
536                 if is_simple_block(self, context.codemap) && prefix.len() < width {
537                     let body = self.expr
538                         .as_ref()
539                         .unwrap()
540                         .rewrite(context, width - prefix.len(), offset);
541                     if let Some(ref expr_str) = body {
542                         let result = format!("{}{{ {} }}", prefix, expr_str);
543                         if result.len() <= width && !result.contains('\n') {
544                             return Some(result);
545                         }
546                     }
547                 }
548
549                 prefix
550             }
551             ast::BlockCheckMode::Default => {
552                 visitor.last_pos = self.span.lo;
553
554                 String::new()
555             }
556         };
557
558         visitor.visit_block(self);
559
560         Some(format!("{}{}", prefix, visitor.buffer))
561     }
562 }
563
564 impl Rewrite for ast::Stmt {
565     fn rewrite(&self, context: &RewriteContext, _width: usize, offset: Indent) -> Option<String> {
566         let result = match self.node {
567             ast::StmtKind::Decl(ref decl, _) => {
568                 if let ast::DeclKind::Local(ref local) = decl.node {
569                     local.rewrite(context, context.config.max_width, offset)
570                 } else {
571                     None
572                 }
573             }
574             ast::StmtKind::Expr(ref ex, _) |
575             ast::StmtKind::Semi(ref ex, _) => {
576                 let suffix = if semicolon_for_stmt(self) { ";" } else { "" };
577
578                 format_expr(ex,
579                             ExprType::Statement,
580                             context,
581                             context.config.max_width - offset.width() - suffix.len(),
582                             offset)
583                     .map(|s| s + suffix)
584             }
585             ast::StmtKind::Mac(..) => None,
586         };
587         result.and_then(|res| recover_comment_removed(res, self.span, context, _width, offset))
588     }
589 }
590
591 // Abstraction over for, while and loop expressions
592 struct Loop<'a> {
593     cond: Option<&'a ast::Expr>,
594     block: &'a ast::Block,
595     label: Option<ast::SpannedIdent>,
596     pat: Option<&'a ast::Pat>,
597     keyword: &'a str,
598     matcher: &'a str,
599     connector: &'a str,
600 }
601
602 impl<'a> Loop<'a> {
603     fn new_loop(block: &'a ast::Block, label: Option<ast::SpannedIdent>) -> Loop<'a> {
604         Loop {
605             cond: None,
606             block: block,
607             label: label,
608             pat: None,
609             keyword: "loop",
610             matcher: "",
611             connector: "",
612         }
613     }
614
615     fn new_while(pat: Option<&'a ast::Pat>,
616                  cond: &'a ast::Expr,
617                  block: &'a ast::Block,
618                  label: Option<ast::SpannedIdent>)
619                  -> Loop<'a> {
620         Loop {
621             cond: Some(cond),
622             block: block,
623             label: label,
624             pat: pat,
625             keyword: "while ",
626             matcher: match pat {
627                 Some(..) => "let ",
628                 None => "",
629             },
630             connector: " =",
631         }
632     }
633
634     fn new_for(pat: &'a ast::Pat,
635                cond: &'a ast::Expr,
636                block: &'a ast::Block,
637                label: Option<ast::SpannedIdent>)
638                -> Loop<'a> {
639         Loop {
640             cond: Some(cond),
641             block: block,
642             label: label,
643             pat: Some(pat),
644             keyword: "for ",
645             matcher: "",
646             connector: " in",
647         }
648     }
649 }
650
651 impl<'a> Rewrite for Loop<'a> {
652     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
653         let label_string = rewrite_label(self.label);
654         // 2 = " {".len()
655         let inner_width = try_opt!(width.checked_sub(self.keyword.len() + 2 + label_string.len()));
656         let inner_offset = offset + self.keyword.len() + label_string.len();
657
658         let pat_expr_string = match self.cond {
659             Some(cond) => {
660                 try_opt!(rewrite_pat_expr(context,
661                                           self.pat,
662                                           cond,
663                                           self.matcher,
664                                           self.connector,
665                                           inner_width,
666                                           inner_offset))
667             }
668             None => String::new(),
669         };
670
671         let alt_block_sep = String::from("\n") + &context.block_indent.to_string(context.config);
672         let block_sep = match context.config.control_brace_style {
673             ControlBraceStyle::AlwaysNextLine => alt_block_sep.as_str(),
674             ControlBraceStyle::AlwaysSameLine => " ",
675         };
676         // FIXME: this drops any comment between "loop" and the block.
677         self.block
678             .rewrite(context, width, offset)
679             .map(|result| {
680                 format!("{}{}{}{}{}",
681                         label_string,
682                         self.keyword,
683                         pat_expr_string,
684                         block_sep,
685                         result)
686             })
687     }
688 }
689
690 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
691     match label {
692         Some(ident) => format!("{}: ", ident.node),
693         None => "".to_owned(),
694     }
695 }
696
697 fn extract_comment(span: Span,
698                    context: &RewriteContext,
699                    offset: Indent,
700                    width: usize)
701                    -> Option<String> {
702     let comment_str = context.snippet(span);
703     if contains_comment(&comment_str) {
704         let comment =
705             try_opt!(rewrite_comment(comment_str.trim(), false, width, offset, context.config));
706         Some(format!("\n{indent}{}\n{indent}",
707                      comment,
708                      indent = offset.to_string(context.config)))
709     } else {
710         None
711     }
712 }
713
714 // Rewrites if-else blocks. If let Some(_) = pat, the expression is
715 // treated as an if-let-else expression.
716 fn rewrite_if_else(context: &RewriteContext,
717                    cond: &ast::Expr,
718                    expr_type: ExprType,
719                    if_block: &ast::Block,
720                    else_block_opt: Option<&ast::Expr>,
721                    span: Span,
722                    pat: Option<&ast::Pat>,
723                    width: usize,
724                    offset: Indent,
725                    allow_single_line: bool)
726                    -> Option<String> {
727     // 3 = "if ", 2 = " {"
728     let pat_penalty = match context.config.else_if_brace_style {
729         ElseIfBraceStyle::AlwaysNextLine => 3,
730         _ => 3 + 2,
731     };
732     let pat_expr_string = try_opt!(rewrite_pat_expr(context,
733                                                     pat,
734                                                     cond,
735                                                     "let ",
736                                                     " =",
737                                                     try_opt!(width.checked_sub(pat_penalty)),
738                                                     offset + 3));
739
740     // Try to format if-else on single line.
741     if expr_type == ExprType::SubExpression && allow_single_line &&
742        context.config.single_line_if_else_max_width > 0 {
743         let trial = single_line_if_else(context, &pat_expr_string, if_block, else_block_opt, width);
744
745         if trial.is_some() &&
746            trial.as_ref().unwrap().len() <= context.config.single_line_if_else_max_width {
747             return trial;
748         }
749     }
750
751     let if_block_string = try_opt!(if_block.rewrite(context, width, offset));
752
753     let between_if_cond = mk_sp(context.codemap.span_after(span, "if"),
754                                 pat.map_or(cond.span.lo,
755                                            |_| context.codemap.span_before(span, "let")));
756
757     let between_if_cond_comment = extract_comment(between_if_cond, &context, offset, width);
758
759     let after_cond_comment = extract_comment(mk_sp(cond.span.hi, if_block.span.lo),
760                                              context,
761                                              offset,
762                                              width);
763
764     let alt_block_sep = String::from("\n") + &context.block_indent.to_string(context.config);
765     let after_sep = match context.config.else_if_brace_style {
766         ElseIfBraceStyle::AlwaysNextLine => alt_block_sep.as_str(),
767         _ => " ",
768     };
769     let mut result = format!("if{}{}{}{}",
770                              between_if_cond_comment.as_ref().map_or(" ", |str| &**str),
771                              pat_expr_string,
772                              after_cond_comment.as_ref().map_or(after_sep, |str| &**str),
773                              if_block_string);
774
775     if let Some(else_block) = else_block_opt {
776         let mut last_in_chain = false;
777         let rewrite = match else_block.node {
778             // If the else expression is another if-else expression, prevent it
779             // from being formatted on a single line.
780             ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
781                 rewrite_if_else(context,
782                                 cond,
783                                 expr_type,
784                                 if_block,
785                                 next_else_block.as_ref().map(|e| &**e),
786                                 mk_sp(else_block.span.lo, span.hi),
787                                 Some(pat),
788                                 width,
789                                 offset,
790                                 false)
791             }
792             ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
793                 rewrite_if_else(context,
794                                 cond,
795                                 expr_type,
796                                 if_block,
797                                 next_else_block.as_ref().map(|e| &**e),
798                                 mk_sp(else_block.span.lo, span.hi),
799                                 None,
800                                 width,
801                                 offset,
802                                 false)
803             }
804             _ => {
805                 last_in_chain = true;
806                 else_block.rewrite(context, width, offset)
807             }
808         };
809
810         let between_if_else_block =
811             mk_sp(if_block.span.hi,
812                   context.codemap.span_before(mk_sp(if_block.span.hi, else_block.span.lo), "else"));
813         let between_if_else_block_comment =
814             extract_comment(between_if_else_block, &context, offset, width);
815
816         let after_else = mk_sp(context.codemap
817                                    .span_after(mk_sp(if_block.span.hi, else_block.span.lo),
818                                                "else"),
819                                else_block.span.lo);
820         let after_else_comment = extract_comment(after_else, &context, offset, width);
821
822         let between_sep = match context.config.else_if_brace_style {
823             ElseIfBraceStyle::AlwaysNextLine |
824             ElseIfBraceStyle::ClosingNextLine => alt_block_sep.as_str(),
825             ElseIfBraceStyle::AlwaysSameLine => " ",
826         };
827         let after_sep = match context.config.else_if_brace_style {
828             ElseIfBraceStyle::AlwaysNextLine if last_in_chain => alt_block_sep.as_str(),
829             _ => " ",
830         };
831         try_opt!(write!(&mut result,
832                         "{}else{}",
833                         between_if_else_block_comment.as_ref()
834                             .map_or(between_sep, |str| &**str),
835                         after_else_comment.as_ref().map_or(after_sep, |str| &**str))
836             .ok());
837         result.push_str(&&try_opt!(rewrite));
838     }
839
840     Some(result)
841 }
842
843 fn single_line_if_else(context: &RewriteContext,
844                        pat_expr_str: &str,
845                        if_node: &ast::Block,
846                        else_block_opt: Option<&ast::Expr>,
847                        width: usize)
848                        -> Option<String> {
849     let else_block = try_opt!(else_block_opt);
850     let fixed_cost = "if  {  } else {  }".len();
851
852     if let ast::ExprKind::Block(ref else_node) = else_block.node {
853         if !is_simple_block(if_node, context.codemap) ||
854            !is_simple_block(else_node, context.codemap) || pat_expr_str.contains('\n') {
855             return None;
856         }
857
858         let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
859         let if_expr = if_node.expr.as_ref().unwrap();
860         let if_str = try_opt!(if_expr.rewrite(context, new_width, Indent::empty()));
861
862         let new_width = try_opt!(new_width.checked_sub(if_str.len()));
863         let else_expr = else_node.expr.as_ref().unwrap();
864         let else_str = try_opt!(else_expr.rewrite(context, new_width, Indent::empty()));
865
866         // FIXME: this check shouldn't be necessary. Rewrites should either fail
867         // or wrap to a newline when the object does not fit the width.
868         let fits_line = fixed_cost + pat_expr_str.len() + if_str.len() + else_str.len() <= width;
869
870         if fits_line && !if_str.contains('\n') && !else_str.contains('\n') {
871             return Some(format!("if {} {{ {} }} else {{ {} }}",
872                                 pat_expr_str,
873                                 if_str,
874                                 else_str));
875         }
876     }
877
878     None
879 }
880
881 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
882     let snippet = codemap.span_to_snippet(block.span).unwrap();
883     contains_comment(&snippet)
884 }
885
886 // Checks that a block contains no statements, an expression and no comments.
887 // FIXME: incorrectly returns false when comment is contained completely within
888 // the expression.
889 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
890     block.stmts.is_empty() && block.expr.is_some() && !block_contains_comment(block, codemap)
891 }
892
893 /// Checks whether a block contains at most one statement or expression, and no comments.
894 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
895     (block.stmts.is_empty() || (block.stmts.len() == 1 && block.expr.is_none())) &&
896     !block_contains_comment(block, codemap)
897 }
898
899 /// Checks whether a block contains no statements, expressions, or comments.
900 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
901     block.stmts.is_empty() && block.expr.is_none() && !block_contains_comment(block, codemap)
902 }
903
904 fn is_unsafe_block(block: &ast::Block) -> bool {
905     if let ast::BlockCheckMode::Unsafe(..) = block.rules {
906         true
907     } else {
908         false
909     }
910 }
911
912 // inter-match-arm-comment-rules:
913 //  - all comments following a match arm before the start of the next arm
914 //    are about the second arm
915 fn rewrite_match_arm_comment(context: &RewriteContext,
916                              missed_str: &str,
917                              width: usize,
918                              arm_indent: Indent,
919                              arm_indent_str: &str)
920                              -> Option<String> {
921     // The leading "," is not part of the arm-comment
922     let missed_str = match missed_str.find_uncommented(",") {
923         Some(n) => &missed_str[n + 1..],
924         None => &missed_str[..],
925     };
926
927     let mut result = String::new();
928     // any text not preceeded by a newline is pushed unmodified to the block
929     let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
930     result.push_str(&missed_str[..first_brk]);
931     let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
932
933     let first = missed_str.find(|c: char| !c.is_whitespace()).unwrap_or(missed_str.len());
934     if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
935         // Excessive vertical whitespace before comment should be preserved
936         // TODO handle vertical whitespace better
937         result.push('\n');
938     }
939     let missed_str = missed_str[first..].trim();
940     if !missed_str.is_empty() {
941         let comment =
942             try_opt!(rewrite_comment(&missed_str, false, width, arm_indent, context.config));
943         result.push('\n');
944         result.push_str(arm_indent_str);
945         result.push_str(&comment);
946     }
947
948     Some(result)
949 }
950
951 fn rewrite_match(context: &RewriteContext,
952                  cond: &ast::Expr,
953                  arms: &[ast::Arm],
954                  width: usize,
955                  offset: Indent,
956                  span: Span)
957                  -> Option<String> {
958     if arms.is_empty() {
959         return None;
960     }
961
962     // `match `cond` {`
963     let cond_budget = try_opt!(width.checked_sub(8));
964     let cond_str = try_opt!(cond.rewrite(context, cond_budget, offset + 6));
965     let alt_block_sep = String::from("\n") + &context.block_indent.to_string(context.config);
966     let block_sep = match context.config.control_brace_style {
967         ControlBraceStyle::AlwaysSameLine => " ",
968         ControlBraceStyle::AlwaysNextLine => alt_block_sep.as_str(),
969     };
970     let mut result = format!("match {}{}{{", cond_str, block_sep);
971
972     let nested_context = context.nested_context();
973     let arm_indent = nested_context.block_indent;
974     let arm_indent_str = arm_indent.to_string(context.config);
975
976     let open_brace_pos = context.codemap
977         .span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])), "{");
978
979     for (i, arm) in arms.iter().enumerate() {
980         // Make sure we get the stuff between arms.
981         let missed_str = if i == 0 {
982             context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
983         } else {
984             context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
985         };
986         let comment = try_opt!(rewrite_match_arm_comment(context,
987                                                          &missed_str,
988                                                          width,
989                                                          arm_indent,
990                                                          &arm_indent_str));
991         result.push_str(&comment);
992         result.push('\n');
993         result.push_str(&arm_indent_str);
994
995         let arm_str = arm.rewrite(&nested_context,
996                                   context.config.max_width - arm_indent.width(),
997                                   arm_indent);
998         if let Some(ref arm_str) = arm_str {
999             result.push_str(arm_str);
1000         } else {
1001             // We couldn't format the arm, just reproduce the source.
1002             let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
1003             result.push_str(&snippet);
1004             result.push_str(arm_comma(&context.config, &arm, &arm.body));
1005         }
1006     }
1007     // BytePos(1) = closing match brace.
1008     let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
1009     let last_comment = context.snippet(last_span);
1010     let comment = try_opt!(rewrite_match_arm_comment(context,
1011                                                      &last_comment,
1012                                                      width,
1013                                                      arm_indent,
1014                                                      &arm_indent_str));
1015     result.push_str(&comment);
1016     result.push('\n');
1017     result.push_str(&context.block_indent.to_string(context.config));
1018     result.push('}');
1019     Some(result)
1020 }
1021
1022 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
1023     let &ast::Arm { ref attrs, ref pats, .. } = arm;
1024     if !attrs.is_empty() {
1025         return attrs[0].span.lo;
1026     }
1027
1028     pats[0].span.lo
1029 }
1030
1031 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
1032     arm.body.span.hi
1033 }
1034
1035 fn arm_comma(config: &Config, arm: &ast::Arm, body: &ast::Expr) -> &'static str {
1036     if !config.match_wildcard_trailing_comma {
1037         if arm.pats.len() == 1 && arm.pats[0].node == ast::PatKind::Wild && arm.guard.is_none() {
1038             return "";
1039         }
1040     }
1041
1042     if config.match_block_trailing_comma {
1043         ","
1044     } else if let ast::ExprKind::Block(ref block) = body.node {
1045         if let ast::BlockCheckMode::Default = block.rules {
1046             ""
1047         } else {
1048             ","
1049         }
1050     } else {
1051         ","
1052     }
1053 }
1054
1055 // Match arms.
1056 impl Rewrite for ast::Arm {
1057     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1058         let &ast::Arm { ref attrs, ref pats, ref guard, ref body } = self;
1059
1060         // FIXME this is all a bit grotty, would be nice to abstract out the
1061         // treatment of attributes.
1062         let attr_str = if !attrs.is_empty() {
1063             // We only use this visitor for the attributes, should we use it for
1064             // more?
1065             let mut attr_visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1066             attr_visitor.block_indent = context.block_indent;
1067             attr_visitor.last_pos = attrs[0].span.lo;
1068             if attr_visitor.visit_attrs(attrs) {
1069                 // Attributes included a skip instruction.
1070                 return None;
1071             }
1072             attr_visitor.format_missing(pats[0].span.lo);
1073             attr_visitor.buffer.to_string()
1074         } else {
1075             String::new()
1076         };
1077
1078         // Patterns
1079         // 5 = ` => {`
1080         let pat_budget = try_opt!(width.checked_sub(5));
1081         let pat_strs = try_opt!(pats.iter()
1082             .map(|p| p.rewrite(context, pat_budget, offset))
1083             .collect::<Option<Vec<_>>>());
1084
1085         let all_simple = pat_strs.iter().all(|p| pat_is_simple(&p));
1086         let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1087         let fmt = ListFormatting {
1088             tactic: if all_simple {
1089                 DefinitiveListTactic::Mixed
1090             } else {
1091                 DefinitiveListTactic::Vertical
1092             },
1093             separator: " |",
1094             trailing_separator: SeparatorTactic::Never,
1095             indent: offset,
1096             width: pat_budget,
1097             ends_with_newline: false,
1098             config: context.config,
1099         };
1100         let pats_str = try_opt!(write_list(items, &fmt));
1101
1102         let budget = if pats_str.contains('\n') {
1103             context.config.max_width - offset.width()
1104         } else {
1105             width
1106         };
1107
1108         let guard_str = try_opt!(rewrite_guard(context,
1109                                                guard,
1110                                                budget,
1111                                                offset,
1112                                                trimmed_last_line_width(&pats_str)));
1113
1114         let pats_str = format!("{}{}", pats_str, guard_str);
1115         // Where the next text can start.
1116         let mut line_start = last_line_width(&pats_str);
1117         if !pats_str.contains('\n') {
1118             line_start += offset.width();
1119         }
1120
1121         let body = match **body {
1122             ast::Expr { node: ast::ExprKind::Block(ref block), .. }
1123                 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) &&
1124                    context.config.wrap_match_arms => block.expr.as_ref().map(|e| &**e).unwrap(),
1125             ref x => x,
1126         };
1127
1128         let comma = arm_comma(&context.config, self, body);
1129         let alt_block_sep = String::from("\n") + &context.block_indent.to_string(context.config);
1130
1131         // Let's try and get the arm body on the same line as the condition.
1132         // 4 = ` => `.len()
1133         if context.config.max_width > line_start + comma.len() + 4 {
1134             let budget = context.config.max_width - line_start - comma.len() - 4;
1135             let offset = Indent::new(offset.block_indent, line_start + 4 - offset.block_indent);
1136             let rewrite = nop_block_collapse(body.rewrite(context, budget, offset), budget);
1137             let is_block = if let ast::ExprKind::Block(..) = body.node {
1138                 true
1139             } else {
1140                 false
1141             };
1142
1143             let block_sep = match context.config.control_brace_style {
1144                 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep.as_str(),
1145                 _ => " ",
1146             };
1147             match rewrite {
1148                 Some(ref body_str) if !body_str.contains('\n') || !context.config.wrap_match_arms ||
1149                                       is_block => {
1150                     return Some(format!("{}{} =>{}{}{}",
1151                                         attr_str.trim_left(),
1152                                         pats_str,
1153                                         block_sep,
1154                                         body_str,
1155                                         comma));
1156                 }
1157                 _ => {}
1158             }
1159         }
1160
1161         // FIXME: we're doing a second rewrite of the expr; This may not be
1162         // necessary.
1163         let body_budget = try_opt!(width.checked_sub(context.config.tab_spaces));
1164         let indent = context.block_indent.block_indent(context.config);
1165         let inner_context = &RewriteContext { block_indent: indent, ..*context };
1166         let next_line_body =
1167             try_opt!(nop_block_collapse(body.rewrite(inner_context, body_budget, indent),
1168                                         body_budget));
1169         let indent_str = offset.block_indent(context.config).to_string(context.config);
1170         let (body_prefix, body_suffix) = if context.config.wrap_match_arms {
1171             if context.config.match_block_trailing_comma {
1172                 (" {", "},")
1173             } else {
1174                 (" {", "}")
1175             }
1176         } else {
1177             ("", "")
1178         };
1179
1180         let block_sep = match context.config.control_brace_style {
1181             ControlBraceStyle::AlwaysNextLine => alt_block_sep,
1182             ControlBraceStyle::AlwaysSameLine => String::from(body_prefix) + "\n",
1183         };
1184         Some(format!("{}{} =>{}{}{}\n{}{}",
1185                      attr_str.trim_left(),
1186                      pats_str,
1187                      block_sep,
1188                      indent_str,
1189                      next_line_body,
1190                      offset.to_string(context.config),
1191                      body_suffix))
1192     }
1193 }
1194
1195 // A pattern is simple if it is very short or it is short-ish and just a path.
1196 // E.g. `Foo::Bar` is simple, but `Foo(..)` is not.
1197 fn pat_is_simple(pat_str: &str) -> bool {
1198     pat_str.len() <= 16 ||
1199     (pat_str.len() <= 24 && pat_str.chars().all(|c| c.is_alphabetic() || c == ':'))
1200 }
1201
1202 // The `if ...` guard on a match arm.
1203 fn rewrite_guard(context: &RewriteContext,
1204                  guard: &Option<ptr::P<ast::Expr>>,
1205                  width: usize,
1206                  offset: Indent,
1207                  // The amount of space used up on this line for the pattern in
1208                  // the arm (excludes offset).
1209                  pattern_width: usize)
1210                  -> Option<String> {
1211     if let Some(ref guard) = *guard {
1212         // First try to fit the guard string on the same line as the pattern.
1213         // 4 = ` if `, 5 = ` => {`
1214         let overhead = pattern_width + 4 + 5;
1215         if overhead < width {
1216             let cond_str = guard.rewrite(context, width - overhead, offset + pattern_width + 4);
1217             if let Some(cond_str) = cond_str {
1218                 return Some(format!(" if {}", cond_str));
1219             }
1220         }
1221
1222         // Not enough space to put the guard after the pattern, try a newline.
1223         let overhead = offset.block_indent(context.config).width() + 4 + 5;
1224         if overhead < width {
1225             let cond_str = guard.rewrite(context,
1226                                          width - overhead,
1227                                          // 3 == `if `
1228                                          offset.block_indent(context.config) + 3);
1229             if let Some(cond_str) = cond_str {
1230                 return Some(format!("\n{}if {}",
1231                                     offset.block_indent(context.config).to_string(context.config),
1232                                     cond_str));
1233             }
1234         }
1235
1236         None
1237     } else {
1238         Some(String::new())
1239     }
1240 }
1241
1242 fn rewrite_pat_expr(context: &RewriteContext,
1243                     pat: Option<&ast::Pat>,
1244                     expr: &ast::Expr,
1245                     matcher: &str,
1246                     // Connecting piece between pattern and expression,
1247                     // *without* trailing space.
1248                     connector: &str,
1249                     width: usize,
1250                     offset: Indent)
1251                     -> Option<String> {
1252     let pat_offset = offset + matcher.len();
1253     let mut result = match pat {
1254         Some(pat) => {
1255             let pat_budget = try_opt!(width.checked_sub(connector.len() + matcher.len()));
1256             let pat_string = try_opt!(pat.rewrite(context, pat_budget, pat_offset));
1257             format!("{}{}{}", matcher, pat_string, connector)
1258         }
1259         None => String::new(),
1260     };
1261
1262     // Consider only the last line of the pat string.
1263     let extra_offset = extra_offset(&result, offset);
1264
1265     // The expression may (partionally) fit on the current line.
1266     if width > extra_offset + 1 {
1267         let spacer = if pat.is_some() { " " } else { "" };
1268
1269         let expr_rewrite = expr.rewrite(context,
1270                                         width - extra_offset - spacer.len(),
1271                                         offset + extra_offset + spacer.len());
1272
1273         if let Some(expr_string) = expr_rewrite {
1274             result.push_str(spacer);
1275             result.push_str(&expr_string);
1276             return Some(result);
1277         }
1278     }
1279
1280     // The expression won't fit on the current line, jump to next.
1281     result.push('\n');
1282     result.push_str(&pat_offset.to_string(context.config));
1283
1284     let expr_rewrite = expr.rewrite(context,
1285                                     context.config.max_width - pat_offset.width(),
1286                                     pat_offset);
1287     result.push_str(&&try_opt!(expr_rewrite));
1288
1289     Some(result)
1290 }
1291
1292 fn rewrite_string_lit(context: &RewriteContext,
1293                       span: Span,
1294                       width: usize,
1295                       offset: Indent)
1296                       -> Option<String> {
1297     let string_lit = context.snippet(span);
1298
1299     if !context.config.format_strings && !context.config.force_format_strings {
1300         return Some(string_lit);
1301     }
1302
1303     if !context.config.force_format_strings &&
1304        !string_requires_rewrite(context, span, &string_lit, width, offset) {
1305         return Some(string_lit);
1306     }
1307
1308     let fmt = StringFormat {
1309         opener: "\"",
1310         closer: "\"",
1311         line_start: " ",
1312         line_end: "\\",
1313         width: width,
1314         offset: offset,
1315         trim_end: false,
1316         config: context.config,
1317     };
1318
1319     // Remove the quote characters.
1320     let str_lit = &string_lit[1..string_lit.len() - 1];
1321
1322     rewrite_string(str_lit, &fmt)
1323 }
1324
1325 fn string_requires_rewrite(context: &RewriteContext,
1326                            span: Span,
1327                            string: &str,
1328                            width: usize,
1329                            offset: Indent)
1330                            -> bool {
1331     if context.codemap.lookup_char_pos(span.lo).col.0 != offset.width() {
1332         return true;
1333     }
1334
1335     for (i, line) in string.lines().enumerate() {
1336         if i == 0 {
1337             if line.len() > width {
1338                 return true;
1339             }
1340         } else {
1341             if line.len() > width + offset.width() {
1342                 return true;
1343             }
1344         }
1345     }
1346
1347     false
1348 }
1349
1350 pub fn rewrite_call<R>(context: &RewriteContext,
1351                        callee: &R,
1352                        args: &[ptr::P<ast::Expr>],
1353                        span: Span,
1354                        width: usize,
1355                        offset: Indent)
1356                        -> Option<String>
1357     where R: Rewrite
1358 {
1359     let closure = |callee_max_width| {
1360         rewrite_call_inner(context, callee, callee_max_width, args, span, width, offset)
1361     };
1362
1363     // 2 is for parens
1364     let max_width = try_opt!(width.checked_sub(2));
1365     binary_search(1, max_width, closure)
1366 }
1367
1368 fn rewrite_call_inner<R>(context: &RewriteContext,
1369                          callee: &R,
1370                          max_callee_width: usize,
1371                          args: &[ptr::P<ast::Expr>],
1372                          span: Span,
1373                          width: usize,
1374                          offset: Indent)
1375                          -> Result<String, Ordering>
1376     where R: Rewrite
1377 {
1378     let callee = callee.borrow();
1379     // FIXME using byte lens instead of char lens (and probably all over the
1380     // place too)
1381     let callee_str = match callee.rewrite(context, max_callee_width, offset) {
1382         Some(string) => {
1383             if !string.contains('\n') && string.len() > max_callee_width {
1384                 panic!("{:?} {}", string, max_callee_width);
1385             } else {
1386                 string
1387             }
1388         }
1389         None => return Err(Ordering::Greater),
1390     };
1391
1392     let span_lo = context.codemap.span_after(span, "(");
1393     let span = mk_sp(span_lo, span.hi);
1394
1395     let extra_offset = extra_offset(&callee_str, offset);
1396     // 2 is for parens.
1397     let remaining_width = match width.checked_sub(extra_offset + 2) {
1398         Some(str) => str,
1399         None => return Err(Ordering::Greater),
1400     };
1401     let offset = offset + extra_offset + 1;
1402     let arg_count = args.len();
1403     let block_indent = if arg_count == 1 {
1404         context.block_indent
1405     } else {
1406         offset
1407     };
1408     let inner_context = &RewriteContext { block_indent: block_indent, ..*context };
1409
1410     let items = itemize_list(context.codemap,
1411                              args.iter(),
1412                              ")",
1413                              |item| item.span.lo,
1414                              |item| item.span.hi,
1415                              |item| item.rewrite(&inner_context, remaining_width, offset),
1416                              span.lo,
1417                              span.hi);
1418     let mut item_vec: Vec<_> = items.collect();
1419
1420     // Try letting the last argument overflow to the next line with block
1421     // indentation. If its first line fits on one line with the other arguments,
1422     // we format the function arguments horizontally.
1423     let overflow_last = match args.last().map(|x| &x.node) {
1424         Some(&ast::ExprKind::Closure(..)) |
1425         Some(&ast::ExprKind::Block(..)) if arg_count > 1 => true,
1426         _ => false,
1427     } && context.config.chains_overflow_last;
1428
1429     let mut orig_last = None;
1430     let mut placeholder = None;
1431
1432     // Replace the last item with its first line to see if it fits with
1433     // first arguments.
1434     if overflow_last {
1435         let inner_context = &RewriteContext { block_indent: context.block_indent, ..*context };
1436         let rewrite = args.last().unwrap().rewrite(&inner_context, remaining_width, offset);
1437
1438         if let Some(rewrite) = rewrite {
1439             let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
1440             placeholder = Some(rewrite);
1441
1442             swap(&mut item_vec[arg_count - 1].item, &mut orig_last);
1443             item_vec[arg_count - 1].item = rewrite_first_line;
1444         }
1445     }
1446
1447     let tactic = definitive_tactic(&item_vec,
1448                                    ListTactic::LimitedHorizontalVertical(context.config
1449                                        .fn_call_width),
1450                                    remaining_width);
1451
1452     // Replace the stub with the full overflowing last argument if the rewrite
1453     // succeeded and its first line fits with the other arguments.
1454     match (overflow_last, tactic, placeholder) {
1455         (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
1456             item_vec[arg_count - 1].item = placeholder;
1457         }
1458         (true, _, _) => {
1459             item_vec[arg_count - 1].item = orig_last;
1460         }
1461         (false, _, _) => {}
1462     }
1463
1464     let fmt = ListFormatting {
1465         tactic: tactic,
1466         separator: ",",
1467         trailing_separator: SeparatorTactic::Never,
1468         indent: offset,
1469         width: width,
1470         ends_with_newline: false,
1471         config: context.config,
1472     };
1473
1474     let list_str = match write_list(&item_vec, &fmt) {
1475         Some(str) => str,
1476         None => return Err(Ordering::Less),
1477     };
1478
1479     Ok(format!("{}({})", callee_str, list_str))
1480 }
1481
1482 fn rewrite_paren(context: &RewriteContext,
1483                  subexpr: &ast::Expr,
1484                  width: usize,
1485                  offset: Indent)
1486                  -> Option<String> {
1487     debug!("rewrite_paren, width: {}, offset: {:?}", width, offset);
1488     // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
1489     // paren on the same line as the subexpr.
1490     let subexpr_str = subexpr.rewrite(context, try_opt!(width.checked_sub(2)), offset + 1);
1491     debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1492     subexpr_str.map(|s| format!("({})", s))
1493 }
1494
1495 fn rewrite_struct_lit<'a>(context: &RewriteContext,
1496                           path: &ast::Path,
1497                           fields: &'a [ast::Field],
1498                           base: Option<&'a ast::Expr>,
1499                           span: Span,
1500                           width: usize,
1501                           offset: Indent)
1502                           -> Option<String> {
1503     debug!("rewrite_struct_lit: width {}, offset {:?}", width, offset);
1504
1505     enum StructLitField<'a> {
1506         Regular(&'a ast::Field),
1507         Base(&'a ast::Expr),
1508     }
1509
1510     // 2 = " {".len()
1511     let path_budget = try_opt!(width.checked_sub(2));
1512     let path_str = try_opt!(rewrite_path(context, true, None, path, path_budget, offset));
1513
1514     // Foo { a: Foo } - indent is +3, width is -5.
1515     let h_budget = width.checked_sub(path_str.len() + 5).unwrap_or(0);
1516     // The 1 taken from the v_budget is for the comma.
1517     let (indent, v_budget) = match context.config.struct_lit_style {
1518         StructLitStyle::Visual => (offset + path_str.len() + 3, h_budget),
1519         StructLitStyle::Block => {
1520             // If we are all on one line, then we'll ignore the indent, and we
1521             // have a smaller budget.
1522             let indent = context.block_indent.block_indent(context.config);
1523             let v_budget = context.config.max_width.checked_sub(indent.width()).unwrap_or(0);
1524             (indent, v_budget)
1525         }
1526     };
1527
1528     let field_iter = fields.into_iter()
1529         .map(StructLitField::Regular)
1530         .chain(base.into_iter().map(StructLitField::Base));
1531
1532     let inner_context = &RewriteContext { block_indent: indent, ..*context };
1533
1534     let items = itemize_list(context.codemap,
1535                              field_iter,
1536                              "}",
1537                              |item| {
1538         match *item {
1539             StructLitField::Regular(ref field) => field.span.lo,
1540             StructLitField::Base(ref expr) => {
1541                 let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
1542                 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
1543                 let pos = snippet.find_uncommented("..").unwrap();
1544                 last_field_hi + BytePos(pos as u32)
1545             }
1546         }
1547     },
1548                              |item| {
1549                                  match *item {
1550                                      StructLitField::Regular(ref field) => field.span.hi,
1551                                      StructLitField::Base(ref expr) => expr.span.hi,
1552                                  }
1553                              },
1554                              |item| {
1555         match *item {
1556             StructLitField::Regular(ref field) => {
1557                 rewrite_field(inner_context,
1558                               &field,
1559                               v_budget.checked_sub(1).unwrap_or(0),
1560                               indent)
1561             }
1562             StructLitField::Base(ref expr) => {
1563                 // 2 = ..
1564                 expr.rewrite(inner_context, try_opt!(v_budget.checked_sub(2)), indent + 2)
1565                     .map(|s| format!("..{}", s))
1566             }
1567         }
1568     },
1569                              context.codemap.span_after(span, "{"),
1570                              span.hi);
1571     let item_vec = items.collect::<Vec<_>>();
1572
1573     let tactic = {
1574         let mut prelim_tactic = match (context.config.struct_lit_style, fields.len()) {
1575             (StructLitStyle::Visual, 1) => ListTactic::HorizontalVertical,
1576             _ => context.config.struct_lit_multiline_style.to_list_tactic(),
1577         };
1578
1579         if prelim_tactic == ListTactic::HorizontalVertical && fields.len() > 1 {
1580             prelim_tactic = ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width);
1581         }
1582
1583         definitive_tactic(&item_vec, prelim_tactic, h_budget)
1584     };
1585
1586     let budget = match tactic {
1587         DefinitiveListTactic::Horizontal => h_budget,
1588         _ => v_budget,
1589     };
1590
1591     let ends_with_newline = context.config.struct_lit_style != StructLitStyle::Visual &&
1592                             tactic == DefinitiveListTactic::Vertical;
1593
1594     let fmt = ListFormatting {
1595         tactic: tactic,
1596         separator: ",",
1597         trailing_separator: if base.is_some() {
1598             SeparatorTactic::Never
1599         } else {
1600             context.config.struct_lit_trailing_comma
1601         },
1602         indent: indent,
1603         width: budget,
1604         ends_with_newline: ends_with_newline,
1605         config: context.config,
1606     };
1607     let fields_str = try_opt!(write_list(&item_vec, &fmt));
1608
1609     if fields_str.is_empty() {
1610         return Some(format!("{} {{}}", path_str));
1611     }
1612
1613     let format_on_newline = || {
1614         let inner_indent = context.block_indent
1615             .block_indent(context.config)
1616             .to_string(context.config);
1617         let outer_indent = context.block_indent.to_string(context.config);
1618         Some(format!("{} {{\n{}{}\n{}}}",
1619                      path_str,
1620                      inner_indent,
1621                      fields_str,
1622                      outer_indent))
1623     };
1624
1625     match (context.config.struct_lit_style, context.config.struct_lit_multiline_style) {
1626         (StructLitStyle::Block, _) if fields_str.contains('\n') || fields_str.len() > h_budget => {
1627             format_on_newline()
1628         }
1629         (StructLitStyle::Block, MultilineStyle::ForceMulti) => format_on_newline(),
1630         _ => Some(format!("{} {{ {} }}", path_str, fields_str)),
1631     }
1632
1633     // FIXME if context.config.struct_lit_style == Visual, but we run out
1634     // of space, we should fall back to BlockIndent.
1635 }
1636
1637 fn rewrite_field(context: &RewriteContext,
1638                  field: &ast::Field,
1639                  width: usize,
1640                  offset: Indent)
1641                  -> Option<String> {
1642     let name = &field.ident.node.to_string();
1643     let overhead = name.len() + 2;
1644     let expr = field.expr.rewrite(context,
1645                                   try_opt!(width.checked_sub(overhead)),
1646                                   offset + overhead);
1647
1648     match expr {
1649         Some(e) => Some(format!("{}: {}", name, e)),
1650         None => {
1651             let expr_offset = offset.block_indent(&context.config);
1652             let expr = field.expr.rewrite(context,
1653                                           try_opt!(context.config
1654                                               .max_width
1655                                               .checked_sub(expr_offset.width())),
1656                                           expr_offset);
1657             expr.map(|s| format!("{}:\n{}{}", name, expr_offset.to_string(&context.config), s))
1658         }
1659     }
1660 }
1661
1662 pub fn rewrite_tuple<'a, I>(context: &RewriteContext,
1663                             mut items: I,
1664                             span: Span,
1665                             width: usize,
1666                             offset: Indent)
1667                             -> Option<String>
1668     where I: ExactSizeIterator,
1669           <I as Iterator>::Item: Deref,
1670           <I::Item as Deref>::Target: Rewrite + Spanned + 'a
1671 {
1672     let indent = offset + 1;
1673     // In case of length 1, need a trailing comma
1674     if items.len() == 1 {
1675         // 3 = "(" + ",)"
1676         let budget = try_opt!(width.checked_sub(3));
1677         return items.next().unwrap().rewrite(context, budget, indent).map(|s| format!("({},)", s));
1678     }
1679
1680     let list_lo = context.codemap.span_after(span, "(");
1681     let items = itemize_list(context.codemap,
1682                              items,
1683                              ")",
1684                              |item| item.span().lo,
1685                              |item| item.span().hi,
1686                              |item| {
1687                                  let inner_width = try_opt!(context.config
1688                                      .max_width
1689                                      .checked_sub(indent.width() + 1));
1690                                  item.rewrite(context, inner_width, indent)
1691                              },
1692                              list_lo,
1693                              span.hi - BytePos(1));
1694     let budget = try_opt!(width.checked_sub(2));
1695     let list_str = try_opt!(format_item_list(items, budget, indent, context.config));
1696
1697     Some(format!("({})", list_str))
1698 }
1699
1700 fn rewrite_binary_op(context: &RewriteContext,
1701                      op: &ast::BinOp,
1702                      lhs: &ast::Expr,
1703                      rhs: &ast::Expr,
1704                      width: usize,
1705                      offset: Indent)
1706                      -> Option<String> {
1707     // FIXME: format comments between operands and operator
1708
1709     let operator_str = context.snippet(op.span);
1710
1711     // Get "full width" rhs and see if it fits on the current line. This
1712     // usually works fairly well since it tends to place operands of
1713     // operations with high precendence close together.
1714     let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
1715
1716     // Second condition is needed in case of line break not caused by a
1717     // shortage of space, but by end-of-line comments, for example.
1718     // Note that this is non-conservative, but its just to see if it's even
1719     // worth trying to put everything on one line.
1720     if rhs_result.len() + 2 + operator_str.len() < width && !rhs_result.contains('\n') {
1721         // 1 = space between lhs expr and operator
1722         if let Some(mut result) = lhs.rewrite(context, width - 1 - operator_str.len(), offset) {
1723             result.push(' ');
1724             result.push_str(&operator_str);
1725             result.push(' ');
1726
1727             let remaining_width = width.checked_sub(last_line_width(&result)).unwrap_or(0);
1728
1729             if rhs_result.len() <= remaining_width {
1730                 result.push_str(&rhs_result);
1731                 return Some(result);
1732             }
1733
1734             if let Some(rhs_result) = rhs.rewrite(context, remaining_width, offset + result.len()) {
1735                 if rhs_result.len() <= remaining_width {
1736                     result.push_str(&rhs_result);
1737                     return Some(result);
1738                 }
1739             }
1740         }
1741     }
1742
1743     // We have to use multiple lines.
1744
1745     // Re-evaluate the lhs because we have more space now:
1746     let budget = try_opt!(context.config
1747         .max_width
1748         .checked_sub(offset.width() + 1 + operator_str.len()));
1749     Some(format!("{} {}\n{}{}",
1750                  try_opt!(lhs.rewrite(context, budget, offset)),
1751                  operator_str,
1752                  offset.to_string(context.config),
1753                  rhs_result))
1754 }
1755
1756 pub fn rewrite_unary_prefix<R: Rewrite>(context: &RewriteContext,
1757                                         prefix: &str,
1758                                         rewrite: &R,
1759                                         width: usize,
1760                                         offset: Indent)
1761                                         -> Option<String> {
1762     rewrite.rewrite(context,
1763                  try_opt!(width.checked_sub(prefix.len())),
1764                  offset + prefix.len())
1765         .map(|r| format!("{}{}", prefix, r))
1766 }
1767
1768 // FIXME: this is probably not correct for multi-line Rewrites. we should
1769 // subtract suffix.len() from the last line budget, not the first!
1770 pub fn rewrite_unary_suffix<R: Rewrite>(context: &RewriteContext,
1771                                         suffix: &str,
1772                                         rewrite: &R,
1773                                         width: usize,
1774                                         offset: Indent)
1775                                         -> Option<String> {
1776     rewrite.rewrite(context, try_opt!(width.checked_sub(suffix.len())), offset)
1777         .map(|mut r| {
1778             r.push_str(suffix);
1779             r
1780         })
1781 }
1782
1783 fn rewrite_unary_op(context: &RewriteContext,
1784                     op: &ast::UnOp,
1785                     expr: &ast::Expr,
1786                     width: usize,
1787                     offset: Indent)
1788                     -> Option<String> {
1789     // For some reason, an UnOp is not spanned like BinOp!
1790     let operator_str = match *op {
1791         ast::UnOp::Deref => "*",
1792         ast::UnOp::Not => "!",
1793         ast::UnOp::Neg => "-",
1794     };
1795     rewrite_unary_prefix(context, operator_str, expr, width, offset)
1796 }
1797
1798 fn rewrite_assignment(context: &RewriteContext,
1799                       lhs: &ast::Expr,
1800                       rhs: &ast::Expr,
1801                       op: Option<&ast::BinOp>,
1802                       width: usize,
1803                       offset: Indent)
1804                       -> Option<String> {
1805     let operator_str = match op {
1806         Some(op) => context.snippet(op.span),
1807         None => "=".to_owned(),
1808     };
1809
1810     // 1 = space between lhs and operator.
1811     let max_width = try_opt!(width.checked_sub(operator_str.len() + 1));
1812     let lhs_str = format!("{} {}",
1813                           try_opt!(lhs.rewrite(context, max_width, offset)),
1814                           operator_str);
1815
1816     rewrite_assign_rhs(&context, lhs_str, rhs, width, offset)
1817 }
1818
1819 // The left hand side must contain everything up to, and including, the
1820 // assignment operator.
1821 pub fn rewrite_assign_rhs<S: Into<String>>(context: &RewriteContext,
1822                                            lhs: S,
1823                                            ex: &ast::Expr,
1824                                            width: usize,
1825                                            offset: Indent)
1826                                            -> Option<String> {
1827     let mut result = lhs.into();
1828     let last_line_width = last_line_width(&result) -
1829                           if result.contains('\n') {
1830         offset.width()
1831     } else {
1832         0
1833     };
1834     // 1 = space between operator and rhs.
1835     let max_width = try_opt!(width.checked_sub(last_line_width + 1));
1836     let rhs = ex.rewrite(&context, max_width, offset + last_line_width + 1);
1837
1838     fn count_line_breaks(src: &str) -> usize {
1839         src.chars().filter(|&x| x == '\n').count()
1840     }
1841
1842     match rhs {
1843         Some(ref new_str) if count_line_breaks(new_str) < 2 => {
1844             result.push(' ');
1845             result.push_str(new_str);
1846         }
1847         _ => {
1848             // Expression did not fit on the same line as the identifier or is
1849             // at least three lines big. Try splitting the line and see
1850             // if that works better.
1851             let new_offset = offset.block_indent(context.config);
1852             let max_width = try_opt!((width + offset.width()).checked_sub(new_offset.width()));
1853             let inner_context = context.nested_context();
1854             let new_rhs = ex.rewrite(&inner_context, max_width, new_offset);
1855
1856             // FIXME: DRY!
1857             match (rhs, new_rhs) {
1858                 (Some(ref orig_rhs), Some(ref replacement_rhs))
1859                     if count_line_breaks(orig_rhs) >
1860                        count_line_breaks(replacement_rhs) + 1 => {
1861                     result.push_str(&format!("\n{}", new_offset.to_string(context.config)));
1862                     result.push_str(replacement_rhs);
1863                 }
1864                 (None, Some(ref final_rhs)) => {
1865                     result.push_str(&format!("\n{}", new_offset.to_string(context.config)));
1866                     result.push_str(final_rhs);
1867                 }
1868                 (None, None) => return None,
1869                 (Some(ref orig_rhs), _) => {
1870                     result.push(' ');
1871                     result.push_str(orig_rhs);
1872                 }
1873             }
1874         }
1875     }
1876
1877     Some(result)
1878 }
1879
1880 fn rewrite_expr_addrof(context: &RewriteContext,
1881                        mutability: ast::Mutability,
1882                        expr: &ast::Expr,
1883                        width: usize,
1884                        offset: Indent)
1885                        -> Option<String> {
1886     let operator_str = match mutability {
1887         ast::Mutability::Immutable => "&",
1888         ast::Mutability::Mutable => "&mut ",
1889     };
1890     rewrite_unary_prefix(context, operator_str, expr, width, offset)
1891 }