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