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