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