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