]> git.lizzy.rs Git - rust.git/blob - src/expr.rs
1d0621539e012656be180b66404b2ed902f139ae
[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
14 use Indent;
15 use rewrite::{Rewrite, RewriteContext};
16 use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic,
17             DefinitiveListTactic, definitive_tactic, ListItem, format_fn_args};
18 use string::{StringFormat, rewrite_string};
19 use utils::{span_after, extra_offset, last_line_width, wrap_str, binary_search};
20 use visitor::FmtVisitor;
21 use config::{StructLitStyle, MultilineStyle};
22 use comment::{FindUncommented, rewrite_comment, contains_comment};
23 use types::rewrite_path;
24 use items::{span_lo_for_arg, span_hi_for_arg};
25 use chains::rewrite_chain;
26 use macros::rewrite_macro;
27
28 use syntax::{ast, ptr};
29 use syntax::codemap::{CodeMap, Span, BytePos, mk_sp};
30 use syntax::visit::Visitor;
31
32 impl Rewrite for ast::Expr {
33     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
34         match self.node {
35             ast::Expr_::ExprVec(ref expr_vec) => {
36                 rewrite_array(expr_vec.iter().map(|e| &**e),
37                               self.span,
38                               context,
39                               width,
40                               offset)
41             }
42             ast::Expr_::ExprLit(ref l) => {
43                 match l.node {
44                     ast::Lit_::LitStr(_, ast::StrStyle::CookedStr) => {
45                         rewrite_string_lit(context, l.span, width, offset)
46                     }
47                     _ => {
48                         wrap_str(context.snippet(self.span),
49                                  context.config.max_width,
50                                  width,
51                                  offset)
52                     }
53                 }
54             }
55             ast::Expr_::ExprCall(ref callee, ref args) => {
56                 let inner_span = mk_sp(callee.span.hi, self.span.hi);
57                 rewrite_call(context, &**callee, args, inner_span, width, offset)
58             }
59             ast::Expr_::ExprParen(ref subexpr) => {
60                 rewrite_paren(context, subexpr, width, offset)
61             }
62             ast::Expr_::ExprBinary(ref op, ref lhs, ref rhs) => {
63                 rewrite_binary_op(context, op, lhs, rhs, width, offset)
64             }
65             ast::Expr_::ExprUnary(ref op, ref subexpr) => {
66                 rewrite_unary_op(context, op, subexpr, width, offset)
67             }
68             ast::Expr_::ExprStruct(ref path, ref fields, ref base) => {
69                 rewrite_struct_lit(context,
70                                    path,
71                                    fields,
72                                    base.as_ref().map(|e| &**e),
73                                    self.span,
74                                    width,
75                                    offset)
76             }
77             ast::Expr_::ExprTup(ref items) => {
78                 rewrite_tuple_lit(context, items, self.span, width, offset)
79             }
80             ast::Expr_::ExprWhile(ref cond, ref block, label) => {
81                 Loop::new_while(None, cond, block, label).rewrite(context, width, offset)
82             }
83             ast::Expr_::ExprWhileLet(ref pat, ref cond, ref block, label) => {
84                 Loop::new_while(Some(pat), cond, block, label).rewrite(context, width, offset)
85             }
86             ast::Expr_::ExprForLoop(ref pat, ref cond, ref block, label) => {
87                 Loop::new_for(pat, cond, block, label).rewrite(context, width, offset)
88             }
89             ast::Expr_::ExprLoop(ref block, label) => {
90                 Loop::new_loop(block, label).rewrite(context, width, offset)
91             }
92             ast::Expr_::ExprBlock(ref block) => {
93                 block.rewrite(context, width, offset)
94             }
95             ast::Expr_::ExprIf(ref cond, ref if_block, ref else_block) => {
96                 rewrite_if_else(context,
97                                 cond,
98                                 if_block,
99                                 else_block.as_ref().map(|e| &**e),
100                                 None,
101                                 width,
102                                 offset,
103                                 true)
104             }
105             ast::Expr_::ExprIfLet(ref pat, ref cond, ref if_block, ref else_block) => {
106                 rewrite_if_else(context,
107                                 cond,
108                                 if_block,
109                                 else_block.as_ref().map(|e| &**e),
110                                 Some(pat),
111                                 width,
112                                 offset,
113                                 true)
114             }
115             ast::Expr_::ExprMatch(ref cond, ref arms, _) => {
116                 rewrite_match(context, cond, arms, width, offset, self.span)
117             }
118             ast::Expr_::ExprPath(ref qself, ref path) => {
119                 rewrite_path(context, qself.as_ref(), path, width, offset)
120             }
121             ast::Expr_::ExprAssign(ref lhs, ref rhs) => {
122                 rewrite_assignment(context, lhs, rhs, None, width, offset)
123             }
124             ast::Expr_::ExprAssignOp(ref op, ref lhs, ref rhs) => {
125                 rewrite_assignment(context, lhs, rhs, Some(op), width, offset)
126             }
127             ast::Expr_::ExprAgain(ref opt_ident) => {
128                 let id_str = match *opt_ident {
129                     Some(ident) => format!(" {}", ident.node),
130                     None => String::new(),
131                 };
132                 Some(format!("continue{}", id_str))
133             }
134             ast::Expr_::ExprBreak(ref opt_ident) => {
135                 let id_str = match *opt_ident {
136                     Some(ident) => format!(" {}", ident.node),
137                     None => String::new(),
138                 };
139                 Some(format!("break{}", id_str))
140             }
141             ast::Expr_::ExprClosure(capture, ref fn_decl, ref body) => {
142                 rewrite_closure(capture, fn_decl, body, self.span, context, width, offset)
143             }
144             ast::Expr_::ExprField(..) |
145             ast::Expr_::ExprTupField(..) |
146             ast::Expr_::ExprMethodCall(..) => {
147                 rewrite_chain(self, context, width, offset)
148             }
149             ast::Expr_::ExprMac(ref mac) => {
150                 // Failure to rewrite a marco should not imply failure to
151                 // rewrite the expression.
152                 rewrite_macro(mac, context, width, offset).or_else(|| {
153                     wrap_str(context.snippet(self.span),
154                              context.config.max_width,
155                              width,
156                              offset)
157                 })
158             }
159             ast::Expr_::ExprRet(None) => {
160                 wrap_str("return".to_owned(), context.config.max_width, width, offset)
161             }
162             ast::Expr_::ExprRet(Some(ref expr)) => {
163                 rewrite_unary_prefix(context, "return ", expr, width, offset)
164             }
165             ast::Expr_::ExprBox(ref expr) => {
166                 rewrite_unary_prefix(context, "box ", expr, width, offset)
167             }
168             ast::Expr_::ExprAddrOf(mutability, ref expr) => {
169                 rewrite_expr_addrof(context, mutability, expr, width, offset)
170             }
171             ast::Expr_::ExprCast(ref expr, ref ty) => {
172                 rewrite_pair(&**expr, &**ty, "", " as ", "", context, width, offset)
173             }
174             ast::Expr_::ExprIndex(ref expr, ref index) => {
175                 rewrite_pair(&**expr, &**index, "", "[", "]", context, width, offset)
176             }
177             ast::Expr_::ExprRepeat(ref expr, ref repeats) => {
178                 rewrite_pair(&**expr, &**repeats, "[", "; ", "]", context, width, offset)
179             }
180             ast::Expr_::ExprRange(Some(ref lhs), Some(ref rhs)) => {
181                 rewrite_pair(&**lhs, &**rhs, "", "..", "", context, width, offset)
182             }
183             ast::Expr_::ExprRange(None, Some(ref rhs)) => {
184                 rewrite_unary_prefix(context, "..", &**rhs, width, offset)
185             }
186             ast::Expr_::ExprRange(Some(ref lhs), None) => {
187                 Some(format!("{}..",
188                              try_opt!(lhs.rewrite(context,
189                                                   try_opt!(width.checked_sub(2)),
190                                                   offset))))
191             }
192             ast::Expr_::ExprRange(None, None) => {
193                 if width >= 2 {
194                     Some("..".into())
195                 } else {
196                     None
197                 }
198             }
199             // We do not format these expressions yet, but they should still
200             // satisfy our width restrictions.
201             ast::Expr_::ExprInPlace(..) |
202             ast::Expr_::ExprInlineAsm(..) => {
203                 wrap_str(context.snippet(self.span),
204                          context.config.max_width,
205                          width,
206                          offset)
207             }
208         }
209     }
210 }
211
212 fn rewrite_pair<LHS, RHS>(lhs: &LHS,
213                           rhs: &RHS,
214                           prefix: &str,
215                           infix: &str,
216                           suffix: &str,
217                           context: &RewriteContext,
218                           width: usize,
219                           offset: Indent)
220                           -> Option<String>
221     where LHS: Rewrite,
222           RHS: Rewrite
223 {
224     let max_width = try_opt!(width.checked_sub(prefix.len() + infix.len() + suffix.len()));
225
226     binary_search(1,
227                   max_width,
228                   |lhs_budget| {
229                       let lhs_offset = offset + prefix.len();
230                       let lhs_str = match lhs.rewrite(context, lhs_budget, lhs_offset) {
231                           Some(result) => result,
232                           None => return Err(Ordering::Greater),
233                       };
234
235                       let last_line_width = last_line_width(&lhs_str);
236                       let rhs_budget = match max_width.checked_sub(last_line_width) {
237                           Some(b) => b,
238                           None => return Err(Ordering::Less),
239                       };
240                       let rhs_indent = offset + last_line_width + prefix.len() + infix.len();
241
242                       let rhs_str = match rhs.rewrite(context, rhs_budget, rhs_indent) {
243                           Some(result) => result,
244                           None => return Err(Ordering::Less),
245                       };
246
247                       Ok(format!("{}{}{}{}{}", prefix, lhs_str, infix, rhs_str, suffix))
248                   })
249 }
250
251 pub fn rewrite_array<'a, I>(expr_iter: I,
252                             span: Span,
253                             context: &RewriteContext,
254                             width: usize,
255                             offset: Indent)
256                             -> Option<String>
257     where I: Iterator<Item = &'a ast::Expr>
258 {
259     // 2 for brackets;
260     let max_item_width = try_opt!(width.checked_sub(2));
261     let items = itemize_list(context.codemap,
262                              expr_iter,
263                              "]",
264                              |item| item.span.lo,
265                              |item| item.span.hi,
266                              // 1 = [
267                              |item| item.rewrite(context, max_item_width, offset + 1),
268                              span_after(span, "[", context.codemap),
269                              span.hi)
270                     .collect::<Vec<_>>();
271
272     let has_long_item = try_opt!(items.iter()
273                                       .map(|li| li.item.as_ref().map(|s| s.len() > 10))
274                                       .fold(Some(false),
275                                             |acc, x| acc.and_then(|y| x.map(|x| (x || y)))));
276
277     let tactic = if has_long_item || items.iter().any(ListItem::is_multiline) {
278         definitive_tactic(&items, ListTactic::HorizontalVertical, max_item_width)
279     } else {
280         DefinitiveListTactic::Mixed
281     };
282
283     let fmt = ListFormatting {
284         tactic: tactic,
285         separator: ",",
286         trailing_separator: SeparatorTactic::Never,
287         indent: offset + 1,
288         width: max_item_width,
289         ends_with_newline: false,
290         config: context.config,
291     };
292     let list_str = try_opt!(write_list(&items, &fmt));
293
294     Some(format!("[{}]", list_str))
295 }
296
297 // This functions is pretty messy because of the wrapping and unwrapping of
298 // expressions into and from blocks. See rust issue #27872.
299 fn rewrite_closure(capture: ast::CaptureClause,
300                    fn_decl: &ast::FnDecl,
301                    body: &ast::Block,
302                    span: Span,
303                    context: &RewriteContext,
304                    width: usize,
305                    offset: Indent)
306                    -> Option<String> {
307     let mover = if capture == ast::CaptureClause::CaptureByValue {
308         "move "
309     } else {
310         ""
311     };
312     let offset = offset + mover.len();
313
314     // 4 = "|| {".len(), which is overconservative when the closure consists of
315     // a single expression.
316     let budget = try_opt!(width.checked_sub(4 + mover.len()));
317     // 1 = |
318     let argument_offset = offset + 1;
319     let ret_str = try_opt!(fn_decl.output.rewrite(context, budget, argument_offset));
320     // 1 = space between arguments and return type.
321     let horizontal_budget = budget.checked_sub(ret_str.len() + 1).unwrap_or(0);
322
323     let arg_items = itemize_list(context.codemap,
324                                  fn_decl.inputs.iter(),
325                                  "|",
326                                  |arg| span_lo_for_arg(arg),
327                                  |arg| span_hi_for_arg(arg),
328                                  |arg| arg.rewrite(context, budget, argument_offset),
329                                  span_after(span, "|", context.codemap),
330                                  body.span.lo);
331     let item_vec = arg_items.collect::<Vec<_>>();
332     let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
333     let budget = match tactic {
334         DefinitiveListTactic::Horizontal => horizontal_budget,
335         _ => budget,
336     };
337
338     let fmt = ListFormatting {
339         tactic: tactic,
340         separator: ",",
341         trailing_separator: SeparatorTactic::Never,
342         indent: argument_offset,
343         width: budget,
344         ends_with_newline: false,
345         config: context.config,
346     };
347     let list_str = try_opt!(write_list(&item_vec, &fmt));
348     let mut prefix = format!("{}|{}|", mover, list_str);
349
350     if !ret_str.is_empty() {
351         if prefix.contains('\n') {
352             prefix.push('\n');
353             prefix.push_str(&argument_offset.to_string(context.config));
354         } else {
355             prefix.push(' ');
356         }
357         prefix.push_str(&ret_str);
358     }
359
360     // Try to format closure body as a single line expression without braces.
361     if is_simple_block(body, context.codemap) && !prefix.contains('\n') {
362         let (spacer, closer) = if ret_str.is_empty() {
363             (" ", "")
364         } else {
365             (" { ", " }")
366         };
367         let expr = body.expr.as_ref().unwrap();
368         // All closure bodies are blocks in the eyes of the AST, but we may not
369         // want to unwrap them when they only contain a single expression.
370         let inner_expr = match expr.node {
371             ast::Expr_::ExprBlock(ref inner) if inner.stmts.is_empty() && inner.expr.is_some() &&
372                                                 inner.rules ==
373                                                 ast::BlockCheckMode::DefaultBlock => {
374                 inner.expr.as_ref().unwrap()
375             }
376             _ => expr,
377         };
378         let extra_offset = extra_offset(&prefix, offset) + spacer.len();
379         let budget = try_opt!(width.checked_sub(extra_offset + closer.len()));
380         let rewrite = inner_expr.rewrite(context, budget, offset + extra_offset);
381
382         // Checks if rewrite succeeded and fits on a single line.
383         let accept_rewrite = rewrite.as_ref().map(|result| !result.contains('\n')).unwrap_or(false);
384
385         if accept_rewrite {
386             return Some(format!("{}{}{}{}", prefix, spacer, rewrite.unwrap(), closer));
387         }
388     }
389
390     // We couldn't format the closure body as a single line expression; fall
391     // back to block formatting.
392     let body_rewrite = body.expr
393                            .as_ref()
394                            .and_then(|body_expr| {
395                                if let ast::Expr_::ExprBlock(ref inner) = body_expr.node {
396                                    Some(inner.rewrite(&context, 2, Indent::empty()))
397                                } else {
398                                    None
399                                }
400                            })
401                            .unwrap_or_else(|| body.rewrite(&context, 2, Indent::empty()));
402
403     Some(format!("{} {}", prefix, try_opt!(body_rewrite)))
404 }
405
406 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
407     block_str.map(|block_str| {
408         if block_str.starts_with("{") && budget >= 2 &&
409            (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2) {
410             "{}".to_owned()
411         } else {
412             block_str.to_owned()
413         }
414     })
415 }
416
417 impl Rewrite for ast::Block {
418     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
419         let user_str = context.snippet(self.span);
420         if user_str == "{}" && width >= 2 {
421             return Some(user_str);
422         }
423
424         let mut visitor = FmtVisitor::from_codemap(context.codemap, context.config);
425         visitor.block_indent = context.block_indent + context.overflow_indent;
426
427         let prefix = match self.rules {
428             ast::BlockCheckMode::PushUnsafeBlock(..) |
429             ast::BlockCheckMode::UnsafeBlock(..) => {
430                 let snippet = context.snippet(self.span);
431                 let open_pos = try_opt!(snippet.find_uncommented("{"));
432                 visitor.last_pos = self.span.lo + BytePos(open_pos as u32);
433
434                 // Extract comment between unsafe and block start.
435                 let trimmed = &snippet[6..open_pos].trim();
436
437                 let prefix = if !trimmed.is_empty() {
438                     // 9 = "unsafe  {".len(), 7 = "unsafe ".len()
439                     let budget = try_opt!(width.checked_sub(9));
440                     format!("unsafe {} ",
441                             try_opt!(rewrite_comment(trimmed,
442                                                      true,
443                                                      budget,
444                                                      offset + 7,
445                                                      context.config)))
446                 } else {
447                     "unsafe ".to_owned()
448                 };
449
450                 if is_simple_block(self, context.codemap) && prefix.len() < width {
451                     let body = self.expr
452                                    .as_ref()
453                                    .unwrap()
454                                    .rewrite(context, width - prefix.len(), offset);
455                     if let Some(ref expr_str) = body {
456                         let result = format!("{}{{ {} }}", prefix, expr_str);
457                         if result.len() <= width && !result.contains('\n') {
458                             return Some(result);
459                         }
460                     }
461                 }
462
463                 prefix
464             }
465             ast::BlockCheckMode::PopUnsafeBlock(..) |
466             ast::BlockCheckMode::DefaultBlock => {
467                 visitor.last_pos = self.span.lo;
468
469                 String::new()
470             }
471         };
472
473         visitor.visit_block(self);
474
475         // Push text between last block item and end of block
476         let snippet = visitor.snippet(mk_sp(visitor.last_pos, self.span.hi));
477         visitor.buffer.push_str(&snippet);
478
479         Some(format!("{}{}", prefix, visitor.buffer))
480     }
481 }
482
483 // FIXME(#18): implement pattern formatting
484 impl Rewrite for ast::Pat {
485     fn rewrite(&self, context: &RewriteContext, _: usize, _: Indent) -> Option<String> {
486         Some(context.snippet(self.span))
487     }
488 }
489
490 // Abstraction over for, while and loop expressions
491 struct Loop<'a> {
492     cond: Option<&'a ast::Expr>,
493     block: &'a ast::Block,
494     label: Option<ast::Ident>,
495     pat: Option<&'a ast::Pat>,
496     keyword: &'a str,
497     matcher: &'a str,
498     connector: &'a str,
499 }
500
501 impl<'a> Loop<'a> {
502     fn new_loop(block: &'a ast::Block, label: Option<ast::Ident>) -> Loop<'a> {
503         Loop {
504             cond: None,
505             block: block,
506             label: label,
507             pat: None,
508             keyword: "loop",
509             matcher: "",
510             connector: "",
511         }
512     }
513
514     fn new_while(pat: Option<&'a ast::Pat>,
515                  cond: &'a ast::Expr,
516                  block: &'a ast::Block,
517                  label: Option<ast::Ident>)
518                  -> Loop<'a> {
519         Loop {
520             cond: Some(cond),
521             block: block,
522             label: label,
523             pat: pat,
524             keyword: "while ",
525             matcher: match pat {
526                 Some(..) => "let ",
527                 None => "",
528             },
529             connector: " =",
530         }
531     }
532
533     fn new_for(pat: &'a ast::Pat,
534                cond: &'a ast::Expr,
535                block: &'a ast::Block,
536                label: Option<ast::Ident>)
537                -> Loop<'a> {
538         Loop {
539             cond: Some(cond),
540             block: block,
541             label: label,
542             pat: Some(pat),
543             keyword: "for ",
544             matcher: "",
545             connector: " in",
546         }
547     }
548 }
549
550 impl<'a> Rewrite for Loop<'a> {
551     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
552         let label_string = rewrite_label(self.label);
553         // 2 = " {".len()
554         let inner_width = try_opt!(width.checked_sub(self.keyword.len() + 2 + label_string.len()));
555         let inner_offset = offset + self.keyword.len() + label_string.len();
556
557         let pat_expr_string = match self.cond {
558             Some(cond) => try_opt!(rewrite_pat_expr(context,
559                                                     self.pat,
560                                                     cond,
561                                                     self.matcher,
562                                                     self.connector,
563                                                     inner_width,
564                                                     inner_offset)),
565             None => String::new(),
566         };
567
568         // FIXME: this drops any comment between "loop" and the block.
569         self.block
570             .rewrite(context, width, offset)
571             .map(|result| {
572                 format!("{}{}{} {}",
573                         label_string,
574                         self.keyword,
575                         pat_expr_string,
576                         result)
577             })
578     }
579 }
580
581 fn rewrite_label(label: Option<ast::Ident>) -> String {
582     match label {
583         Some(ident) => format!("{}: ", ident),
584         None => "".to_owned(),
585     }
586 }
587
588 // Rewrites if-else blocks. If let Some(_) = pat, the expression is
589 // treated as an if-let-else expression.
590 fn rewrite_if_else(context: &RewriteContext,
591                    cond: &ast::Expr,
592                    if_block: &ast::Block,
593                    else_block_opt: Option<&ast::Expr>,
594                    pat: Option<&ast::Pat>,
595                    width: usize,
596                    offset: Indent,
597                    allow_single_line: bool)
598                    -> Option<String> {
599     // 3 = "if ", 2 = " {"
600     let pat_expr_string = try_opt!(rewrite_pat_expr(context,
601                                                     pat,
602                                                     cond,
603                                                     "let ",
604                                                     " =",
605                                                     try_opt!(width.checked_sub(3 + 2)),
606                                                     offset + 3));
607
608     // Try to format if-else on single line.
609     if allow_single_line && context.config.single_line_if_else {
610         let trial = single_line_if_else(context, &pat_expr_string, if_block, else_block_opt, width);
611
612         if trial.is_some() {
613             return trial;
614         }
615     }
616
617     let if_block_string = try_opt!(if_block.rewrite(context, width, offset));
618     let mut result = format!("if {} {}", pat_expr_string, if_block_string);
619
620     if let Some(else_block) = else_block_opt {
621         let rewrite = match else_block.node {
622             // If the else expression is another if-else expression, prevent it
623             // from being formatted on a single line.
624             ast::Expr_::ExprIfLet(ref pat, ref cond, ref if_block, ref else_block) => {
625                 rewrite_if_else(context,
626                                 cond,
627                                 if_block,
628                                 else_block.as_ref().map(|e| &**e),
629                                 Some(pat),
630                                 width,
631                                 offset,
632                                 false)
633             }
634             ast::Expr_::ExprIf(ref cond, ref if_block, ref else_block) => {
635                 rewrite_if_else(context,
636                                 cond,
637                                 if_block,
638                                 else_block.as_ref().map(|e| &**e),
639                                 None,
640                                 width,
641                                 offset,
642                                 false)
643             }
644             _ => else_block.rewrite(context, width, offset),
645         };
646
647         result.push_str(" else ");
648         result.push_str(&&try_opt!(rewrite));
649     }
650
651     Some(result)
652 }
653
654 fn single_line_if_else(context: &RewriteContext,
655                        pat_expr_str: &str,
656                        if_node: &ast::Block,
657                        else_block_opt: Option<&ast::Expr>,
658                        width: usize)
659                        -> Option<String> {
660     let else_block = try_opt!(else_block_opt);
661     let fixed_cost = "if  {  } else {  }".len();
662
663     if let ast::ExprBlock(ref else_node) = else_block.node {
664         if !is_simple_block(if_node, context.codemap) ||
665            !is_simple_block(else_node, context.codemap) || pat_expr_str.contains('\n') {
666             return None;
667         }
668
669         let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
670         let if_expr = if_node.expr.as_ref().unwrap();
671         let if_str = try_opt!(if_expr.rewrite(context, new_width, Indent::empty()));
672
673         let new_width = try_opt!(new_width.checked_sub(if_str.len()));
674         let else_expr = else_node.expr.as_ref().unwrap();
675         let else_str = try_opt!(else_expr.rewrite(context, new_width, Indent::empty()));
676
677         // FIXME: this check shouldn't be necessary. Rewrites should either fail
678         // or wrap to a newline when the object does not fit the width.
679         let fits_line = fixed_cost + pat_expr_str.len() + if_str.len() + else_str.len() <= width;
680
681         if fits_line && !if_str.contains('\n') && !else_str.contains('\n') {
682             return Some(format!("if {} {{ {} }} else {{ {} }}",
683                                 pat_expr_str,
684                                 if_str,
685                                 else_str));
686         }
687     }
688
689     None
690 }
691
692 // Checks that a block contains no statements, an expression and no comments.
693 fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
694     if !block.stmts.is_empty() || block.expr.is_none() {
695         return false;
696     }
697
698     let snippet = codemap.span_to_snippet(block.span).unwrap();
699
700     !contains_comment(&snippet)
701 }
702
703 // inter-match-arm-comment-rules:
704 //  - all comments following a match arm before the start of the next arm
705 //    are about the second arm
706 fn rewrite_match_arm_comment(context: &RewriteContext,
707                              missed_str: &str,
708                              width: usize,
709                              arm_indent: Indent,
710                              arm_indent_str: &str)
711                              -> Option<String> {
712     // The leading "," is not part of the arm-comment
713     let missed_str = match missed_str.find_uncommented(",") {
714         Some(n) => &missed_str[n + 1..],
715         None => &missed_str[..],
716     };
717
718     let mut result = String::new();
719     // any text not preceeded by a newline is pushed unmodified to the block
720     let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
721     result.push_str(&missed_str[..first_brk]);
722     let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
723
724     let first = missed_str.find(|c: char| !c.is_whitespace()).unwrap_or(missed_str.len());
725     if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
726         // Excessive vertical whitespace before comment should be preserved
727         // TODO handle vertical whitespace better
728         result.push('\n');
729     }
730     let missed_str = missed_str[first..].trim();
731     if !missed_str.is_empty() {
732         let comment = try_opt!(rewrite_comment(&missed_str,
733                                                false,
734                                                width,
735                                                arm_indent,
736                                                context.config));
737         result.push('\n');
738         result.push_str(arm_indent_str);
739         result.push_str(&comment);
740     }
741
742     Some(result)
743 }
744
745 fn rewrite_match(context: &RewriteContext,
746                  cond: &ast::Expr,
747                  arms: &[ast::Arm],
748                  width: usize,
749                  offset: Indent,
750                  span: Span)
751                  -> Option<String> {
752     if arms.is_empty() {
753         return None;
754     }
755
756     // `match `cond` {`
757     let cond_budget = try_opt!(width.checked_sub(8));
758     let cond_str = try_opt!(cond.rewrite(context, cond_budget, offset + 6));
759     let mut result = format!("match {} {{", cond_str);
760
761     let nested_context = context.nested_context();
762     let arm_indent = nested_context.block_indent + context.overflow_indent;
763     let arm_indent_str = arm_indent.to_string(context.config);
764
765     let open_brace_pos = span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])),
766                                     "{",
767                                     context.codemap);
768
769     for (i, arm) in arms.iter().enumerate() {
770         // Make sure we get the stuff between arms.
771         let missed_str = if i == 0 {
772             context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
773         } else {
774             context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
775         };
776         let comment = try_opt!(rewrite_match_arm_comment(context,
777                                                          &missed_str,
778                                                          width,
779                                                          arm_indent,
780                                                          &arm_indent_str));
781         result.push_str(&comment);
782         result.push('\n');
783         result.push_str(&arm_indent_str);
784
785         let arm_str = arm.rewrite(&nested_context,
786                                   context.config.max_width - arm_indent.width(),
787                                   arm_indent);
788         if let Some(ref arm_str) = arm_str {
789             result.push_str(arm_str);
790         } else {
791             // We couldn't format the arm, just reproduce the source.
792             let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
793             result.push_str(&snippet);
794         }
795     }
796     // BytePos(1) = closing match brace.
797     let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
798     let last_comment = context.snippet(last_span);
799     let comment = try_opt!(rewrite_match_arm_comment(context,
800                                                      &last_comment,
801                                                      width,
802                                                      arm_indent,
803                                                      &arm_indent_str));
804     result.push_str(&comment);
805     result.push('\n');
806     result.push_str(&(context.block_indent + context.overflow_indent).to_string(context.config));
807     result.push('}');
808     Some(result)
809 }
810
811 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
812     let &ast::Arm { ref attrs, ref pats, .. } = arm;
813     if !attrs.is_empty() {
814         return attrs[0].span.lo
815     }
816
817     pats[0].span.lo
818 }
819
820 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
821     arm.body.span.hi
822 }
823
824 // Match arms.
825 impl Rewrite for ast::Arm {
826     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
827         let &ast::Arm { ref attrs, ref pats, ref guard, ref body } = self;
828         let indent_str = offset.to_string(context.config);
829
830         // FIXME this is all a bit grotty, would be nice to abstract out the
831         // treatment of attributes.
832         let attr_str = if !attrs.is_empty() {
833             // We only use this visitor for the attributes, should we use it for
834             // more?
835             let mut attr_visitor = FmtVisitor::from_codemap(context.codemap, context.config);
836             attr_visitor.block_indent = context.block_indent;
837             attr_visitor.last_pos = attrs[0].span.lo;
838             if attr_visitor.visit_attrs(attrs) {
839                 // Attributes included a skip instruction.
840                 let snippet = context.snippet(mk_sp(attrs[0].span.lo, body.span.hi));
841                 return Some(snippet);
842             }
843             attr_visitor.format_missing(pats[0].span.lo);
844             attr_visitor.buffer.to_string()
845         } else {
846             String::new()
847         };
848
849         // Patterns
850         // 5 = ` => {`
851         let pat_budget = try_opt!(width.checked_sub(5));
852         let pat_strs = try_opt!(pats.iter()
853                                     .map(|p| {
854                                         p.rewrite(context,
855                                                   pat_budget,
856                                                   offset.block_indent(context.config))
857                                     })
858                                     .collect::<Option<Vec<_>>>());
859
860         let mut total_width = pat_strs.iter().fold(0, |a, p| a + p.len());
861         // Add ` | `.len().
862         total_width += (pat_strs.len() - 1) * 3;
863
864         let mut vertical = total_width > pat_budget || pat_strs.iter().any(|p| p.contains('\n'));
865         if !vertical && context.config.take_source_hints {
866             // If the patterns were previously stacked, keep them stacked.
867             let pat_span = mk_sp(pats[0].span.lo, pats[pats.len() - 1].span.hi);
868             let pat_str = context.snippet(pat_span);
869             vertical = pat_str.find('\n').is_some();
870         }
871
872         let pats_width = if vertical {
873             pat_strs[pat_strs.len() - 1].len()
874         } else {
875             total_width
876         };
877
878         let mut pats_str = String::new();
879         for p in pat_strs {
880             if !pats_str.is_empty() {
881                 if vertical {
882                     pats_str.push_str(" |\n");
883                     pats_str.push_str(&indent_str);
884                 } else {
885                     pats_str.push_str(" | ");
886                 }
887             }
888             pats_str.push_str(&p);
889         }
890
891         let guard_str = try_opt!(rewrite_guard(context, guard, width, offset, pats_width));
892
893         let pats_str = format!("{}{}", pats_str, guard_str);
894         // Where the next text can start.
895         let mut line_start = last_line_width(&pats_str);
896         if !pats_str.contains('\n') {
897             line_start += offset.width();
898         }
899
900         let comma = if let ast::ExprBlock(_) = body.node {
901             ""
902         } else {
903             ","
904         };
905
906         // Let's try and get the arm body on the same line as the condition.
907         // 4 = ` => `.len()
908         let same_line_body = if context.config.max_width > line_start + comma.len() + 4 {
909             let budget = context.config.max_width - line_start - comma.len() - 4;
910             let offset = Indent::new(offset.block_indent, line_start + 4 - offset.block_indent);
911             let rewrite = nop_block_collapse(body.rewrite(context, budget, offset), budget);
912
913             match rewrite {
914                 Some(ref body_str) if body_str.len() <= budget || comma.is_empty() =>
915                     return Some(format!("{}{} => {}{}",
916                                         attr_str.trim_left(),
917                                         pats_str,
918                                         body_str,
919                                         comma)),
920                 _ => rewrite,
921             }
922         } else {
923             None
924         };
925
926         if let ast::ExprBlock(_) = body.node {
927             // We're trying to fit a block in, but it still failed, give up.
928             return None;
929         }
930
931         let body_budget = try_opt!(width.checked_sub(context.config.tab_spaces));
932         let next_line_body = nop_block_collapse(body.rewrite(context,
933                                                              body_budget,
934                                                              context.block_indent
935                                                                     .block_indent(context.config)),
936                                                 body_budget);
937
938         let body_str = try_opt!(match_arm_heuristic(same_line_body.as_ref().map(|x| &x[..]),
939                                                     next_line_body.as_ref().map(|x| &x[..])));
940
941         let spacer = match same_line_body {
942             Some(ref body) if body == body_str => " ".to_owned(),
943             _ => format!("\n{}",
944                          offset.block_indent(context.config).to_string(context.config)),
945         };
946
947         Some(format!("{}{} =>{}{},",
948                      attr_str.trim_left(),
949                      pats_str,
950                      spacer,
951                      body_str))
952     }
953 }
954
955 // Takes two possible rewrites for the match arm body and chooses the "nicest".
956 fn match_arm_heuristic<'a>(former: Option<&'a str>, latter: Option<&'a str>) -> Option<&'a str> {
957     match (former, latter) {
958         (f @ Some(..), None) => f,
959         (Some(f), Some(l)) if f.chars().filter(|&c| c == '\n').count() <=
960                               l.chars().filter(|&c| c == '\n').count() => {
961             Some(f)
962         }
963         (_, l) => l,
964     }
965 }
966
967 // The `if ...` guard on a match arm.
968 fn rewrite_guard(context: &RewriteContext,
969                  guard: &Option<ptr::P<ast::Expr>>,
970                  width: usize,
971                  offset: Indent,
972                  // The amount of space used up on this line for the pattern in
973                  // the arm (excludes offset).
974                  pattern_width: usize)
975                  -> Option<String> {
976     if let &Some(ref guard) = guard {
977         // First try to fit the guard string on the same line as the pattern.
978         // 4 = ` if `, 5 = ` => {`
979         let overhead = pattern_width + 4 + 5;
980         if overhead < width {
981             let cond_str = guard.rewrite(context, width - overhead, offset + pattern_width + 4);
982             if let Some(cond_str) = cond_str {
983                 return Some(format!(" if {}", cond_str));
984             }
985         }
986
987         // Not enough space to put the guard after the pattern, try a newline.
988         let overhead = context.config.tab_spaces + 4 + 5;
989         if overhead < width {
990             let cond_str = guard.rewrite(context,
991                                          width - overhead,
992                                          offset.block_indent(context.config));
993             if let Some(cond_str) = cond_str {
994                 return Some(format!("\n{}if {}",
995                                     offset.block_indent(context.config).to_string(context.config),
996                                     cond_str));
997             }
998         }
999
1000         None
1001     } else {
1002         Some(String::new())
1003     }
1004 }
1005
1006 fn rewrite_pat_expr(context: &RewriteContext,
1007                     pat: Option<&ast::Pat>,
1008                     expr: &ast::Expr,
1009                     matcher: &str,
1010                     // Connecting piece between pattern and expression,
1011                     // *without* trailing space.
1012                     connector: &str,
1013                     width: usize,
1014                     offset: Indent)
1015                     -> Option<String> {
1016     let pat_offset = offset + matcher.len();
1017     let mut result = match pat {
1018         Some(pat) => {
1019             let pat_budget = try_opt!(width.checked_sub(connector.len() + matcher.len()));
1020             let pat_string = try_opt!(pat.rewrite(context, pat_budget, pat_offset));
1021             format!("{}{}{}", matcher, pat_string, connector)
1022         }
1023         None => String::new(),
1024     };
1025
1026     // Consider only the last line of the pat string.
1027     let extra_offset = extra_offset(&result, offset);
1028
1029     // The expression may (partionally) fit on the current line.
1030     if width > extra_offset + 1 {
1031         let spacer = if pat.is_some() {
1032             " "
1033         } else {
1034             ""
1035         };
1036
1037         let expr_rewrite = expr.rewrite(context,
1038                                         width - extra_offset - spacer.len(),
1039                                         offset + extra_offset + spacer.len());
1040
1041         if let Some(expr_string) = expr_rewrite {
1042             result.push_str(spacer);
1043             result.push_str(&expr_string);
1044             return Some(result);
1045         }
1046     }
1047
1048     // The expression won't fit on the current line, jump to next.
1049     result.push('\n');
1050     result.push_str(&pat_offset.to_string(context.config));
1051
1052     let expr_rewrite = expr.rewrite(context,
1053                                     context.config.max_width - pat_offset.width(),
1054                                     pat_offset);
1055     result.push_str(&&try_opt!(expr_rewrite));
1056
1057     Some(result)
1058 }
1059
1060 fn rewrite_string_lit(context: &RewriteContext,
1061                       span: Span,
1062                       width: usize,
1063                       offset: Indent)
1064                       -> Option<String> {
1065     if !context.config.format_strings {
1066         return Some(context.snippet(span));
1067     }
1068
1069     let fmt = StringFormat {
1070         opener: "\"",
1071         closer: "\"",
1072         line_start: " ",
1073         line_end: "\\",
1074         width: width,
1075         offset: offset,
1076         trim_end: false,
1077         config: context.config,
1078     };
1079
1080     let string_lit = context.snippet(span);
1081     let str_lit = &string_lit[1..string_lit.len() - 1]; // Remove the quote characters.
1082
1083     rewrite_string(str_lit, &fmt)
1084 }
1085
1086 pub fn rewrite_call<R>(context: &RewriteContext,
1087                        callee: &R,
1088                        args: &[ptr::P<ast::Expr>],
1089                        span: Span,
1090                        width: usize,
1091                        offset: Indent)
1092                        -> Option<String>
1093     where R: Rewrite
1094 {
1095     let closure = |callee_max_width| {
1096         rewrite_call_inner(context, callee, callee_max_width, args, span, width, offset)
1097     };
1098
1099     // 2 is for parens
1100     let max_width = try_opt!(width.checked_sub(2));
1101     binary_search(1, max_width, closure)
1102 }
1103
1104 fn rewrite_call_inner<R>(context: &RewriteContext,
1105                          callee: &R,
1106                          max_callee_width: usize,
1107                          args: &[ptr::P<ast::Expr>],
1108                          span: Span,
1109                          width: usize,
1110                          offset: Indent)
1111                          -> Result<String, Ordering>
1112     where R: Rewrite
1113 {
1114     let callee = callee.borrow();
1115     // FIXME using byte lens instead of char lens (and probably all over the
1116     // place too)
1117     let callee_str = match callee.rewrite(context, max_callee_width, offset) {
1118         Some(string) => {
1119             if !string.contains('\n') && string.len() > max_callee_width {
1120                 panic!("{:?} {}", string, max_callee_width);
1121             } else {
1122                 string
1123             }
1124         }
1125         None => return Err(Ordering::Greater),
1126     };
1127
1128     let span_lo = span_after(span, "(", context.codemap);
1129     let span = mk_sp(span_lo, span.hi);
1130
1131     let extra_offset = extra_offset(&callee_str, offset);
1132     // 2 is for parens.
1133     let remaining_width = match width.checked_sub(extra_offset + 2) {
1134         Some(str) => str,
1135         None => return Err(Ordering::Greater),
1136     };
1137     let offset = offset + extra_offset + 1;
1138     let block_indent = if args.len() == 1 {
1139         context.block_indent
1140     } else {
1141         offset
1142     };
1143     let inner_context = &RewriteContext { block_indent: block_indent, ..*context };
1144
1145     let items = itemize_list(context.codemap,
1146                              args.iter(),
1147                              ")",
1148                              |item| item.span.lo,
1149                              |item| item.span.hi,
1150                              |item| item.rewrite(&inner_context, remaining_width, offset),
1151                              span.lo,
1152                              span.hi);
1153
1154     let list_str = match format_fn_args(items, remaining_width, offset, context.config) {
1155         Some(str) => str,
1156         None => return Err(Ordering::Less),
1157     };
1158
1159     Ok(format!("{}({})", callee_str, list_str))
1160 }
1161
1162 fn rewrite_paren(context: &RewriteContext,
1163                  subexpr: &ast::Expr,
1164                  width: usize,
1165                  offset: Indent)
1166                  -> Option<String> {
1167     debug!("rewrite_paren, width: {}, offset: {:?}", width, offset);
1168     // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
1169     // paren on the same line as the subexpr.
1170     let subexpr_str = subexpr.rewrite(context, try_opt!(width.checked_sub(2)), offset + 1);
1171     debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1172     subexpr_str.map(|s| format!("({})", s))
1173 }
1174
1175 fn rewrite_struct_lit<'a>(context: &RewriteContext,
1176                           path: &ast::Path,
1177                           fields: &'a [ast::Field],
1178                           base: Option<&'a ast::Expr>,
1179                           span: Span,
1180                           width: usize,
1181                           offset: Indent)
1182                           -> Option<String> {
1183     debug!("rewrite_struct_lit: width {}, offset {:?}", width, offset);
1184     assert!(!fields.is_empty() || base.is_some());
1185
1186     enum StructLitField<'a> {
1187         Regular(&'a ast::Field),
1188         Base(&'a ast::Expr),
1189     }
1190
1191     // 2 = " {".len()
1192     let path_budget = try_opt!(width.checked_sub(2));
1193     let path_str = try_opt!(path.rewrite(context, path_budget, offset));
1194
1195     // Foo { a: Foo } - indent is +3, width is -5.
1196     let h_budget = width.checked_sub(path_str.len() + 5).unwrap_or(0);
1197     let (indent, v_budget) = match context.config.struct_lit_style {
1198         StructLitStyle::Visual => {
1199             (offset + path_str.len() + 3, h_budget)
1200         }
1201         StructLitStyle::Block => {
1202             // If we are all on one line, then we'll ignore the indent, and we
1203             // have a smaller budget.
1204             let indent = context.block_indent.block_indent(context.config);
1205             let v_budget = context.config.max_width.checked_sub(indent.width()).unwrap_or(0);
1206             (indent, v_budget)
1207         }
1208     };
1209
1210     let field_iter = fields.into_iter()
1211                            .map(StructLitField::Regular)
1212                            .chain(base.into_iter().map(StructLitField::Base));
1213
1214     let inner_context = &RewriteContext { block_indent: indent, ..*context };
1215
1216     let items = itemize_list(context.codemap,
1217                              field_iter,
1218                              "}",
1219                              |item| {
1220                                  match *item {
1221                                      StructLitField::Regular(ref field) => field.span.lo,
1222                                      StructLitField::Base(ref expr) => {
1223                                          let last_field_hi = fields.last().map_or(span.lo,
1224                                                                                   |field| {
1225                                                                                       field.span.hi
1226                                                                                   });
1227                                          let snippet = context.snippet(mk_sp(last_field_hi,
1228                                                                              expr.span.lo));
1229                                          let pos = snippet.find_uncommented("..").unwrap();
1230                                          last_field_hi + BytePos(pos as u32)
1231                                      }
1232                                  }
1233                              },
1234                              |item| {
1235                                  match *item {
1236                                      StructLitField::Regular(ref field) => field.span.hi,
1237                                      StructLitField::Base(ref expr) => expr.span.hi,
1238                                  }
1239                              },
1240                              |item| {
1241                                  match *item {
1242                                      StructLitField::Regular(ref field) => {
1243                                          rewrite_field(inner_context, &field, v_budget, indent)
1244                                      }
1245                                      StructLitField::Base(ref expr) => {
1246                                          // 2 = ..
1247                                          expr.rewrite(inner_context,
1248                                                       try_opt!(v_budget.checked_sub(2)),
1249                                                       indent + 2)
1250                                              .map(|s| format!("..{}", s))
1251                                      }
1252                                  }
1253                              },
1254                              span_after(span, "{", context.codemap),
1255                              span.hi);
1256     let item_vec = items.collect::<Vec<_>>();
1257
1258     let tactic = {
1259         let mut prelim_tactic = match (context.config.struct_lit_style, fields.len()) {
1260             (StructLitStyle::Visual, 1) => ListTactic::HorizontalVertical,
1261             _ => context.config.struct_lit_multiline_style.to_list_tactic(),
1262         };
1263
1264         if prelim_tactic == ListTactic::HorizontalVertical && fields.len() > 1 {
1265             prelim_tactic = ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width);
1266         };
1267
1268         definitive_tactic(&item_vec, prelim_tactic, h_budget)
1269     };
1270
1271     let budget = match tactic {
1272         DefinitiveListTactic::Horizontal => h_budget,
1273         _ => v_budget,
1274     };
1275
1276     let fmt = ListFormatting {
1277         tactic: tactic,
1278         separator: ",",
1279         trailing_separator: if base.is_some() {
1280             SeparatorTactic::Never
1281         } else {
1282             context.config.struct_lit_trailing_comma
1283         },
1284         indent: indent,
1285         width: budget,
1286         ends_with_newline: false,
1287         config: context.config,
1288     };
1289     let fields_str = try_opt!(write_list(&item_vec, &fmt));
1290
1291     let format_on_newline = || {
1292         let inner_indent = context.block_indent
1293                                   .block_indent(context.config)
1294                                   .to_string(context.config);
1295         let outer_indent = context.block_indent.to_string(context.config);
1296         Some(format!("{} {{\n{}{}\n{}}}",
1297                      path_str,
1298                      inner_indent,
1299                      fields_str,
1300                      outer_indent))
1301     };
1302
1303     match (context.config.struct_lit_style,
1304            context.config.struct_lit_multiline_style) {
1305         (StructLitStyle::Block, _) if fields_str.contains('\n') || fields_str.len() > h_budget =>
1306             format_on_newline(),
1307         (StructLitStyle::Block, MultilineStyle::ForceMulti) => format_on_newline(),
1308         _ => Some(format!("{} {{ {} }}", path_str, fields_str)),
1309     }
1310
1311     // FIXME if context.config.struct_lit_style == Visual, but we run out
1312     // of space, we should fall back to BlockIndent.
1313 }
1314
1315 fn rewrite_field(context: &RewriteContext,
1316                  field: &ast::Field,
1317                  width: usize,
1318                  offset: Indent)
1319                  -> Option<String> {
1320     let name = &field.ident.node.to_string();
1321     let overhead = name.len() + 2;
1322     let expr = field.expr.rewrite(context,
1323                                   try_opt!(width.checked_sub(overhead)),
1324                                   offset + overhead);
1325     expr.map(|s| format!("{}: {}", name, s))
1326 }
1327
1328 fn rewrite_tuple_lit(context: &RewriteContext,
1329                      items: &[ptr::P<ast::Expr>],
1330                      span: Span,
1331                      width: usize,
1332                      offset: Indent)
1333                      -> Option<String> {
1334     debug!("rewrite_tuple_lit: width: {}, offset: {:?}", width, offset);
1335     let indent = offset + 1;
1336     // In case of length 1, need a trailing comma
1337     if items.len() == 1 {
1338         // 3 = "(" + ",)"
1339         let budget = try_opt!(width.checked_sub(3));
1340         return items[0].rewrite(context, budget, indent).map(|s| format!("({},)", s));
1341     }
1342
1343     let items = itemize_list(context.codemap,
1344                              items.iter(),
1345                              ")",
1346                              |item| item.span.lo,
1347                              |item| item.span.hi,
1348                              |item| {
1349                                  let inner_width = context.config.max_width - indent.width() - 1;
1350                                  item.rewrite(context, inner_width, indent)
1351                              },
1352                              span.lo + BytePos(1), // Remove parens
1353                              span.hi - BytePos(1));
1354     let budget = try_opt!(width.checked_sub(2));
1355     let list_str = try_opt!(format_fn_args(items, budget, indent, context.config));
1356
1357     Some(format!("({})", list_str))
1358 }
1359
1360 fn rewrite_binary_op(context: &RewriteContext,
1361                      op: &ast::BinOp,
1362                      lhs: &ast::Expr,
1363                      rhs: &ast::Expr,
1364                      width: usize,
1365                      offset: Indent)
1366                      -> Option<String> {
1367     // FIXME: format comments between operands and operator
1368
1369     let operator_str = context.snippet(op.span);
1370
1371     // Get "full width" rhs and see if it fits on the current line. This
1372     // usually works fairly well since it tends to place operands of
1373     // operations with high precendence close together.
1374     let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
1375
1376     // Second condition is needed in case of line break not caused by a
1377     // shortage of space, but by end-of-line comments, for example.
1378     // Note that this is non-conservative, but its just to see if it's even
1379     // worth trying to put everything on one line.
1380     if rhs_result.len() + 2 + operator_str.len() < width && !rhs_result.contains('\n') {
1381         // 1 = space between lhs expr and operator
1382         if let Some(mut result) = lhs.rewrite(context, width - 1 - operator_str.len(), offset) {
1383             result.push(' ');
1384             result.push_str(&operator_str);
1385             result.push(' ');
1386
1387             let remaining_width = width.checked_sub(last_line_width(&result)).unwrap_or(0);
1388
1389             if rhs_result.len() <= remaining_width {
1390                 result.push_str(&rhs_result);
1391                 return Some(result);
1392             }
1393
1394             if let Some(rhs_result) = rhs.rewrite(context, remaining_width, offset + result.len()) {
1395                 if rhs_result.len() <= remaining_width {
1396                     result.push_str(&rhs_result);
1397                     return Some(result);
1398                 }
1399             }
1400         }
1401     }
1402
1403     // We have to use multiple lines.
1404
1405     // Re-evaluate the lhs because we have more space now:
1406     let budget = try_opt!(context.config
1407                                  .max_width
1408                                  .checked_sub(offset.width() + 1 + operator_str.len()));
1409     Some(format!("{} {}\n{}{}",
1410                  try_opt!(lhs.rewrite(context, budget, offset)),
1411                  operator_str,
1412                  offset.to_string(context.config),
1413                  rhs_result))
1414 }
1415
1416 fn rewrite_unary_prefix(context: &RewriteContext,
1417                         prefix: &str,
1418                         expr: &ast::Expr,
1419                         width: usize,
1420                         offset: Indent)
1421                         -> Option<String> {
1422     expr.rewrite(context,
1423                  try_opt!(width.checked_sub(prefix.len())),
1424                  offset + prefix.len())
1425         .map(|r| format!("{}{}", prefix, r))
1426 }
1427
1428 fn rewrite_unary_op(context: &RewriteContext,
1429                     op: &ast::UnOp,
1430                     expr: &ast::Expr,
1431                     width: usize,
1432                     offset: Indent)
1433                     -> Option<String> {
1434     // For some reason, an UnOp is not spanned like BinOp!
1435     let operator_str = match *op {
1436         ast::UnOp::UnDeref => "*",
1437         ast::UnOp::UnNot => "!",
1438         ast::UnOp::UnNeg => "-",
1439     };
1440     rewrite_unary_prefix(context, operator_str, expr, width, offset)
1441 }
1442
1443 fn rewrite_assignment(context: &RewriteContext,
1444                       lhs: &ast::Expr,
1445                       rhs: &ast::Expr,
1446                       op: Option<&ast::BinOp>,
1447                       width: usize,
1448                       offset: Indent)
1449                       -> Option<String> {
1450     let operator_str = match op {
1451         Some(op) => context.snippet(op.span),
1452         None => "=".to_owned(),
1453     };
1454
1455     // 1 = space between lhs and operator.
1456     let max_width = try_opt!(width.checked_sub(operator_str.len() + 1));
1457     let lhs_str = format!("{} {}",
1458                           try_opt!(lhs.rewrite(context, max_width, offset)),
1459                           operator_str);
1460
1461     rewrite_assign_rhs(&context, lhs_str, rhs, width, offset)
1462 }
1463
1464 // The left hand side must contain everything up to, and including, the
1465 // assignment operator.
1466 pub fn rewrite_assign_rhs<S: Into<String>>(context: &RewriteContext,
1467                                            lhs: S,
1468                                            ex: &ast::Expr,
1469                                            width: usize,
1470                                            offset: Indent)
1471                                            -> Option<String> {
1472     let mut result = lhs.into();
1473
1474     // 1 = space between operator and rhs.
1475     let max_width = try_opt!(width.checked_sub(result.len() + 1));
1476     let rhs = ex.rewrite(&context, max_width, offset + result.len() + 1);
1477
1478     match rhs {
1479         Some(new_str) => {
1480             result.push(' ');
1481             result.push_str(&new_str)
1482         }
1483         None => {
1484             // Expression did not fit on the same line as the identifier. Retry
1485             // on the next line.
1486             let new_offset = offset.block_indent(context.config);
1487             result.push_str(&format!("\n{}", new_offset.to_string(context.config)));
1488
1489             // FIXME: we probably should related max_width to width instead of config.max_width
1490             // where is the 1 coming from anyway?
1491             let max_width = try_opt!(context.config.max_width.checked_sub(new_offset.width() + 1));
1492             let rhs_indent = Indent::new(context.config.tab_spaces, 0);
1493             let overflow_context = context.overflow_context(rhs_indent);
1494             let rhs = ex.rewrite(&overflow_context, max_width, new_offset);
1495
1496             result.push_str(&&try_opt!(rhs));
1497         }
1498     }
1499
1500     Some(result)
1501 }
1502
1503 fn rewrite_expr_addrof(context: &RewriteContext,
1504                        mutability: ast::Mutability,
1505                        expr: &ast::Expr,
1506                        width: usize,
1507                        offset: Indent)
1508                        -> Option<String> {
1509     let operator_str = match mutability {
1510         ast::Mutability::MutImmutable => "&",
1511         ast::Mutability::MutMutable => "&mut ",
1512     };
1513     rewrite_unary_prefix(context, operator_str, expr, width, offset)
1514 }