]> git.lizzy.rs Git - rust.git/blob - src/expr.rs
0c30aaf3f6fec3d2f69e4265aa787705ae4f6203
[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, trimmed_last_line_width};
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             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, _) |
501             ast::StmtKind::Semi(ref ex, _) => {
502                 let suffix = if semicolon_for_stmt(self) {
503                     ";"
504                 } else {
505                     ""
506                 };
507
508                 ex.rewrite(context,
509                            context.config.max_width - offset.width() - suffix.len(),
510                            offset)
511                   .map(|s| s + suffix)
512             }
513             ast::StmtKind::Mac(..) => None,
514         };
515         result.and_then(|res| recover_comment_removed(res, self.span, context, _width, offset))
516     }
517 }
518
519 // Abstraction over for, while and loop expressions
520 struct Loop<'a> {
521     cond: Option<&'a ast::Expr>,
522     block: &'a ast::Block,
523     label: Option<ast::Ident>,
524     pat: Option<&'a ast::Pat>,
525     keyword: &'a str,
526     matcher: &'a str,
527     connector: &'a str,
528 }
529
530 impl<'a> Loop<'a> {
531     fn new_loop(block: &'a ast::Block, label: Option<ast::Ident>) -> Loop<'a> {
532         Loop {
533             cond: None,
534             block: block,
535             label: label,
536             pat: None,
537             keyword: "loop",
538             matcher: "",
539             connector: "",
540         }
541     }
542
543     fn new_while(pat: Option<&'a ast::Pat>,
544                  cond: &'a ast::Expr,
545                  block: &'a ast::Block,
546                  label: Option<ast::Ident>)
547                  -> Loop<'a> {
548         Loop {
549             cond: Some(cond),
550             block: block,
551             label: label,
552             pat: pat,
553             keyword: "while ",
554             matcher: match pat {
555                 Some(..) => "let ",
556                 None => "",
557             },
558             connector: " =",
559         }
560     }
561
562     fn new_for(pat: &'a ast::Pat,
563                cond: &'a ast::Expr,
564                block: &'a ast::Block,
565                label: Option<ast::Ident>)
566                -> Loop<'a> {
567         Loop {
568             cond: Some(cond),
569             block: block,
570             label: label,
571             pat: Some(pat),
572             keyword: "for ",
573             matcher: "",
574             connector: " in",
575         }
576     }
577 }
578
579 impl<'a> Rewrite for Loop<'a> {
580     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
581         let label_string = rewrite_label(self.label);
582         // 2 = " {".len()
583         let inner_width = try_opt!(width.checked_sub(self.keyword.len() + 2 + label_string.len()));
584         let inner_offset = offset + self.keyword.len() + label_string.len();
585
586         let pat_expr_string = match self.cond {
587             Some(cond) => {
588                 try_opt!(rewrite_pat_expr(context,
589                                           self.pat,
590                                           cond,
591                                           self.matcher,
592                                           self.connector,
593                                           inner_width,
594                                           inner_offset))
595             }
596             None => String::new(),
597         };
598
599         // FIXME: this drops any comment between "loop" and the block.
600         self.block
601             .rewrite(context, width, offset)
602             .map(|result| {
603                 format!("{}{}{} {}",
604                         label_string,
605                         self.keyword,
606                         pat_expr_string,
607                         result)
608             })
609     }
610 }
611
612 fn rewrite_label(label: Option<ast::Ident>) -> String {
613     match label {
614         Some(ident) => format!("{}: ", ident),
615         None => "".to_owned(),
616     }
617 }
618
619 fn extract_comment(span: Span,
620                    context: &RewriteContext,
621                    offset: Indent,
622                    width: usize)
623                    -> Option<String> {
624     let comment_str = context.snippet(span);
625     if contains_comment(&comment_str) {
626         let comment = try_opt!(rewrite_comment(comment_str.trim(),
627                                                false,
628                                                width,
629                                                offset,
630                                                context.config));
631         Some(format!("\n{indent}{}\n{indent}",
632                      comment,
633                      indent = offset.to_string(context.config)))
634     } else {
635         None
636     }
637 }
638
639 // Rewrites if-else blocks. If let Some(_) = pat, the expression is
640 // treated as an if-let-else expression.
641 fn rewrite_if_else(context: &RewriteContext,
642                    cond: &ast::Expr,
643                    if_block: &ast::Block,
644                    else_block_opt: Option<&ast::Expr>,
645                    span: Span,
646                    pat: Option<&ast::Pat>,
647                    width: usize,
648                    offset: Indent,
649                    allow_single_line: bool)
650                    -> Option<String> {
651     // 3 = "if ", 2 = " {"
652     let pat_expr_string = try_opt!(rewrite_pat_expr(context,
653                                                     pat,
654                                                     cond,
655                                                     "let ",
656                                                     " =",
657                                                     try_opt!(width.checked_sub(3 + 2)),
658                                                     offset + 3));
659
660     // Try to format if-else on single line.
661     if allow_single_line && context.config.single_line_if_else {
662         let trial = single_line_if_else(context, &pat_expr_string, if_block, else_block_opt, width);
663
664         if trial.is_some() {
665             return trial;
666         }
667     }
668
669     let if_block_string = try_opt!(if_block.rewrite(context, width, offset));
670
671     let between_if_cond = mk_sp(context.codemap.span_after(span, "if"),
672                                 pat.map_or(cond.span.lo,
673                                            |_| context.codemap.span_before(span, "let")));
674
675     let between_if_cond_comment = extract_comment(between_if_cond, &context, offset, width);
676
677     let after_cond_comment = extract_comment(mk_sp(cond.span.hi, if_block.span.lo),
678                                              context,
679                                              offset,
680                                              width);
681
682     let mut result = format!("if{}{}{}{}",
683                              between_if_cond_comment.as_ref().map_or(" ", |str| &**str),
684                              pat_expr_string,
685                              after_cond_comment.as_ref().map_or(" ", |str| &**str),
686                              if_block_string);
687
688     if let Some(else_block) = else_block_opt {
689         let rewrite = match else_block.node {
690             // If the else expression is another if-else expression, prevent it
691             // from being formatted on a single line.
692             ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
693                 rewrite_if_else(context,
694                                 cond,
695                                 if_block,
696                                 next_else_block.as_ref().map(|e| &**e),
697                                 mk_sp(else_block.span.lo, span.hi),
698                                 Some(pat),
699                                 width,
700                                 offset,
701                                 false)
702             }
703             ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
704                 rewrite_if_else(context,
705                                 cond,
706                                 if_block,
707                                 next_else_block.as_ref().map(|e| &**e),
708                                 mk_sp(else_block.span.lo, span.hi),
709                                 None,
710                                 width,
711                                 offset,
712                                 false)
713             }
714             _ => else_block.rewrite(context, width, offset),
715         };
716
717         let between_if_else_block = mk_sp(if_block.span.hi,
718                                           context.codemap.span_before(mk_sp(if_block.span.hi,
719                                                                             else_block.span.lo),
720                                                                       "else"));
721         let between_if_else_block_comment = extract_comment(between_if_else_block,
722                                                             &context,
723                                                             offset,
724                                                             width);
725
726         let after_else = mk_sp(context.codemap
727                                       .span_after(mk_sp(if_block.span.hi, else_block.span.lo),
728                                                   "else"),
729                                else_block.span.lo);
730         let after_else_comment = extract_comment(after_else, &context, offset, width);
731
732         try_opt!(write!(&mut result,
733                         "{}else{}",
734                         between_if_else_block_comment.as_ref().map_or(" ", |str| &**str),
735                         after_else_comment.as_ref().map_or(" ", |str| &**str))
736                      .ok());
737         result.push_str(&&try_opt!(rewrite));
738     }
739
740     Some(result)
741 }
742
743 fn single_line_if_else(context: &RewriteContext,
744                        pat_expr_str: &str,
745                        if_node: &ast::Block,
746                        else_block_opt: Option<&ast::Expr>,
747                        width: usize)
748                        -> Option<String> {
749     let else_block = try_opt!(else_block_opt);
750     let fixed_cost = "if  {  } else {  }".len();
751
752     if let ast::ExprKind::Block(ref else_node) = else_block.node {
753         if !is_simple_block(if_node, context.codemap) ||
754            !is_simple_block(else_node, context.codemap) || pat_expr_str.contains('\n') {
755             return None;
756         }
757
758         let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
759         let if_expr = if_node.expr.as_ref().unwrap();
760         let if_str = try_opt!(if_expr.rewrite(context, new_width, Indent::empty()));
761
762         let new_width = try_opt!(new_width.checked_sub(if_str.len()));
763         let else_expr = else_node.expr.as_ref().unwrap();
764         let else_str = try_opt!(else_expr.rewrite(context, new_width, Indent::empty()));
765
766         // FIXME: this check shouldn't be necessary. Rewrites should either fail
767         // or wrap to a newline when the object does not fit the width.
768         let fits_line = fixed_cost + pat_expr_str.len() + if_str.len() + else_str.len() <= width;
769
770         if fits_line && !if_str.contains('\n') && !else_str.contains('\n') {
771             return Some(format!("if {} {{ {} }} else {{ {} }}",
772                                 pat_expr_str,
773                                 if_str,
774                                 else_str));
775         }
776     }
777
778     None
779 }
780
781 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
782     let snippet = codemap.span_to_snippet(block.span).unwrap();
783     contains_comment(&snippet)
784 }
785
786 // Checks that a block contains no statements, an expression and no comments.
787 // FIXME: incorrectly returns false when comment is contained completely within
788 // the expression.
789 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
790     block.stmts.is_empty() && block.expr.is_some() && !block_contains_comment(block, codemap)
791 }
792
793 /// Checks whether a block contains at most one statement or expression, and no comments.
794 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
795     (block.stmts.is_empty() || (block.stmts.len() == 1 && block.expr.is_none())) &&
796     !block_contains_comment(block, codemap)
797 }
798
799 /// Checks whether a block contains no statements, expressions, or comments.
800 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
801     block.stmts.is_empty() && block.expr.is_none() && !block_contains_comment(block, codemap)
802 }
803
804 fn is_unsafe_block(block: &ast::Block) -> bool {
805     if let ast::BlockCheckMode::Unsafe(..) = block.rules {
806         true
807     } else {
808         false
809     }
810 }
811
812 // inter-match-arm-comment-rules:
813 //  - all comments following a match arm before the start of the next arm
814 //    are about the second arm
815 fn rewrite_match_arm_comment(context: &RewriteContext,
816                              missed_str: &str,
817                              width: usize,
818                              arm_indent: Indent,
819                              arm_indent_str: &str)
820                              -> Option<String> {
821     // The leading "," is not part of the arm-comment
822     let missed_str = match missed_str.find_uncommented(",") {
823         Some(n) => &missed_str[n + 1..],
824         None => &missed_str[..],
825     };
826
827     let mut result = String::new();
828     // any text not preceeded by a newline is pushed unmodified to the block
829     let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
830     result.push_str(&missed_str[..first_brk]);
831     let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
832
833     let first = missed_str.find(|c: char| !c.is_whitespace()).unwrap_or(missed_str.len());
834     if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
835         // Excessive vertical whitespace before comment should be preserved
836         // TODO handle vertical whitespace better
837         result.push('\n');
838     }
839     let missed_str = missed_str[first..].trim();
840     if !missed_str.is_empty() {
841         let comment = try_opt!(rewrite_comment(&missed_str,
842                                                false,
843                                                width,
844                                                arm_indent,
845                                                context.config));
846         result.push('\n');
847         result.push_str(arm_indent_str);
848         result.push_str(&comment);
849     }
850
851     Some(result)
852 }
853
854 fn rewrite_match(context: &RewriteContext,
855                  cond: &ast::Expr,
856                  arms: &[ast::Arm],
857                  width: usize,
858                  offset: Indent,
859                  span: Span)
860                  -> Option<String> {
861     if arms.is_empty() {
862         return None;
863     }
864
865     // `match `cond` {`
866     let cond_budget = try_opt!(width.checked_sub(8));
867     let cond_str = try_opt!(cond.rewrite(context, cond_budget, offset + 6));
868     let mut result = format!("match {} {{", cond_str);
869
870     let nested_context = context.nested_context();
871     let arm_indent = nested_context.block_indent;
872     let arm_indent_str = arm_indent.to_string(context.config);
873
874     let open_brace_pos = context.codemap
875                                 .span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])), "{");
876
877     for (i, arm) in arms.iter().enumerate() {
878         // Make sure we get the stuff between arms.
879         let missed_str = if i == 0 {
880             context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
881         } else {
882             context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
883         };
884         let comment = try_opt!(rewrite_match_arm_comment(context,
885                                                          &missed_str,
886                                                          width,
887                                                          arm_indent,
888                                                          &arm_indent_str));
889         result.push_str(&comment);
890         result.push('\n');
891         result.push_str(&arm_indent_str);
892
893         let arm_str = arm.rewrite(&nested_context,
894                                   context.config.max_width - arm_indent.width(),
895                                   arm_indent);
896         if let Some(ref arm_str) = arm_str {
897             result.push_str(arm_str);
898         } else {
899             // We couldn't format the arm, just reproduce the source.
900             let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
901             result.push_str(&snippet);
902             result.push_str(arm_comma(&context.config, &arm, &arm.body));
903         }
904     }
905     // BytePos(1) = closing match brace.
906     let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
907     let last_comment = context.snippet(last_span);
908     let comment = try_opt!(rewrite_match_arm_comment(context,
909                                                      &last_comment,
910                                                      width,
911                                                      arm_indent,
912                                                      &arm_indent_str));
913     result.push_str(&comment);
914     result.push('\n');
915     result.push_str(&context.block_indent.to_string(context.config));
916     result.push('}');
917     Some(result)
918 }
919
920 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
921     let &ast::Arm { ref attrs, ref pats, .. } = arm;
922     if !attrs.is_empty() {
923         return attrs[0].span.lo;
924     }
925
926     pats[0].span.lo
927 }
928
929 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
930     arm.body.span.hi
931 }
932
933 fn arm_comma(config: &Config, arm: &ast::Arm, body: &ast::Expr) -> &'static str {
934     if !config.match_wildcard_trailing_comma {
935         if arm.pats.len() == 1 && arm.pats[0].node == ast::PatKind::Wild && arm.guard.is_none() {
936             return "";
937         }
938     }
939
940     if config.match_block_trailing_comma {
941         ","
942     } else if let ast::ExprKind::Block(ref block) = body.node {
943         if let ast::BlockCheckMode::Default = block.rules {
944             ""
945         } else {
946             ","
947         }
948     } else {
949         ","
950     }
951 }
952
953 // Match arms.
954 impl Rewrite for ast::Arm {
955     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
956         let &ast::Arm { ref attrs, ref pats, ref guard, ref body } = self;
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 all_simple = pat_strs.iter().all(|p| pat_is_simple(&p));
984         let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
985         let fmt = ListFormatting {
986             tactic: if all_simple {
987                 DefinitiveListTactic::Mixed
988             } else {
989                 DefinitiveListTactic::Vertical
990             },
991             separator: " |",
992             trailing_separator: SeparatorTactic::Never,
993             indent: offset,
994             width: pat_budget,
995             ends_with_newline: false,
996             config: context.config,
997         };
998         let pats_str = try_opt!(write_list(items, &fmt));
999
1000         let budget = if pats_str.contains('\n') {
1001             context.config.max_width - offset.width()
1002         } else {
1003             width
1004         };
1005
1006         let guard_str = try_opt!(rewrite_guard(context,
1007                                                guard,
1008                                                budget,
1009                                                offset,
1010                                                trimmed_last_line_width(&pats_str)));
1011
1012         let pats_str = format!("{}{}", pats_str, guard_str);
1013         // Where the next text can start.
1014         let mut line_start = last_line_width(&pats_str);
1015         if !pats_str.contains('\n') {
1016             line_start += offset.width();
1017         }
1018
1019         let body = match **body {
1020             ast::Expr { node: ast::ExprKind::Block(ref block), .. }
1021                 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) &&
1022                    context.config.wrap_match_arms => block.expr.as_ref().map(|e| &**e).unwrap(),
1023             ref x => x,
1024         };
1025
1026         let comma = arm_comma(&context.config, self, body);
1027
1028         // Let's try and get the arm body on the same line as the condition.
1029         // 4 = ` => `.len()
1030         if context.config.max_width > line_start + comma.len() + 4 {
1031             let budget = context.config.max_width - line_start - comma.len() - 4;
1032             let offset = Indent::new(offset.block_indent, line_start + 4 - offset.block_indent);
1033             let rewrite = nop_block_collapse(body.rewrite(context, budget, offset), budget);
1034             let is_block = if let ast::ExprKind::Block(..) = body.node {
1035                 true
1036             } else {
1037                 false
1038             };
1039
1040             match rewrite {
1041                 Some(ref body_str) if !body_str.contains('\n') || !context.config.wrap_match_arms ||
1042                                       is_block => {
1043                     return Some(format!("{}{} => {}{}",
1044                                         attr_str.trim_left(),
1045                                         pats_str,
1046                                         body_str,
1047                                         comma));
1048                 }
1049                 _ => {}
1050             }
1051         }
1052
1053         // FIXME: we're doing a second rewrite of the expr; This may not be
1054         // necessary.
1055         let body_budget = try_opt!(width.checked_sub(context.config.tab_spaces));
1056         let indent = context.block_indent.block_indent(context.config);
1057         let inner_context = &RewriteContext { block_indent: indent, ..*context };
1058         let next_line_body = try_opt!(nop_block_collapse(body.rewrite(inner_context,
1059                                                                       body_budget,
1060                                                                       indent),
1061                                                          body_budget));
1062         let indent_str = offset.block_indent(context.config).to_string(context.config);
1063         let (body_prefix, body_suffix) = if context.config.wrap_match_arms {
1064             if context.config.match_block_trailing_comma {
1065                 (" {", "},")
1066             } else {
1067                 (" {", "}")
1068             }
1069         } else {
1070             ("", "")
1071         };
1072
1073         Some(format!("{}{} =>{}\n{}{}\n{}{}",
1074                      attr_str.trim_left(),
1075                      pats_str,
1076                      body_prefix,
1077                      indent_str,
1078                      next_line_body,
1079                      offset.to_string(context.config),
1080                      body_suffix))
1081     }
1082 }
1083
1084 // A pattern is simple if it is very short or it is short-ish and just a path.
1085 // E.g. `Foo::Bar` is simple, but `Foo(..)` is not.
1086 fn pat_is_simple(pat_str: &str) -> bool {
1087     pat_str.len() <= 16 ||
1088     (pat_str.len() <= 24 && pat_str.chars().all(|c| c.is_alphabetic() || c == ':'))
1089 }
1090
1091 // The `if ...` guard on a match arm.
1092 fn rewrite_guard(context: &RewriteContext,
1093                  guard: &Option<ptr::P<ast::Expr>>,
1094                  width: usize,
1095                  offset: Indent,
1096                  // The amount of space used up on this line for the pattern in
1097                  // the arm (excludes offset).
1098                  pattern_width: usize)
1099                  -> Option<String> {
1100     if let Some(ref guard) = *guard {
1101         // First try to fit the guard string on the same line as the pattern.
1102         // 4 = ` if `, 5 = ` => {`
1103         let overhead = pattern_width + 4 + 5;
1104         if overhead < width {
1105             let cond_str = guard.rewrite(context, width - overhead, offset + pattern_width + 4);
1106             if let Some(cond_str) = cond_str {
1107                 return Some(format!(" if {}", cond_str));
1108             }
1109         }
1110
1111         // Not enough space to put the guard after the pattern, try a newline.
1112         let overhead = offset.block_indent(context.config).width() + 4 + 5;
1113         if overhead < width {
1114             let cond_str = guard.rewrite(context,
1115                                          width - overhead,
1116                                          // 3 == `if `
1117                                          offset.block_indent(context.config) + 3);
1118             if let Some(cond_str) = cond_str {
1119                 return Some(format!("\n{}if {}",
1120                                     offset.block_indent(context.config).to_string(context.config),
1121                                     cond_str));
1122             }
1123         }
1124
1125         None
1126     } else {
1127         Some(String::new())
1128     }
1129 }
1130
1131 fn rewrite_pat_expr(context: &RewriteContext,
1132                     pat: Option<&ast::Pat>,
1133                     expr: &ast::Expr,
1134                     matcher: &str,
1135                     // Connecting piece between pattern and expression,
1136                     // *without* trailing space.
1137                     connector: &str,
1138                     width: usize,
1139                     offset: Indent)
1140                     -> Option<String> {
1141     let pat_offset = offset + matcher.len();
1142     let mut result = match pat {
1143         Some(pat) => {
1144             let pat_budget = try_opt!(width.checked_sub(connector.len() + matcher.len()));
1145             let pat_string = try_opt!(pat.rewrite(context, pat_budget, pat_offset));
1146             format!("{}{}{}", matcher, pat_string, connector)
1147         }
1148         None => String::new(),
1149     };
1150
1151     // Consider only the last line of the pat string.
1152     let extra_offset = extra_offset(&result, offset);
1153
1154     // The expression may (partionally) fit on the current line.
1155     if width > extra_offset + 1 {
1156         let spacer = if pat.is_some() {
1157             " "
1158         } else {
1159             ""
1160         };
1161
1162         let expr_rewrite = expr.rewrite(context,
1163                                         width - extra_offset - spacer.len(),
1164                                         offset + extra_offset + spacer.len());
1165
1166         if let Some(expr_string) = expr_rewrite {
1167             result.push_str(spacer);
1168             result.push_str(&expr_string);
1169             return Some(result);
1170         }
1171     }
1172
1173     // The expression won't fit on the current line, jump to next.
1174     result.push('\n');
1175     result.push_str(&pat_offset.to_string(context.config));
1176
1177     let expr_rewrite = expr.rewrite(context,
1178                                     context.config.max_width - pat_offset.width(),
1179                                     pat_offset);
1180     result.push_str(&&try_opt!(expr_rewrite));
1181
1182     Some(result)
1183 }
1184
1185 fn rewrite_string_lit(context: &RewriteContext,
1186                       span: Span,
1187                       width: usize,
1188                       offset: Indent)
1189                       -> Option<String> {
1190     let string_lit = context.snippet(span);
1191
1192     if !context.config.format_strings && !context.config.force_format_strings {
1193         return Some(string_lit);
1194     }
1195
1196     if !context.config.force_format_strings &&
1197        !string_requires_rewrite(context, span, &string_lit, width, offset) {
1198         return Some(string_lit);
1199     }
1200
1201     let fmt = StringFormat {
1202         opener: "\"",
1203         closer: "\"",
1204         line_start: " ",
1205         line_end: "\\",
1206         width: width,
1207         offset: offset,
1208         trim_end: false,
1209         config: context.config,
1210     };
1211
1212     // Remove the quote characters.
1213     let str_lit = &string_lit[1..string_lit.len() - 1];
1214
1215     rewrite_string(str_lit, &fmt)
1216 }
1217
1218 fn string_requires_rewrite(context: &RewriteContext,
1219                            span: Span,
1220                            string: &str,
1221                            width: usize,
1222                            offset: Indent)
1223                            -> bool {
1224     if context.codemap.lookup_char_pos(span.lo).col.0 != offset.width() {
1225         return true;
1226     }
1227
1228     for (i, line) in string.lines().enumerate() {
1229         if i == 0 {
1230             if line.len() > width {
1231                 return true;
1232             }
1233         } else {
1234             if line.len() > width + offset.width() {
1235                 return true;
1236             }
1237         }
1238     }
1239
1240     false
1241 }
1242
1243 pub fn rewrite_call<R>(context: &RewriteContext,
1244                        callee: &R,
1245                        args: &[ptr::P<ast::Expr>],
1246                        span: Span,
1247                        width: usize,
1248                        offset: Indent)
1249                        -> Option<String>
1250     where R: Rewrite
1251 {
1252     let closure = |callee_max_width| {
1253         rewrite_call_inner(context, callee, callee_max_width, args, span, width, offset)
1254     };
1255
1256     // 2 is for parens
1257     let max_width = try_opt!(width.checked_sub(2));
1258     binary_search(1, max_width, closure)
1259 }
1260
1261 fn rewrite_call_inner<R>(context: &RewriteContext,
1262                          callee: &R,
1263                          max_callee_width: usize,
1264                          args: &[ptr::P<ast::Expr>],
1265                          span: Span,
1266                          width: usize,
1267                          offset: Indent)
1268                          -> Result<String, Ordering>
1269     where R: Rewrite
1270 {
1271     let callee = callee.borrow();
1272     // FIXME using byte lens instead of char lens (and probably all over the
1273     // place too)
1274     let callee_str = match callee.rewrite(context, max_callee_width, offset) {
1275         Some(string) => {
1276             if !string.contains('\n') && string.len() > max_callee_width {
1277                 panic!("{:?} {}", string, max_callee_width);
1278             } else {
1279                 string
1280             }
1281         }
1282         None => return Err(Ordering::Greater),
1283     };
1284
1285     let span_lo = context.codemap.span_after(span, "(");
1286     let span = mk_sp(span_lo, span.hi);
1287
1288     let extra_offset = extra_offset(&callee_str, offset);
1289     // 2 is for parens.
1290     let remaining_width = match width.checked_sub(extra_offset + 2) {
1291         Some(str) => str,
1292         None => return Err(Ordering::Greater),
1293     };
1294     let offset = offset + extra_offset + 1;
1295     let arg_count = args.len();
1296     let block_indent = if arg_count == 1 {
1297         context.block_indent
1298     } else {
1299         offset
1300     };
1301     let inner_context = &RewriteContext { block_indent: block_indent, ..*context };
1302
1303     let items = itemize_list(context.codemap,
1304                              args.iter(),
1305                              ")",
1306                              |item| item.span.lo,
1307                              |item| item.span.hi,
1308                              |item| item.rewrite(&inner_context, remaining_width, offset),
1309                              span.lo,
1310                              span.hi);
1311     let mut item_vec: Vec<_> = items.collect();
1312
1313     // Try letting the last argument overflow to the next line with block
1314     // indentation. If its first line fits on one line with the other arguments,
1315     // we format the function arguments horizontally.
1316     let overflow_last = match args.last().map(|x| &x.node) {
1317         Some(&ast::ExprKind::Closure(..)) |
1318         Some(&ast::ExprKind::Block(..)) if arg_count > 1 => true,
1319         _ => false,
1320     } && context.config.chains_overflow_last;
1321
1322     let mut orig_last = None;
1323     let mut placeholder = None;
1324
1325     // Replace the last item with its first line to see if it fits with
1326     // first arguments.
1327     if overflow_last {
1328         let inner_context = &RewriteContext { block_indent: context.block_indent, ..*context };
1329         let rewrite = args.last().unwrap().rewrite(&inner_context, remaining_width, offset);
1330
1331         if let Some(rewrite) = rewrite {
1332             let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
1333             placeholder = Some(rewrite);
1334
1335             swap(&mut item_vec[arg_count - 1].item, &mut orig_last);
1336             item_vec[arg_count - 1].item = rewrite_first_line;
1337         }
1338     }
1339
1340     let tactic = definitive_tactic(&item_vec,
1341                                    ListTactic::LimitedHorizontalVertical(context.config
1342                                                                                 .fn_call_width),
1343                                    remaining_width);
1344
1345     // Replace the stub with the full overflowing last argument if the rewrite
1346     // succeeded and its first line fits with the other arguments.
1347     match (overflow_last, tactic, placeholder) {
1348         (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
1349             item_vec[arg_count - 1].item = placeholder;
1350         }
1351         (true, _, _) => {
1352             item_vec[arg_count - 1].item = orig_last;
1353         }
1354         (false, _, _) => {}
1355     }
1356
1357     let fmt = ListFormatting {
1358         tactic: tactic,
1359         separator: ",",
1360         trailing_separator: SeparatorTactic::Never,
1361         indent: offset,
1362         width: width,
1363         ends_with_newline: false,
1364         config: context.config,
1365     };
1366
1367     let list_str = match write_list(&item_vec, &fmt) {
1368         Some(str) => str,
1369         None => return Err(Ordering::Less),
1370     };
1371
1372     Ok(format!("{}({})", callee_str, list_str))
1373 }
1374
1375 fn rewrite_paren(context: &RewriteContext,
1376                  subexpr: &ast::Expr,
1377                  width: usize,
1378                  offset: Indent)
1379                  -> Option<String> {
1380     debug!("rewrite_paren, width: {}, offset: {:?}", width, offset);
1381     // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
1382     // paren on the same line as the subexpr.
1383     let subexpr_str = subexpr.rewrite(context, try_opt!(width.checked_sub(2)), offset + 1);
1384     debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1385     subexpr_str.map(|s| format!("({})", s))
1386 }
1387
1388 fn rewrite_struct_lit<'a>(context: &RewriteContext,
1389                           path: &ast::Path,
1390                           fields: &'a [ast::Field],
1391                           base: Option<&'a ast::Expr>,
1392                           span: Span,
1393                           width: usize,
1394                           offset: Indent)
1395                           -> Option<String> {
1396     debug!("rewrite_struct_lit: width {}, offset {:?}", width, offset);
1397
1398     enum StructLitField<'a> {
1399         Regular(&'a ast::Field),
1400         Base(&'a ast::Expr),
1401     }
1402
1403     // 2 = " {".len()
1404     let path_budget = try_opt!(width.checked_sub(2));
1405     let path_str = try_opt!(rewrite_path(context, true, None, path, path_budget, offset));
1406
1407     // Foo { a: Foo } - indent is +3, width is -5.
1408     let h_budget = width.checked_sub(path_str.len() + 5).unwrap_or(0);
1409     // The 1 taken from the v_budget is for the comma.
1410     let (indent, v_budget) = match context.config.struct_lit_style {
1411         StructLitStyle::Visual => (offset + path_str.len() + 3, h_budget),
1412         StructLitStyle::Block => {
1413             // If we are all on one line, then we'll ignore the indent, and we
1414             // have a smaller budget.
1415             let indent = context.block_indent.block_indent(context.config);
1416             let v_budget = context.config.max_width.checked_sub(indent.width()).unwrap_or(0);
1417             (indent, v_budget)
1418         }
1419     };
1420
1421     let field_iter = fields.into_iter()
1422                            .map(StructLitField::Regular)
1423                            .chain(base.into_iter().map(StructLitField::Base));
1424
1425     let inner_context = &RewriteContext { block_indent: indent, ..*context };
1426
1427     let items = itemize_list(context.codemap,
1428                              field_iter,
1429                              "}",
1430                              |item| {
1431                                  match *item {
1432                                      StructLitField::Regular(ref field) => field.span.lo,
1433                                      StructLitField::Base(ref expr) => {
1434                                          let last_field_hi = fields.last().map_or(span.lo,
1435                                                                                   |field| {
1436                                                                                       field.span.hi
1437                                                                                   });
1438                                          let snippet = context.snippet(mk_sp(last_field_hi,
1439                                                                              expr.span.lo));
1440                                          let pos = snippet.find_uncommented("..").unwrap();
1441                                          last_field_hi + BytePos(pos as u32)
1442                                      }
1443                                  }
1444                              },
1445                              |item| {
1446                                  match *item {
1447                                      StructLitField::Regular(ref field) => field.span.hi,
1448                                      StructLitField::Base(ref expr) => expr.span.hi,
1449                                  }
1450                              },
1451                              |item| {
1452                                  match *item {
1453                                      StructLitField::Regular(ref field) => {
1454                                          rewrite_field(inner_context,
1455                                                        &field,
1456                                                        v_budget.checked_sub(1).unwrap_or(0),
1457                                                        indent)
1458                                      }
1459                                      StructLitField::Base(ref expr) => {
1460                                          // 2 = ..
1461                                          expr.rewrite(inner_context,
1462                                                       try_opt!(v_budget.checked_sub(2)),
1463                                                       indent + 2)
1464                                              .map(|s| format!("..{}", s))
1465                                      }
1466                                  }
1467                              },
1468                              context.codemap.span_after(span, "{"),
1469                              span.hi);
1470     let item_vec = items.collect::<Vec<_>>();
1471
1472     let tactic = {
1473         let mut prelim_tactic = match (context.config.struct_lit_style, fields.len()) {
1474             (StructLitStyle::Visual, 1) => ListTactic::HorizontalVertical,
1475             _ => context.config.struct_lit_multiline_style.to_list_tactic(),
1476         };
1477
1478         if prelim_tactic == ListTactic::HorizontalVertical && fields.len() > 1 {
1479             prelim_tactic = ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width);
1480         }
1481
1482         definitive_tactic(&item_vec, prelim_tactic, h_budget)
1483     };
1484
1485     let budget = match tactic {
1486         DefinitiveListTactic::Horizontal => h_budget,
1487         _ => v_budget,
1488     };
1489
1490     let ends_with_newline = context.config.struct_lit_style != StructLitStyle::Visual &&
1491                             tactic == DefinitiveListTactic::Vertical;
1492
1493     let fmt = ListFormatting {
1494         tactic: tactic,
1495         separator: ",",
1496         trailing_separator: if base.is_some() {
1497             SeparatorTactic::Never
1498         } else {
1499             context.config.struct_lit_trailing_comma
1500         },
1501         indent: indent,
1502         width: budget,
1503         ends_with_newline: ends_with_newline,
1504         config: context.config,
1505     };
1506     let fields_str = try_opt!(write_list(&item_vec, &fmt));
1507
1508     if fields_str.is_empty() {
1509         return Some(format!("{} {{}}", path_str));
1510     }
1511
1512     let format_on_newline = || {
1513         let inner_indent = context.block_indent
1514                                   .block_indent(context.config)
1515                                   .to_string(context.config);
1516         let outer_indent = context.block_indent.to_string(context.config);
1517         Some(format!("{} {{\n{}{}\n{}}}",
1518                      path_str,
1519                      inner_indent,
1520                      fields_str,
1521                      outer_indent))
1522     };
1523
1524     match (context.config.struct_lit_style, context.config.struct_lit_multiline_style) {
1525         (StructLitStyle::Block, _) if fields_str.contains('\n') || fields_str.len() > h_budget => {
1526             format_on_newline()
1527         }
1528         (StructLitStyle::Block, MultilineStyle::ForceMulti) => format_on_newline(),
1529         _ => Some(format!("{} {{ {} }}", path_str, fields_str)),
1530     }
1531
1532     // FIXME if context.config.struct_lit_style == Visual, but we run out
1533     // of space, we should fall back to BlockIndent.
1534 }
1535
1536 fn rewrite_field(context: &RewriteContext,
1537                  field: &ast::Field,
1538                  width: usize,
1539                  offset: Indent)
1540                  -> Option<String> {
1541     let name = &field.ident.node.to_string();
1542     let overhead = name.len() + 2;
1543     let expr = field.expr.rewrite(context,
1544                                   try_opt!(width.checked_sub(overhead)),
1545                                   offset + overhead);
1546
1547     match expr {
1548         Some(e) => Some(format!("{}: {}", name, e)),
1549         None => {
1550             let expr_offset = offset.block_indent(&context.config);
1551             let expr = field.expr.rewrite(context,
1552                                           try_opt!(context.config
1553                                                           .max_width
1554                                                           .checked_sub(expr_offset.width())),
1555                                           expr_offset);
1556             expr.map(|s| format!("{}:\n{}{}", name, expr_offset.to_string(&context.config), s))
1557         }
1558     }
1559 }
1560
1561 pub fn rewrite_tuple<'a, I>(context: &RewriteContext,
1562                             mut items: I,
1563                             span: Span,
1564                             width: usize,
1565                             offset: Indent)
1566                             -> Option<String>
1567     where I: ExactSizeIterator,
1568           <I as Iterator>::Item: Deref,
1569           <I::Item as Deref>::Target: Rewrite + Spanned + 'a
1570 {
1571     let indent = offset + 1;
1572     // In case of length 1, need a trailing comma
1573     if items.len() == 1 {
1574         // 3 = "(" + ",)"
1575         let budget = try_opt!(width.checked_sub(3));
1576         return items.next().unwrap().rewrite(context, budget, indent).map(|s| format!("({},)", s));
1577     }
1578
1579     let list_lo = context.codemap.span_after(span, "(");
1580     let items = itemize_list(context.codemap,
1581                              items,
1582                              ")",
1583                              |item| item.span().lo,
1584                              |item| item.span().hi,
1585                              |item| {
1586                                  let inner_width = try_opt!(context.config
1587                                                                    .max_width
1588                                                                    .checked_sub(indent.width() +
1589                                                                                 1));
1590                                  item.rewrite(context, inner_width, indent)
1591                              },
1592                              list_lo,
1593                              span.hi - BytePos(1));
1594     let budget = try_opt!(width.checked_sub(2));
1595     let list_str = try_opt!(format_item_list(items, budget, indent, context.config));
1596
1597     Some(format!("({})", list_str))
1598 }
1599
1600 fn rewrite_binary_op(context: &RewriteContext,
1601                      op: &ast::BinOp,
1602                      lhs: &ast::Expr,
1603                      rhs: &ast::Expr,
1604                      width: usize,
1605                      offset: Indent)
1606                      -> Option<String> {
1607     // FIXME: format comments between operands and operator
1608
1609     let operator_str = context.snippet(op.span);
1610
1611     // Get "full width" rhs and see if it fits on the current line. This
1612     // usually works fairly well since it tends to place operands of
1613     // operations with high precendence close together.
1614     let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
1615
1616     // Second condition is needed in case of line break not caused by a
1617     // shortage of space, but by end-of-line comments, for example.
1618     // Note that this is non-conservative, but its just to see if it's even
1619     // worth trying to put everything on one line.
1620     if rhs_result.len() + 2 + operator_str.len() < width && !rhs_result.contains('\n') {
1621         // 1 = space between lhs expr and operator
1622         if let Some(mut result) = lhs.rewrite(context, width - 1 - operator_str.len(), offset) {
1623             result.push(' ');
1624             result.push_str(&operator_str);
1625             result.push(' ');
1626
1627             let remaining_width = width.checked_sub(last_line_width(&result)).unwrap_or(0);
1628
1629             if rhs_result.len() <= remaining_width {
1630                 result.push_str(&rhs_result);
1631                 return Some(result);
1632             }
1633
1634             if let Some(rhs_result) = rhs.rewrite(context, remaining_width, offset + result.len()) {
1635                 if rhs_result.len() <= remaining_width {
1636                     result.push_str(&rhs_result);
1637                     return Some(result);
1638                 }
1639             }
1640         }
1641     }
1642
1643     // We have to use multiple lines.
1644
1645     // Re-evaluate the lhs because we have more space now:
1646     let budget = try_opt!(context.config
1647                                  .max_width
1648                                  .checked_sub(offset.width() + 1 + operator_str.len()));
1649     Some(format!("{} {}\n{}{}",
1650                  try_opt!(lhs.rewrite(context, budget, offset)),
1651                  operator_str,
1652                  offset.to_string(context.config),
1653                  rhs_result))
1654 }
1655
1656 pub fn rewrite_unary_prefix<R: Rewrite>(context: &RewriteContext,
1657                                         prefix: &str,
1658                                         rewrite: &R,
1659                                         width: usize,
1660                                         offset: Indent)
1661                                         -> Option<String> {
1662     rewrite.rewrite(context,
1663                     try_opt!(width.checked_sub(prefix.len())),
1664                     offset + prefix.len())
1665            .map(|r| format!("{}{}", prefix, r))
1666 }
1667
1668 fn rewrite_unary_op(context: &RewriteContext,
1669                     op: &ast::UnOp,
1670                     expr: &ast::Expr,
1671                     width: usize,
1672                     offset: Indent)
1673                     -> Option<String> {
1674     // For some reason, an UnOp is not spanned like BinOp!
1675     let operator_str = match *op {
1676         ast::UnOp::Deref => "*",
1677         ast::UnOp::Not => "!",
1678         ast::UnOp::Neg => "-",
1679     };
1680     rewrite_unary_prefix(context, operator_str, expr, width, offset)
1681 }
1682
1683 fn rewrite_assignment(context: &RewriteContext,
1684                       lhs: &ast::Expr,
1685                       rhs: &ast::Expr,
1686                       op: Option<&ast::BinOp>,
1687                       width: usize,
1688                       offset: Indent)
1689                       -> Option<String> {
1690     let operator_str = match op {
1691         Some(op) => context.snippet(op.span),
1692         None => "=".to_owned(),
1693     };
1694
1695     // 1 = space between lhs and operator.
1696     let max_width = try_opt!(width.checked_sub(operator_str.len() + 1));
1697     let lhs_str = format!("{} {}",
1698                           try_opt!(lhs.rewrite(context, max_width, offset)),
1699                           operator_str);
1700
1701     rewrite_assign_rhs(&context, lhs_str, rhs, width, offset)
1702 }
1703
1704 // The left hand side must contain everything up to, and including, the
1705 // assignment operator.
1706 pub fn rewrite_assign_rhs<S: Into<String>>(context: &RewriteContext,
1707                                            lhs: S,
1708                                            ex: &ast::Expr,
1709                                            width: usize,
1710                                            offset: Indent)
1711                                            -> Option<String> {
1712     let mut result = lhs.into();
1713     let last_line_width = last_line_width(&result) -
1714                           if result.contains('\n') {
1715         offset.width()
1716     } else {
1717         0
1718     };
1719     // 1 = space between operator and rhs.
1720     let max_width = try_opt!(width.checked_sub(last_line_width + 1));
1721     let rhs = ex.rewrite(&context, max_width, offset + last_line_width + 1);
1722
1723     match rhs {
1724         Some(new_str) => {
1725             result.push(' ');
1726             result.push_str(&new_str)
1727         }
1728         None => {
1729             // Expression did not fit on the same line as the identifier. Retry
1730             // on the next line.
1731             let new_offset = offset.block_indent(context.config);
1732             result.push_str(&format!("\n{}", new_offset.to_string(context.config)));
1733
1734             // FIXME: we probably should related max_width to width instead of
1735             // config.max_width where is the 1 coming from anyway?
1736             let max_width = try_opt!(context.config.max_width.checked_sub(new_offset.width() + 1));
1737             let inner_context = context.nested_context();
1738             let rhs = ex.rewrite(&inner_context, max_width, new_offset);
1739
1740             result.push_str(&&try_opt!(rhs));
1741         }
1742     }
1743
1744     Some(result)
1745 }
1746
1747 fn rewrite_expr_addrof(context: &RewriteContext,
1748                        mutability: ast::Mutability,
1749                        expr: &ast::Expr,
1750                        width: usize,
1751                        offset: Indent)
1752                        -> Option<String> {
1753     let operator_str = match mutability {
1754         ast::Mutability::Immutable => "&",
1755         ast::Mutability::Mutable => "&mut ",
1756     };
1757     rewrite_unary_prefix(context, operator_str, expr, width, offset)
1758 }