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