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