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