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