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