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