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