]> git.lizzy.rs Git - rust.git/blob - src/items.rs
Use trailing commas if block formatting fn args
[rust.git] / src / items.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 // Formatting top-level items - functions, structs, enums, traits, impls.
12
13 use {Indent, Shape};
14 use codemap::SpanUtils;
15 use utils::{format_mutability, format_visibility, contains_skip, end_typaram, wrap_str,
16             last_line_width, format_unsafety, trim_newlines, stmt_expr, semicolon_for_expr};
17 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic,
18             DefinitiveListTactic, ListTactic, definitive_tactic, format_item_list};
19 use expr::{is_empty_block, is_simple_block_stmt, rewrite_assign_rhs, type_annotation_separator};
20 use comment::{FindUncommented, contains_comment};
21 use visitor::FmtVisitor;
22 use rewrite::{Rewrite, RewriteContext};
23 use config::{Config, BlockIndentStyle, Density, ReturnIndent, BraceStyle, FnArgLayoutStyle, Style};
24 use itertools::Itertools;
25
26 use syntax::{ast, abi, codemap, ptr, symbol};
27 use syntax::codemap::{Span, BytePos, mk_sp};
28 use syntax::ast::ImplItem;
29
30 // Statements of the form
31 // let pat: ty = init;
32 impl Rewrite for ast::Local {
33     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
34         debug!("Local::rewrite {:?} {} {:?}",
35                self,
36                shape.width,
37                shape.indent);
38         let mut result = "let ".to_owned();
39         let pattern_offset = shape.indent + result.len();
40         // 1 = ;
41         let pattern_width = try_opt!(shape.width.checked_sub(pattern_offset.width() + 1));
42
43         let pat_str = try_opt!(self.pat.rewrite(&context,
44                                                 Shape::legacy(pattern_width, pattern_offset)));
45         result.push_str(&pat_str);
46
47         // String that is placed within the assignment pattern and expression.
48         let infix = {
49             let mut infix = String::new();
50
51             if let Some(ref ty) = self.ty {
52                 let separator = type_annotation_separator(context.config);
53                 let indent = shape.indent + last_line_width(&result) + separator.len();
54                 // 1 = ;
55                 let budget = try_opt!(shape.width.checked_sub(indent.width() + 1));
56                 let rewrite = try_opt!(ty.rewrite(context, Shape::legacy(budget, indent)));
57
58                 infix.push_str(separator);
59                 infix.push_str(&rewrite);
60             }
61
62             if self.init.is_some() {
63                 infix.push_str(" =");
64             }
65
66             infix
67         };
68
69         result.push_str(&infix);
70
71         if let Some(ref ex) = self.init {
72             // 1 = trailing semicolon;
73             let budget = try_opt!(shape.width.checked_sub(shape.indent.block_only().width() + 1));
74
75             result = try_opt!(rewrite_assign_rhs(&context,
76                                                  result,
77                                                  ex,
78                                                  Shape::legacy(budget, shape.indent.block_only())));
79         }
80
81         result.push(';');
82         Some(result)
83     }
84 }
85
86 // TODO convert to using rewrite style rather than visitor
87 // TODO format modules in this style
88 #[allow(dead_code)]
89 struct Item<'a> {
90     keyword: &'static str,
91     abi: String,
92     vis: Option<&'a ast::Visibility>,
93     body: Vec<BodyElement<'a>>,
94     span: Span,
95 }
96
97 impl<'a> Item<'a> {
98     fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
99         let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi {
100             "extern".into()
101         } else {
102             format!("extern {}", fm.abi)
103         };
104         Item {
105             keyword: "",
106             abi: abi,
107             vis: None,
108             body: fm.items
109                 .iter()
110                 .map(|i| BodyElement::ForeignItem(i))
111                 .collect(),
112             span: span,
113         }
114     }
115 }
116
117 enum BodyElement<'a> {
118     // Stmt(&'a ast::Stmt),
119     // Field(&'a ast::Field),
120     // Variant(&'a ast::Variant),
121     // Item(&'a ast::Item),
122     ForeignItem(&'a ast::ForeignItem),
123 }
124
125 impl<'a> FmtVisitor<'a> {
126     fn format_item(&mut self, item: Item) {
127         self.buffer.push_str(&item.abi);
128         self.buffer.push_str(" ");
129
130         let snippet = self.snippet(item.span);
131         let brace_pos = snippet.find_uncommented("{").unwrap();
132
133         self.buffer.push_str("{");
134         if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
135             // FIXME: this skips comments between the extern keyword and the opening
136             // brace.
137             self.last_pos = item.span.lo + BytePos(brace_pos as u32 + 1);
138             self.block_indent = self.block_indent.block_indent(self.config);
139
140             if item.body.is_empty() {
141                 self.format_missing_no_indent(item.span.hi - BytePos(1));
142                 self.block_indent = self.block_indent.block_unindent(self.config);
143
144                 self.buffer.push_str(&self.block_indent.to_string(self.config));
145             } else {
146                 for item in &item.body {
147                     self.format_body_element(item);
148                 }
149
150                 self.block_indent = self.block_indent.block_unindent(self.config);
151                 self.format_missing_with_indent(item.span.hi - BytePos(1));
152             }
153         }
154
155         self.buffer.push_str("}");
156         self.last_pos = item.span.hi;
157     }
158
159     fn format_body_element(&mut self, element: &BodyElement) {
160         match *element {
161             BodyElement::ForeignItem(ref item) => self.format_foreign_item(item),
162         }
163     }
164
165     pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
166         let item = Item::from_foreign_mod(fm, span, self.config);
167         self.format_item(item);
168     }
169
170     fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
171         self.format_missing_with_indent(item.span.lo);
172         // Drop semicolon or it will be interpreted as comment.
173         // FIXME: this may be a faulty span from libsyntax.
174         let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
175
176         match item.node {
177             ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
178                 let indent = self.block_indent;
179                 let rewrite = rewrite_fn_base(&self.get_context(),
180                                               indent,
181                                               item.ident,
182                                               fn_decl,
183                                               generics,
184                                               ast::Unsafety::Normal,
185                                               ast::Constness::NotConst,
186                                               ast::Defaultness::Final,
187                                               // These are not actually rust functions,
188                                               // but we format them as such.
189                                               abi::Abi::Rust,
190                                               &item.vis,
191                                               span,
192                                               false,
193                                               false);
194
195                 match rewrite {
196                     Some((new_fn, _)) => {
197                         self.buffer.push_str(&new_fn);
198                         self.buffer.push_str(";");
199                     }
200                     None => self.format_missing(item.span.hi),
201                 }
202             }
203             ast::ForeignItemKind::Static(ref ty, is_mutable) => {
204                 // FIXME(#21): we're dropping potential comments in between the
205                 // function keywords here.
206                 let vis = format_visibility(&item.vis);
207                 let mut_str = if is_mutable { "mut " } else { "" };
208                 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
209                 let offset = self.block_indent + prefix.len();
210                 // 1 = ;
211                 let width = self.config.max_width - offset.width() - 1;
212                 let rewrite = ty.rewrite(&self.get_context(), Shape::legacy(width, offset));
213
214                 match rewrite {
215                     Some(result) => {
216                         self.buffer.push_str(&prefix);
217                         self.buffer.push_str(&result);
218                         self.buffer.push_str(";");
219                     }
220                     None => self.format_missing(item.span.hi),
221                 }
222             }
223         }
224
225         self.last_pos = item.span.hi;
226     }
227
228     pub fn rewrite_fn(&mut self,
229                       indent: Indent,
230                       ident: ast::Ident,
231                       fd: &ast::FnDecl,
232                       generics: &ast::Generics,
233                       unsafety: ast::Unsafety,
234                       constness: ast::Constness,
235                       defaultness: ast::Defaultness,
236                       abi: abi::Abi,
237                       vis: &ast::Visibility,
238                       span: Span,
239                       block: &ast::Block)
240                       -> Option<String> {
241         let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
242         let context = self.get_context();
243
244         let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
245         let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
246                        !context.config.fn_empty_single_line;
247
248         let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
249                                                                          indent,
250                                                                          ident,
251                                                                          fd,
252                                                                          generics,
253                                                                          unsafety,
254                                                                          constness,
255                                                                          defaultness,
256                                                                          abi,
257                                                                          vis,
258                                                                          span,
259                                                                          newline_brace,
260                                                                          has_body));
261
262         if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
263             newline_brace = false;
264         } else if force_newline_brace {
265             newline_brace = true;
266         }
267
268         // Prepare for the function body by possibly adding a newline and
269         // indent.
270         // FIXME we'll miss anything between the end of the signature and the
271         // start of the body, but we need more spans from the compiler to solve
272         // this.
273         if newline_brace {
274             result.push('\n');
275             result.push_str(&indent.to_string(self.config));
276         } else {
277             result.push(' ');
278         }
279
280         self.single_line_fn(&result, block).or_else(|| Some(result))
281     }
282
283     pub fn rewrite_required_fn(&mut self,
284                                indent: Indent,
285                                ident: ast::Ident,
286                                sig: &ast::MethodSig,
287                                span: Span)
288                                -> Option<String> {
289         // Drop semicolon or it will be interpreted as comment.
290         let span = mk_sp(span.lo, span.hi - BytePos(1));
291         let context = self.get_context();
292
293         let (mut result, _) = try_opt!(rewrite_fn_base(&context,
294                                                        indent,
295                                                        ident,
296                                                        &sig.decl,
297                                                        &sig.generics,
298                                                        sig.unsafety,
299                                                        sig.constness.node,
300                                                        ast::Defaultness::Final,
301                                                        sig.abi,
302                                                        &ast::Visibility::Inherited,
303                                                        span,
304                                                        false,
305                                                        false));
306
307         // Re-attach semicolon
308         result.push(';');
309
310         Some(result)
311     }
312
313     fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
314         if fn_str.contains('\n') {
315             return None;
316         }
317
318         let codemap = self.get_context().codemap;
319
320         if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
321            self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
322             return Some(format!("{}{{}}", fn_str));
323         }
324
325         if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
326             let rewrite = {
327                 if let Some(ref stmt) = block.stmts.first() {
328                     match stmt_expr(stmt) {
329                         Some(e) => {
330                             let suffix = if semicolon_for_expr(e) { ";" } else { "" };
331
332                             e.rewrite(&self.get_context(),
333                                          Shape::legacy(self.config.max_width -
334                                                        self.block_indent.width(),
335                                                        self.block_indent))
336                                 .map(|s| s + suffix)
337                                 .or_else(|| Some(self.snippet(e.span)))
338                         }
339                         None => {
340                             stmt.rewrite(&self.get_context(),
341                                          Shape::legacy(self.config.max_width -
342                                                        self.block_indent.width(),
343                                                        self.block_indent))
344                         }
345                     }
346                 } else {
347                     None
348                 }
349             };
350
351             if let Some(res) = rewrite {
352                 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
353                 if !res.contains('\n') && width <= self.config.max_width {
354                     return Some(format!("{}{{ {} }}", fn_str, res));
355                 }
356             }
357         }
358
359         None
360     }
361
362     pub fn visit_enum(&mut self,
363                       ident: ast::Ident,
364                       vis: &ast::Visibility,
365                       enum_def: &ast::EnumDef,
366                       generics: &ast::Generics,
367                       span: Span) {
368         self.buffer.push_str(&format_header("enum ", ident, vis));
369
370         let enum_snippet = self.snippet(span);
371         let brace_pos = enum_snippet.find_uncommented("{").unwrap();
372         let body_start = span.lo + BytePos(brace_pos as u32 + 1);
373         let generics_str = format_generics(&self.get_context(),
374                                            generics,
375                                            "{",
376                                            "{",
377                                            self.config.item_brace_style,
378                                            enum_def.variants.is_empty(),
379                                            self.block_indent,
380                                            self.block_indent.block_indent(self.config),
381                                            mk_sp(span.lo, body_start))
382                 .unwrap();
383         self.buffer.push_str(&generics_str);
384
385         self.last_pos = body_start;
386
387         self.block_indent = self.block_indent.block_indent(self.config);
388         let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
389         match variant_list {
390             Some(ref body_str) => self.buffer.push_str(body_str),
391             None => {
392                 if contains_comment(&enum_snippet[brace_pos..]) {
393                     self.format_missing_no_indent(span.hi - BytePos(1))
394                 } else {
395                     self.format_missing(span.hi - BytePos(1))
396                 }
397             }
398         }
399         self.block_indent = self.block_indent.block_unindent(self.config);
400
401         if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
402             self.buffer.push_str(&self.block_indent.to_string(self.config));
403         }
404         self.buffer.push_str("}");
405         self.last_pos = span.hi;
406     }
407
408     // Format the body of an enum definition
409     fn format_variant_list(&self,
410                            enum_def: &ast::EnumDef,
411                            body_lo: BytePos,
412                            body_hi: BytePos)
413                            -> Option<String> {
414         if enum_def.variants.is_empty() {
415             return None;
416         }
417         let mut result = String::with_capacity(1024);
418         result.push('\n');
419         let indentation = self.block_indent.to_string(self.config);
420         result.push_str(&indentation);
421
422         let items = itemize_list(self.codemap,
423                                  enum_def.variants.iter(),
424                                  "}",
425                                  |f| if !f.node.attrs.is_empty() {
426                                      f.node.attrs[0].span.lo
427                                  } else {
428                                      f.span.lo
429                                  },
430                                  |f| f.span.hi,
431                                  |f| self.format_variant(f),
432                                  body_lo,
433                                  body_hi);
434
435         let budget = self.config.max_width - self.block_indent.width() - 2;
436         let fmt = ListFormatting {
437             tactic: DefinitiveListTactic::Vertical,
438             separator: ",",
439             trailing_separator: self.config.trailing_comma,
440             shape: Shape::legacy(budget, self.block_indent),
441             ends_with_newline: true,
442             config: self.config,
443         };
444
445         let list = try_opt!(write_list(items, &fmt));
446         result.push_str(&list);
447         result.push('\n');
448         Some(result)
449     }
450
451     // Variant of an enum.
452     fn format_variant(&self, field: &ast::Variant) -> Option<String> {
453         if contains_skip(&field.node.attrs) {
454             let lo = field.node.attrs[0].span.lo;
455             let span = mk_sp(lo, field.span.hi);
456             return Some(self.snippet(span));
457         }
458
459         let indent = self.block_indent;
460         let mut result = try_opt!(field.node.attrs.rewrite(&self.get_context(),
461                                                            Shape::legacy(self.config.max_width -
462                                                                          indent.width(),
463                                                                          indent)));
464         if !result.is_empty() {
465             result.push('\n');
466             result.push_str(&indent.to_string(self.config));
467         }
468
469         let context = self.get_context();
470         let variant_body = match field.node.data {
471             ast::VariantData::Tuple(..) |
472             ast::VariantData::Struct(..) => {
473                 // FIXME: Should limit the width, as we have a trailing comma
474                 format_struct(&context,
475                               "",
476                               field.node.name,
477                               &ast::Visibility::Inherited,
478                               &field.node.data,
479                               None,
480                               field.span,
481                               indent,
482                               Some(self.config.struct_variant_width))
483             }
484             ast::VariantData::Unit(..) => {
485                 let tag = if let Some(ref expr) = field.node.disr_expr {
486                     format!("{} = {}", field.node.name, self.snippet(expr.span))
487                 } else {
488                     field.node.name.to_string()
489                 };
490
491                 wrap_str(tag,
492                          self.config.max_width,
493                          Shape::legacy(self.config.max_width - indent.width(), indent))
494             }
495         };
496
497         if let Some(variant_str) = variant_body {
498             result.push_str(&variant_str);
499             Some(result)
500         } else {
501             None
502         }
503     }
504 }
505
506 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
507     if let ast::ItemKind::Impl(_, _, ref generics, ref trait_ref, _, ref items) = item.node {
508         let mut result = String::new();
509         // First try to format the ref and type without a split at the 'for'.
510         let mut ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset, false));
511
512         // If there is a line break present in the first result format it again
513         // with a split at the 'for'. Skip this if there is no trait ref and
514         // therefore no 'for'.
515         if ref_and_type.contains('\n') && trait_ref.is_some() {
516             ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset, true));
517         }
518         result.push_str(&ref_and_type);
519
520         let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
521         let where_clause_str = try_opt!(rewrite_where_clause(context,
522                                                              &generics.where_clause,
523                                                              context.config.item_brace_style,
524                                                              Shape::legacy(where_budget,
525                                                                            offset.block_only()),
526                                                              context.config.where_density,
527                                                              "{",
528                                                              false,
529                                                              false,
530                                                              None));
531
532         if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
533             result.push_str(&where_clause_str);
534             if where_clause_str.contains('\n') {
535                 let white_space = offset.to_string(context.config);
536                 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
537             } else {
538                 result.push_str(" {}");
539             }
540             return Some(result);
541         }
542
543         if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
544             result.push('\n');
545             let width = offset.block_indent + context.config.tab_spaces - 1;
546             let where_indent = Indent::new(0, width);
547             result.push_str(&where_indent.to_string(context.config));
548         }
549         result.push_str(&where_clause_str);
550
551         match context.config.item_brace_style {
552             BraceStyle::AlwaysNextLine => {
553                 result.push('\n');
554                 result.push_str(&offset.to_string(context.config));
555             }
556             BraceStyle::PreferSameLine => result.push(' '),
557             BraceStyle::SameLineWhere => {
558                 if !where_clause_str.is_empty() {
559                     result.push('\n');
560                     result.push_str(&offset.to_string(context.config));
561                 } else {
562                     result.push(' ');
563                 }
564             }
565         }
566
567         result.push('{');
568
569         let snippet = context.snippet(item.span);
570         let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
571
572         if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
573             let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
574             visitor.block_indent = offset.block_only().block_indent(context.config);
575             visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
576
577             for item in items {
578                 visitor.visit_impl_item(item);
579             }
580
581             visitor.format_missing(item.span.hi - BytePos(1));
582
583             let inner_indent_str = visitor.block_indent.to_string(context.config);
584             let outer_indent_str = offset.block_only().to_string(context.config);
585
586             result.push('\n');
587             result.push_str(&inner_indent_str);
588             result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
589             result.push('\n');
590             result.push_str(&outer_indent_str);
591         }
592
593         if result.chars().last().unwrap() == '{' {
594             result.push('\n');
595             result.push_str(&offset.to_string(context.config));
596         }
597         result.push('}');
598
599         Some(result)
600     } else {
601         unreachable!();
602     }
603 }
604
605 fn is_impl_single_line(context: &RewriteContext,
606                        items: &[ImplItem],
607                        result: &str,
608                        where_clause_str: &str,
609                        item: &ast::Item)
610                        -> Option<bool> {
611     let snippet = context.snippet(item.span);
612     let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
613
614     Some(context.config.impl_empty_single_line && items.is_empty() &&
615          result.len() + where_clause_str.len() <= context.config.max_width &&
616          !contains_comment(&snippet[open_pos..]))
617 }
618
619 fn format_impl_ref_and_type(context: &RewriteContext,
620                             item: &ast::Item,
621                             offset: Indent,
622                             split_at_for: bool)
623                             -> Option<String> {
624     if let ast::ItemKind::Impl(unsafety, polarity, ref generics, ref trait_ref, ref self_ty, _) =
625         item.node {
626         let mut result = String::new();
627
628         result.push_str(&*format_visibility(&item.vis));
629         result.push_str(format_unsafety(unsafety));
630         result.push_str("impl");
631
632         let lo = context.codemap.span_after(item.span, "impl");
633         let hi = match *trait_ref {
634             Some(ref tr) => tr.path.span.lo,
635             None => self_ty.span.lo,
636         };
637         let generics_str = try_opt!(rewrite_generics(context,
638                                                      generics,
639                                                      Shape::legacy(context.config.max_width,
640                                                                    offset),
641                                                      offset + result.len(),
642                                                      mk_sp(lo, hi)));
643         result.push_str(&generics_str);
644
645         if polarity == ast::ImplPolarity::Negative {
646             result.push_str(" !");
647         }
648         if let Some(ref trait_ref) = *trait_ref {
649             if polarity != ast::ImplPolarity::Negative {
650                 result.push_str(" ");
651             }
652             let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
653             let indent = offset + result.len();
654             result.push_str(&*try_opt!(trait_ref.rewrite(context, Shape::legacy(budget, indent))));
655
656             if split_at_for {
657                 result.push('\n');
658
659                 // Add indentation of one additional tab.
660                 let width = offset.block_indent + context.config.tab_spaces;
661                 let for_indent = Indent::new(0, width);
662                 result.push_str(&for_indent.to_string(context.config));
663
664                 result.push_str("for");
665             } else {
666                 result.push_str(" for");
667             }
668         }
669
670         let mut used_space = last_line_width(&result);
671         if generics.where_clause.predicates.is_empty() {
672             // If there is no where clause adapt budget for type formatting to take space and curly
673             // brace into account.
674             match context.config.item_brace_style {
675                 BraceStyle::AlwaysNextLine => {}
676                 BraceStyle::PreferSameLine => used_space += 2,
677                 BraceStyle::SameLineWhere => used_space += 2,
678             }
679         }
680
681         // 1 = space before the type.
682         let budget = try_opt!(context.config.max_width.checked_sub(used_space + 1));
683         let indent = offset + result.len() + 1;
684         let self_ty_str = self_ty.rewrite(context, Shape::legacy(budget, indent));
685         if let Some(self_ty_str) = self_ty_str {
686             result.push_str(" ");
687             result.push_str(&self_ty_str);
688             return Some(result);
689         }
690
691         // Can't fit the self type on what's left of the line, so start a new one.
692         let indent = offset.block_indent(context.config);
693         result.push_str(&format!("\n{}", indent.to_string(context.config)));
694         let budget = try_opt!(context.config.max_width.checked_sub(indent.width()));
695         result.push_str(&*try_opt!(self_ty.rewrite(context, Shape::legacy(budget, indent))));
696         Some(result)
697     } else {
698         unreachable!();
699     }
700 }
701
702 pub fn format_struct(context: &RewriteContext,
703                      item_name: &str,
704                      ident: ast::Ident,
705                      vis: &ast::Visibility,
706                      struct_def: &ast::VariantData,
707                      generics: Option<&ast::Generics>,
708                      span: Span,
709                      offset: Indent,
710                      one_line_width: Option<usize>)
711                      -> Option<String> {
712     match *struct_def {
713         ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
714         ast::VariantData::Tuple(ref fields, _) => {
715             format_tuple_struct(context,
716                                 item_name,
717                                 ident,
718                                 vis,
719                                 fields,
720                                 generics,
721                                 span,
722                                 offset)
723         }
724         ast::VariantData::Struct(ref fields, _) => {
725             format_struct_struct(context,
726                                  item_name,
727                                  ident,
728                                  vis,
729                                  fields,
730                                  generics,
731                                  span,
732                                  offset,
733                                  one_line_width)
734         }
735     }
736 }
737
738 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
739     if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
740         item.node {
741         let mut result = String::new();
742         let header = format!("{}{}trait {}",
743                              format_visibility(&item.vis),
744                              format_unsafety(unsafety),
745                              item.ident);
746
747         result.push_str(&header);
748
749         let body_lo = context.codemap.span_after(item.span, "{");
750
751         let generics_str = try_opt!(rewrite_generics(context,
752                                                      generics,
753                                                      Shape::legacy(context.config.max_width,
754                                                                    offset),
755                                                      offset + result.len(),
756                                                      mk_sp(item.span.lo, body_lo)));
757         result.push_str(&generics_str);
758
759         let trait_bound_str =
760             try_opt!(rewrite_trait_bounds(context,
761                                           type_param_bounds,
762                                           Shape::legacy(context.config.max_width, offset)));
763         // If the trait, generics, and trait bound cannot fit on the same line,
764         // put the trait bounds on an indented new line
765         if offset.width() + last_line_width(&result) + trait_bound_str.len() >
766            context.config.ideal_width {
767             result.push('\n');
768             let trait_indent = offset.block_only().block_indent(context.config);
769             result.push_str(&trait_indent.to_string(context.config));
770         }
771         result.push_str(&trait_bound_str);
772
773         let has_body = !trait_items.is_empty();
774
775         let where_density =
776             if (context.config.where_density == Density::Compressed &&
777                 (!result.contains('\n') ||
778                  context.config.fn_args_layout == FnArgLayoutStyle::Block)) ||
779                (context.config.fn_args_layout == FnArgLayoutStyle::Block && result.is_empty()) ||
780                (context.config.where_density == Density::CompressedIfEmpty && !has_body &&
781                 !result.contains('\n')) {
782                 Density::Compressed
783             } else {
784                 Density::Tall
785             };
786
787         let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
788         let where_clause_str = try_opt!(rewrite_where_clause(context,
789                                                              &generics.where_clause,
790                                                              context.config.item_brace_style,
791                                                              Shape::legacy(where_budget,
792                                                                            offset.block_only()),
793                                                              where_density,
794                                                              "{",
795                                                              !has_body,
796                                                              false,
797                                                              None));
798         // If the where clause cannot fit on the same line,
799         // put the where clause on a new line
800         if !where_clause_str.contains('\n') &&
801            last_line_width(&result) + where_clause_str.len() + offset.width() >
802            context.config.ideal_width {
803             result.push('\n');
804             let width = offset.block_indent + context.config.tab_spaces - 1;
805             let where_indent = Indent::new(0, width);
806             result.push_str(&where_indent.to_string(context.config));
807         }
808         result.push_str(&where_clause_str);
809
810         match context.config.item_brace_style {
811             BraceStyle::AlwaysNextLine => {
812                 result.push('\n');
813                 result.push_str(&offset.to_string(context.config));
814             }
815             BraceStyle::PreferSameLine => result.push(' '),
816             BraceStyle::SameLineWhere => {
817                 if !where_clause_str.is_empty() &&
818                    (!trait_items.is_empty() || result.contains('\n')) {
819                     result.push('\n');
820                     result.push_str(&offset.to_string(context.config));
821                 } else {
822                     result.push(' ');
823                 }
824             }
825         }
826         result.push('{');
827
828         let snippet = context.snippet(item.span);
829         let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
830
831         if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
832             let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
833             visitor.block_indent = offset.block_only().block_indent(context.config);
834             visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
835
836             for item in trait_items {
837                 visitor.visit_trait_item(item);
838             }
839
840             visitor.format_missing(item.span.hi - BytePos(1));
841
842             let inner_indent_str = visitor.block_indent.to_string(context.config);
843             let outer_indent_str = offset.block_only().to_string(context.config);
844
845             result.push('\n');
846             result.push_str(&inner_indent_str);
847             result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
848             result.push('\n');
849             result.push_str(&outer_indent_str);
850         } else if result.contains('\n') {
851             result.push('\n');
852         }
853
854         result.push('}');
855         Some(result)
856     } else {
857         unreachable!();
858     }
859 }
860
861 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
862     format!("{};", format_header(item_name, ident, vis))
863 }
864
865 fn format_struct_struct(context: &RewriteContext,
866                         item_name: &str,
867                         ident: ast::Ident,
868                         vis: &ast::Visibility,
869                         fields: &[ast::StructField],
870                         generics: Option<&ast::Generics>,
871                         span: Span,
872                         offset: Indent,
873                         one_line_width: Option<usize>)
874                         -> Option<String> {
875     let mut result = String::with_capacity(1024);
876
877     let header_str = format_header(item_name, ident, vis);
878     result.push_str(&header_str);
879
880     let body_lo = context.codemap.span_after(span, "{");
881
882     let generics_str = match generics {
883         Some(g) => {
884             try_opt!(format_generics(context,
885                                      g,
886                                      "{",
887                                      "{",
888                                      context.config.item_brace_style,
889                                      fields.is_empty(),
890                                      offset,
891                                      offset + header_str.len(),
892                                      mk_sp(span.lo, body_lo)))
893         }
894         None => {
895             if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() {
896                 format!("\n{}{{", offset.block_only().to_string(context.config))
897             } else {
898                 " {".to_owned()
899             }
900         }
901     };
902     result.push_str(&generics_str);
903
904     // FIXME(#919): properly format empty structs and their comments.
905     if fields.is_empty() {
906         let snippet = context.snippet(mk_sp(body_lo, span.hi - BytePos(1)));
907         if snippet.trim().is_empty() {
908             // `struct S {}`
909         } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
910             // fix indent
911             result.push_str(&snippet.trim_right());
912             result.push('\n');
913             result.push_str(&offset.to_string(context.config));
914         } else {
915             result.push_str(&snippet);
916         }
917         result.push('}');
918         return Some(result);
919     }
920
921     let item_indent = offset.block_indent(context.config);
922     // 1 = ","
923     let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 1));
924
925     let items =
926         itemize_list(context.codemap,
927                      fields.iter(),
928                      "}",
929                      |field| {
930             // Include attributes and doc comments, if present
931             if !field.attrs.is_empty() {
932                 field.attrs[0].span.lo
933             } else {
934                 field.span.lo
935             }
936         },
937                      |field| field.ty.span.hi,
938                      |field| field.rewrite(context, Shape::legacy(item_budget, item_indent)),
939                      context.codemap.span_after(span, "{"),
940                      span.hi)
941                 .collect::<Vec<_>>();
942     // 1 = ,
943     let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
944
945     let tactic = match one_line_width {
946         Some(w) => definitive_tactic(&items, ListTactic::LimitedHorizontalVertical(w), budget),
947         None => DefinitiveListTactic::Vertical,
948     };
949
950     let fmt = ListFormatting {
951         tactic: tactic,
952         separator: ",",
953         trailing_separator: context.config.trailing_comma,
954         shape: Shape::legacy(budget, item_indent),
955         ends_with_newline: true,
956         config: context.config,
957     };
958     let items_str = try_opt!(write_list(&items, &fmt));
959     if one_line_width.is_some() && !items_str.contains('\n') {
960         Some(format!("{} {} }}", result, items_str))
961     } else {
962         Some(format!("{}\n{}{}\n{}}}",
963                      result,
964                      offset.block_indent(context.config).to_string(context.config),
965                      items_str,
966                      offset.to_string(context.config)))
967     }
968 }
969
970 fn format_tuple_struct(context: &RewriteContext,
971                        item_name: &str,
972                        ident: ast::Ident,
973                        vis: &ast::Visibility,
974                        fields: &[ast::StructField],
975                        generics: Option<&ast::Generics>,
976                        span: Span,
977                        offset: Indent)
978                        -> Option<String> {
979     let mut result = String::with_capacity(1024);
980
981     let header_str = format_header(item_name, ident, vis);
982     result.push_str(&header_str);
983
984     // FIXME(#919): don't lose comments on empty tuple structs.
985     let body_lo = if fields.is_empty() {
986         span.hi
987     } else {
988         fields[0].span.lo
989     };
990
991     let where_clause_str = match generics {
992         Some(generics) => {
993             let generics_str = try_opt!(rewrite_generics(context,
994                                                          generics,
995                                                          Shape::legacy(context.config.max_width,
996                                                                        offset),
997                                                          offset + header_str.len(),
998                                                          mk_sp(span.lo, body_lo)));
999             result.push_str(&generics_str);
1000
1001             let where_budget =
1002                 try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1003             try_opt!(rewrite_where_clause(context,
1004                                           &generics.where_clause,
1005                                           context.config.item_brace_style,
1006                                           Shape::legacy(where_budget, offset.block_only()),
1007                                           Density::Compressed,
1008                                           ";",
1009                                           true,
1010                                           false,
1011                                           None))
1012         }
1013         None => "".to_owned(),
1014     };
1015     result.push('(');
1016
1017     let item_indent = offset.block_only() + result.len();
1018     // 2 = ");"
1019     let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 2));
1020
1021     let items =
1022         itemize_list(context.codemap,
1023                      fields.iter(),
1024                      ")",
1025                      |field| {
1026             // Include attributes and doc comments, if present
1027             if !field.attrs.is_empty() {
1028                 field.attrs[0].span.lo
1029             } else {
1030                 field.span.lo
1031             }
1032         },
1033                      |field| field.ty.span.hi,
1034                      |field| field.rewrite(context, Shape::legacy(item_budget, item_indent)),
1035                      context.codemap.span_after(span, "("),
1036                      span.hi);
1037     let body = try_opt!(format_item_list(items,
1038                                          Shape::legacy(item_budget, item_indent),
1039                                          context.config));
1040
1041     if context.config.spaces_within_parens && body.len() > 0 {
1042         result.push(' ');
1043     }
1044
1045     result.push_str(&body);
1046
1047     if context.config.spaces_within_parens && body.len() > 0 {
1048         result.push(' ');
1049     }
1050
1051     result.push(')');
1052
1053     if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1054        (result.contains('\n') ||
1055         offset.block_indent + result.len() + where_clause_str.len() + 1 >
1056         context.config.max_width) {
1057         // We need to put the where clause on a new line, but we didn'to_string
1058         // know that earlier, so the where clause will not be indented properly.
1059         result.push('\n');
1060         result.push_str(&(offset.block_only() + (context.config.tab_spaces - 1))
1061                              .to_string(context.config));
1062     }
1063     result.push_str(&where_clause_str);
1064
1065     Some(result)
1066 }
1067
1068 pub fn rewrite_type_alias(context: &RewriteContext,
1069                           indent: Indent,
1070                           ident: ast::Ident,
1071                           ty: &ast::Ty,
1072                           generics: &ast::Generics,
1073                           vis: &ast::Visibility,
1074                           span: Span)
1075                           -> Option<String> {
1076     let mut result = String::new();
1077
1078     result.push_str(&format_visibility(vis));
1079     result.push_str("type ");
1080     result.push_str(&ident.to_string());
1081
1082     let generics_indent = indent + result.len();
1083     let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1084     let generics_width = context.config.max_width - " =".len();
1085     let generics_str = try_opt!(rewrite_generics(context,
1086                                                  generics,
1087                                                  Shape::legacy(generics_width, indent),
1088                                                  generics_indent,
1089                                                  generics_span));
1090
1091     result.push_str(&generics_str);
1092
1093     let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1094     let where_clause_str = try_opt!(rewrite_where_clause(context,
1095                                                          &generics.where_clause,
1096                                                          context.config.item_brace_style,
1097                                                          Shape::legacy(where_budget, indent),
1098                                                          context.config.where_density,
1099                                                          "=",
1100                                                          true,
1101                                                          false,
1102                                                          Some(span.hi)));
1103     result.push_str(&where_clause_str);
1104     result.push_str(" = ");
1105
1106     let line_width = last_line_width(&result);
1107     // This checked_sub may fail as the extra space after '=' is not taken into account
1108     // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1109     let budget = context.config
1110         .max_width
1111         .checked_sub(indent.width() + line_width + ";".len())
1112         .unwrap_or(0);
1113     let type_indent = indent + line_width;
1114     // Try to fit the type on the same line
1115     let ty_str = try_opt!(ty.rewrite(context, Shape::legacy(budget, type_indent)).or_else(|| {
1116         // The line was too short, try to put the type on the next line
1117
1118         // Remove the space after '='
1119         result.pop();
1120         let type_indent = indent.block_indent(context.config);
1121         result.push('\n');
1122         result.push_str(&type_indent.to_string(context.config));
1123         let budget = try_opt!(context.config.max_width.checked_sub(type_indent.width() +
1124                                                                    ";".len()));
1125         ty.rewrite(context, Shape::legacy(budget, type_indent))
1126     }));
1127     result.push_str(&ty_str);
1128     result.push_str(";");
1129     Some(result)
1130 }
1131
1132 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1133     (if config.space_before_type_annotation {
1134          " "
1135      } else {
1136          ""
1137      },
1138      if config.space_after_type_annotation_colon {
1139          " "
1140      } else {
1141          ""
1142      })
1143 }
1144
1145 impl Rewrite for ast::StructField {
1146     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1147         if contains_skip(&self.attrs) {
1148             let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
1149             return wrap_str(span, context.config.max_width, shape);
1150         }
1151
1152         let name = self.ident;
1153         let vis = format_visibility(&self.vis);
1154         let mut attr_str = try_opt!(self.attrs.rewrite(context,
1155                                                        Shape::legacy(context.config.max_width -
1156                                                                      shape.indent.width(),
1157                                                                      shape.indent)));
1158         if !attr_str.is_empty() {
1159             attr_str.push('\n');
1160             attr_str.push_str(&shape.indent.to_string(context.config));
1161         }
1162
1163         let type_annotation_spacing = type_annotation_spacing(context.config);
1164         let result = match name {
1165             Some(name) => {
1166                 format!("{}{}{}{}:{}",
1167                         attr_str,
1168                         vis,
1169                         name,
1170                         type_annotation_spacing.0,
1171                         type_annotation_spacing.1)
1172             }
1173             None => format!("{}{}", attr_str, vis),
1174         };
1175
1176         let last_line_width = last_line_width(&result);
1177         let budget = try_opt!(shape.width.checked_sub(last_line_width));
1178         let rewrite = try_opt!(self.ty.rewrite(context,
1179                                                Shape::legacy(budget,
1180                                                              shape.indent + last_line_width)));
1181         Some(result + &rewrite)
1182     }
1183 }
1184
1185 pub fn rewrite_static(prefix: &str,
1186                       vis: &ast::Visibility,
1187                       ident: ast::Ident,
1188                       ty: &ast::Ty,
1189                       mutability: ast::Mutability,
1190                       expr_opt: Option<&ptr::P<ast::Expr>>,
1191                       offset: Indent,
1192                       context: &RewriteContext)
1193                       -> Option<String> {
1194     let type_annotation_spacing = type_annotation_spacing(context.config);
1195     let prefix = format!("{}{} {}{}{}:{}",
1196                          format_visibility(vis),
1197                          prefix,
1198                          format_mutability(mutability),
1199                          ident,
1200                          type_annotation_spacing.0,
1201                          type_annotation_spacing.1);
1202     // 2 = " =".len()
1203     let ty_str = try_opt!(ty.rewrite(context,
1204                                      Shape::legacy(context.config.max_width - offset.block_indent -
1205                                                    prefix.len() -
1206                                                    2,
1207                                                    offset.block_only())));
1208
1209     if let Some(expr) = expr_opt {
1210         let lhs = format!("{}{} =", prefix, ty_str);
1211         // 1 = ;
1212         let remaining_width = context.config.max_width - offset.block_indent - 1;
1213         rewrite_assign_rhs(context,
1214                            lhs,
1215                            expr,
1216                            Shape::legacy(remaining_width, offset.block_only()))
1217                 .map(|s| s + ";")
1218     } else {
1219         let lhs = format!("{}{};", prefix, ty_str);
1220         Some(lhs)
1221     }
1222 }
1223
1224 pub fn rewrite_associated_type(ident: ast::Ident,
1225                                ty_opt: Option<&ptr::P<ast::Ty>>,
1226                                ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1227                                context: &RewriteContext,
1228                                indent: Indent)
1229                                -> Option<String> {
1230     let prefix = format!("type {}", ident);
1231
1232     let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1233         let bounds: &[_] = ty_param_bounds;
1234         let bound_str = try_opt!(bounds.iter()
1235             .map(|ty_bound| {
1236                 ty_bound.rewrite(context, Shape::legacy(context.config.max_width, indent))
1237             })
1238             .intersperse(Some(" + ".to_string()))
1239             .collect::<Option<String>>());
1240         if bounds.len() > 0 {
1241             format!(": {}", bound_str)
1242         } else {
1243             String::new()
1244         }
1245     } else {
1246         String::new()
1247     };
1248
1249     if let Some(ty) = ty_opt {
1250         let ty_str = try_opt!(ty.rewrite(context,
1251                                          Shape::legacy(context.config.max_width -
1252                                                        indent.block_indent -
1253                                                        prefix.len() -
1254                                                        2,
1255                                                        indent.block_only())));
1256         Some(format!("{} = {};", prefix, ty_str))
1257     } else {
1258         Some(format!("{}{};", prefix, type_bounds_str))
1259     }
1260 }
1261
1262 pub fn rewrite_associated_impl_type(ident: ast::Ident,
1263                                     defaultness: ast::Defaultness,
1264                                     ty_opt: Option<&ptr::P<ast::Ty>>,
1265                                     ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1266                                     context: &RewriteContext,
1267                                     indent: Indent)
1268                                     -> Option<String> {
1269     let result =
1270         try_opt!(rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent));
1271
1272     match defaultness {
1273         ast::Defaultness::Default => Some(format!("default {}", result)),
1274         _ => Some(result),
1275     }
1276 }
1277
1278 impl Rewrite for ast::FunctionRetTy {
1279     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1280         match *self {
1281             ast::FunctionRetTy::Default(_) => Some(String::new()),
1282             ast::FunctionRetTy::Ty(ref ty) => {
1283                 let inner_width = try_opt!(shape.width.checked_sub(3));
1284                 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3)).map(|r| {
1285                     format!("-> {}", r)
1286                 })
1287             }
1288         }
1289     }
1290 }
1291
1292 impl Rewrite for ast::Arg {
1293     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1294         if is_named_arg(self) {
1295             let mut result = try_opt!(self.pat.rewrite(context,
1296                                                        Shape::legacy(shape.width, shape.indent)));
1297
1298             if self.ty.node != ast::TyKind::Infer {
1299                 if context.config.space_before_type_annotation {
1300                     result.push_str(" ");
1301                 }
1302                 result.push_str(":");
1303                 if context.config.space_after_type_annotation_colon {
1304                     result.push_str(" ");
1305                 }
1306                 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1307                 let ty_str = try_opt!(self.ty.rewrite(context,
1308                                                       Shape::legacy(max_width,
1309                                                                     shape.indent + result.len())));
1310                 result.push_str(&ty_str);
1311             }
1312
1313             Some(result)
1314         } else {
1315             self.ty.rewrite(context, shape)
1316         }
1317     }
1318 }
1319
1320 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1321                          args: &[ast::Arg],
1322                          context: &RewriteContext)
1323                          -> Option<String> {
1324     match explicit_self.node {
1325         ast::SelfKind::Region(lt, m) => {
1326             let mut_str = format_mutability(m);
1327             match lt {
1328                 Some(ref l) => {
1329                     let lifetime_str = try_opt!(l.rewrite(context,
1330                                                           Shape::legacy(usize::max_value(),
1331                                                                         Indent::empty())));
1332                     Some(format!("&{} {}self", lifetime_str, mut_str))
1333                 }
1334                 None => Some(format!("&{}self", mut_str)),
1335             }
1336         }
1337         ast::SelfKind::Explicit(ref ty, _) => {
1338             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1339
1340             let mutability = explicit_self_mutability(&args[0]);
1341             let type_str = try_opt!(ty.rewrite(context,
1342                                                Shape::legacy(usize::max_value(), Indent::empty())));
1343
1344             Some(format!("{}self: {}", format_mutability(mutability), type_str))
1345         }
1346         ast::SelfKind::Value(_) => {
1347             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1348
1349             let mutability = explicit_self_mutability(&args[0]);
1350
1351             Some(format!("{}self", format_mutability(mutability)))
1352         }
1353     }
1354 }
1355
1356 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1357 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1358 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1359     if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1360         mutability
1361     } else {
1362         unreachable!()
1363     }
1364 }
1365
1366 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1367     if is_named_arg(arg) {
1368         arg.pat.span.lo
1369     } else {
1370         arg.ty.span.lo
1371     }
1372 }
1373
1374 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1375     match arg.ty.node {
1376         ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1377         _ => arg.ty.span.hi,
1378     }
1379 }
1380
1381 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1382     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1383         ident.node != symbol::keywords::Invalid.ident()
1384     } else {
1385         true
1386     }
1387 }
1388
1389 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1390     match *ret {
1391         ast::FunctionRetTy::Default(ref span) => span.clone(),
1392         ast::FunctionRetTy::Ty(ref ty) => ty.span,
1393     }
1394 }
1395
1396 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1397     // Note that ty.span is the span for ty.ident, not the whole item.
1398     let lo = ty.span.lo;
1399     if let Some(ref def) = ty.default {
1400         return mk_sp(lo, def.span.hi);
1401     }
1402     if ty.bounds.is_empty() {
1403         return ty.span;
1404     }
1405     let hi = match ty.bounds[ty.bounds.len() - 1] {
1406         ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1407         ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1408     };
1409     mk_sp(lo, hi)
1410 }
1411
1412 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1413     match *pred {
1414         ast::WherePredicate::BoundPredicate(ref p) => p.span,
1415         ast::WherePredicate::RegionPredicate(ref p) => p.span,
1416         ast::WherePredicate::EqPredicate(ref p) => p.span,
1417     }
1418 }
1419
1420 // Return type is (result, force_new_line_for_brace)
1421 fn rewrite_fn_base(context: &RewriteContext,
1422                    indent: Indent,
1423                    ident: ast::Ident,
1424                    fd: &ast::FnDecl,
1425                    generics: &ast::Generics,
1426                    unsafety: ast::Unsafety,
1427                    constness: ast::Constness,
1428                    defaultness: ast::Defaultness,
1429                    abi: abi::Abi,
1430                    vis: &ast::Visibility,
1431                    span: Span,
1432                    newline_brace: bool,
1433                    has_body: bool)
1434                    -> Option<(String, bool)> {
1435     let mut force_new_line_for_brace = false;
1436
1437     let where_clause = &generics.where_clause;
1438
1439     let mut result = String::with_capacity(1024);
1440     // Vis unsafety abi.
1441     result.push_str(&*format_visibility(vis));
1442
1443     if let ast::Defaultness::Default = defaultness {
1444         result.push_str("default ");
1445     }
1446
1447     if let ast::Constness::Const = constness {
1448         result.push_str("const ");
1449     }
1450
1451     result.push_str(::utils::format_unsafety(unsafety));
1452
1453     if abi != abi::Abi::Rust {
1454         result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi));
1455     }
1456
1457     // fn foo
1458     result.push_str("fn ");
1459     result.push_str(&ident.to_string());
1460
1461     // Generics.
1462     let generics_indent = indent + result.len();
1463     let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1464     let generics_str = try_opt!(rewrite_generics(context,
1465                                                  generics,
1466                                                  Shape::legacy(context.config.max_width, indent),
1467                                                  generics_indent,
1468                                                  generics_span));
1469     result.push_str(&generics_str);
1470
1471     // Note that if the width and indent really matter, we'll re-layout the
1472     // return type later anyway.
1473     let ret_str = try_opt!(fd.output.rewrite(&context,
1474                                              Shape::legacy(context.config.max_width -
1475                                                            indent.width(),
1476                                                            indent)));
1477
1478     let multi_line_ret_str = ret_str.contains('\n');
1479     let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1480
1481     // Args.
1482     let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1483         try_opt!(compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace));
1484
1485     if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1486        context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1487         arg_indent = indent.block_indent(context.config);
1488         multi_line_budget = context.config.max_width - arg_indent.width();
1489     }
1490
1491     debug!("rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1492            one_line_budget,
1493            multi_line_budget,
1494            arg_indent);
1495
1496     // Check if vertical layout was forced.
1497     if one_line_budget == 0 {
1498         if context.config.fn_args_paren_newline {
1499             result.push('\n');
1500             result.push_str(&arg_indent.to_string(context.config));
1501             arg_indent = arg_indent + 1; // extra space for `(`
1502             result.push('(');
1503             if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1504                 result.push(' ')
1505             }
1506         } else {
1507             result.push_str("(\n");
1508             result.push_str(&arg_indent.to_string(context.config));
1509         }
1510     } else {
1511         result.push('(');
1512         if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1513             result.push(' ')
1514         }
1515     }
1516
1517     if multi_line_ret_str {
1518         one_line_budget = 0;
1519     }
1520
1521     // A conservative estimation, to goal is to be over all parens in generics
1522     let args_start = generics.ty_params.last().map_or(span.lo, |tp| end_typaram(tp));
1523     let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1524                           span_for_return(&fd.output).lo);
1525     let arg_str = try_opt!(rewrite_args(context,
1526                                         &fd.inputs,
1527                                         fd.get_self().as_ref(),
1528                                         one_line_budget,
1529                                         multi_line_budget,
1530                                         indent,
1531                                         arg_indent,
1532                                         args_span,
1533                                         fd.variadic));
1534
1535     let multi_line_arg_str = arg_str.contains('\n');
1536
1537     let put_args_in_block = match context.config.fn_args_layout {
1538         FnArgLayoutStyle::Block => multi_line_arg_str,
1539         FnArgLayoutStyle::BlockAlways => true,
1540         _ => false,
1541     } && !fd.inputs.is_empty();
1542
1543     if put_args_in_block {
1544         arg_indent = indent.block_indent(context.config);
1545         result.push('\n');
1546         result.push_str(&arg_indent.to_string(context.config));
1547         result.push_str(&arg_str);
1548         result.push('\n');
1549         result.push_str(&indent.to_string(context.config));
1550         result.push(')');
1551     } else {
1552         result.push_str(&arg_str);
1553         if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1554             result.push(' ')
1555         }
1556         result.push(')');
1557     }
1558
1559     // Return type.
1560     if !ret_str.is_empty() {
1561         let ret_should_indent = match context.config.fn_args_layout {
1562             // If our args are block layout then we surely must have space.
1563             FnArgLayoutStyle::Block if put_args_in_block => false,
1564             FnArgLayoutStyle::BlockAlways => false,
1565             _ => {
1566                 // If we've already gone multi-line, or the return type would push over the max
1567                 // width, then put the return type on a new line. With the +1 for the signature
1568                 // length an additional space between the closing parenthesis of the argument and
1569                 // the arrow '->' is considered.
1570                 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1571
1572                 // If there is no where clause, take into account the space after the return type
1573                 // and the brace.
1574                 if where_clause.predicates.is_empty() {
1575                     sig_length += 2;
1576                 }
1577
1578                 let overlong_sig = sig_length > context.config.max_width;
1579
1580                 result.contains('\n') || multi_line_ret_str || overlong_sig
1581             }
1582         };
1583         let ret_indent = if ret_should_indent {
1584             let indent = match context.config.fn_return_indent {
1585                 ReturnIndent::WithWhereClause => indent + 4,
1586                 // Aligning with non-existent args looks silly.
1587                 _ if arg_str.is_empty() => {
1588                     force_new_line_for_brace = true;
1589                     indent + 4
1590                 }
1591                 // FIXME: we might want to check that using the arg indent
1592                 // doesn't blow our budget, and if it does, then fallback to
1593                 // the where clause indent.
1594                 _ => arg_indent,
1595             };
1596
1597             result.push('\n');
1598             result.push_str(&indent.to_string(context.config));
1599             indent
1600         } else {
1601             result.push(' ');
1602             Indent::new(indent.width(), result.len())
1603         };
1604
1605         if multi_line_ret_str {
1606             // Now that we know the proper indent and width, we need to
1607             // re-layout the return type.
1608             let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1609             let ret_str = try_opt!(fd.output.rewrite(context, Shape::legacy(budget, ret_indent)));
1610             result.push_str(&ret_str);
1611         } else {
1612             result.push_str(&ret_str);
1613         }
1614
1615         // Comment between return type and the end of the decl.
1616         let snippet_lo = fd.output.span().hi;
1617         if where_clause.predicates.is_empty() {
1618             let snippet_hi = span.hi;
1619             let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1620             let snippet = snippet.trim();
1621             if !snippet.is_empty() {
1622                 result.push(' ');
1623                 result.push_str(snippet);
1624             }
1625         } else {
1626             // FIXME it would be nice to catch comments between the return type
1627             // and the where clause, but we don't have a span for the where
1628             // clause.
1629         }
1630     }
1631
1632     let should_compress_where = match context.config.where_density {
1633         Density::Compressed => !result.contains('\n') || put_args_in_block,
1634         Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1635         _ => false,
1636     } || (put_args_in_block && ret_str.is_empty());
1637
1638     let where_density = if should_compress_where {
1639         Density::Compressed
1640     } else {
1641         Density::Tall
1642     };
1643
1644     // Where clause.
1645     let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1646     let where_clause_str = try_opt!(rewrite_where_clause(context,
1647                                                          where_clause,
1648                                                          context.config.fn_brace_style,
1649                                                          Shape::legacy(where_budget, indent),
1650                                                          where_density,
1651                                                          "{",
1652                                                          !has_body,
1653                                                          put_args_in_block && ret_str.is_empty(),
1654                                                          Some(span.hi)));
1655
1656     if last_line_width(&result) + where_clause_str.len() > context.config.max_width &&
1657        !where_clause_str.contains('\n') {
1658         result.push('\n');
1659     }
1660
1661     result.push_str(&where_clause_str);
1662
1663     Some((result, force_new_line_for_brace))
1664 }
1665
1666 fn rewrite_args(context: &RewriteContext,
1667                 args: &[ast::Arg],
1668                 explicit_self: Option<&ast::ExplicitSelf>,
1669                 one_line_budget: usize,
1670                 multi_line_budget: usize,
1671                 indent: Indent,
1672                 arg_indent: Indent,
1673                 span: Span,
1674                 variadic: bool)
1675                 -> Option<String> {
1676     let mut arg_item_strs =
1677         try_opt!(args.iter()
1678                      .map(|arg| {
1679                               arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
1680                           })
1681                      .collect::<Option<Vec<_>>>());
1682
1683     // Account for sugary self.
1684     // FIXME: the comment for the self argument is dropped. This is blocked
1685     // on rust issue #27522.
1686     let min_args =
1687         explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1688             .map_or(1, |self_str| {
1689                 arg_item_strs[0] = self_str;
1690                 2
1691             });
1692
1693     // Comments between args.
1694     let mut arg_items = Vec::new();
1695     if min_args == 2 {
1696         arg_items.push(ListItem::from_str(""));
1697     }
1698
1699     // FIXME(#21): if there are no args, there might still be a comment, but
1700     // without spans for the comment or parens, there is no chance of
1701     // getting it right. You also don't get to put a comment on self, unless
1702     // it is explicit.
1703     if args.len() >= min_args || variadic {
1704         let comment_span_start = if min_args == 2 {
1705             let second_arg_start = if arg_has_pattern(&args[1]) {
1706                 args[1].pat.span.lo
1707             } else {
1708                 args[1].ty.span.lo
1709             };
1710             let reduced_span = mk_sp(span.lo, second_arg_start);
1711
1712             context.codemap.span_after_last(reduced_span, ",")
1713         } else {
1714             span.lo
1715         };
1716
1717         enum ArgumentKind<'a> {
1718             Regular(&'a ast::Arg),
1719             Variadic(BytePos),
1720         }
1721
1722         let variadic_arg = if variadic {
1723             let variadic_span = mk_sp(args.last()
1724                                           .unwrap()
1725                                           .ty
1726                                           .span
1727                                           .hi,
1728                                       span.hi);
1729             let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1730             Some(ArgumentKind::Variadic(variadic_start))
1731         } else {
1732             None
1733         };
1734
1735         let more_items = itemize_list(context.codemap,
1736                                       args[min_args - 1..]
1737                                           .iter()
1738                                           .map(ArgumentKind::Regular)
1739                                           .chain(variadic_arg),
1740                                       ")",
1741                                       |arg| match *arg {
1742                                           ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1743                                           ArgumentKind::Variadic(start) => start,
1744                                       },
1745                                       |arg| match *arg {
1746                                           ArgumentKind::Regular(arg) => arg.ty.span.hi,
1747                                           ArgumentKind::Variadic(start) => start + BytePos(3),
1748                                       },
1749                                       |arg| match *arg {
1750                                           ArgumentKind::Regular(..) => None,
1751                                           ArgumentKind::Variadic(..) => Some("...".to_owned()),
1752                                       },
1753                                       comment_span_start,
1754                                       span.hi);
1755
1756         arg_items.extend(more_items);
1757     }
1758
1759     for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1760         item.item = Some(arg);
1761     }
1762
1763     let indent = match context.config.fn_arg_indent {
1764         BlockIndentStyle::Inherit => indent,
1765         BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1766         BlockIndentStyle::Visual => arg_indent,
1767     };
1768
1769     let tactic = definitive_tactic(&arg_items,
1770                                    context.config.fn_args_density.to_list_tactic(),
1771                                    one_line_budget);
1772     let budget = match tactic {
1773         DefinitiveListTactic::Horizontal => one_line_budget,
1774         _ => multi_line_budget,
1775     };
1776
1777     debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1778
1779     let (trailing_comma, end_with_newline) = match context.config.fn_args_layout {
1780         FnArgLayoutStyle::Block => (SeparatorTactic::Vertical, true),
1781         FnArgLayoutStyle::BlockAlways => (SeparatorTactic::Always, true),
1782         _ => (SeparatorTactic::Never, false),
1783     };
1784
1785     let fmt = ListFormatting {
1786         tactic: tactic,
1787         separator: ",",
1788         trailing_separator: trailing_comma,
1789         shape: Shape::legacy(budget, indent),
1790         ends_with_newline: end_with_newline,
1791         config: context.config,
1792     };
1793
1794     write_list(&arg_items, &fmt)
1795 }
1796
1797 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1798     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1799         ident.node != symbol::keywords::Invalid.ident()
1800     } else {
1801         true
1802     }
1803 }
1804
1805 fn compute_budgets_for_args(context: &RewriteContext,
1806                             result: &str,
1807                             indent: Indent,
1808                             ret_str_len: usize,
1809                             newline_brace: bool)
1810                             -> Option<((usize, usize, Indent))> {
1811     debug!("compute_budgets_for_args {} {:?}, {}, {}",
1812            result.len(),
1813            indent,
1814            ret_str_len,
1815            newline_brace);
1816     // Try keeping everything on the same line.
1817     if !result.contains('\n') {
1818         // 3 = `() `, space is before ret_string.
1819         let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1820         if !newline_brace {
1821             used_space += 2;
1822         }
1823         let one_line_budget = context.config
1824             .max_width
1825             .checked_sub(used_space)
1826             .unwrap_or(0);
1827
1828         if one_line_budget > 0 {
1829             // 4 = "() {".len()
1830             let multi_line_budget =
1831                 try_opt!(context.config.max_width.checked_sub(indent.width() + result.len() + 4));
1832
1833             return Some((one_line_budget, multi_line_budget, indent + result.len() + 1));
1834         }
1835     }
1836
1837     // Didn't work. we must force vertical layout and put args on a newline.
1838     let new_indent = indent.block_indent(context.config);
1839     let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`.
1840     let max_space = context.config.max_width;
1841     if used_space <= max_space {
1842         Some((0, max_space - used_space, new_indent))
1843     } else {
1844         // Whoops! bankrupt.
1845         None
1846     }
1847 }
1848
1849 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1850     match config.fn_brace_style {
1851         BraceStyle::AlwaysNextLine => true,
1852         BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1853         _ => false,
1854     }
1855 }
1856
1857 fn rewrite_generics(context: &RewriteContext,
1858                     generics: &ast::Generics,
1859                     shape: Shape,
1860                     // TODO shouldn't need this
1861                     generics_offset: Indent,
1862                     span: Span)
1863                     -> Option<String> {
1864     // FIXME: convert bounds to where clauses where they get too big or if
1865     // there is a where clause at all.
1866     let lifetimes: &[_] = &generics.lifetimes;
1867     let tys: &[_] = &generics.ty_params;
1868     if lifetimes.is_empty() && tys.is_empty() {
1869         return Some(String::new());
1870     }
1871
1872     let offset = match context.config.generics_indent {
1873         BlockIndentStyle::Inherit => shape.indent,
1874         BlockIndentStyle::Tabbed => shape.indent.block_indent(context.config),
1875         // 1 = <
1876         BlockIndentStyle::Visual => generics_offset + 1,
1877     };
1878
1879     let h_budget = try_opt!(shape.width.checked_sub(generics_offset.width() + 2));
1880     // FIXME: might need to insert a newline if the generics are really long.
1881
1882     // Strings for the generics.
1883     let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, Shape::legacy(h_budget, offset)));
1884     let ty_strs =
1885         tys.iter().map(|ty_param| ty_param.rewrite(context, Shape::legacy(h_budget, offset)));
1886
1887     // Extract comments between generics.
1888     let lt_spans = lifetimes.iter().map(|l| {
1889         let hi = if l.bounds.is_empty() {
1890             l.lifetime.span.hi
1891         } else {
1892             l.bounds[l.bounds.len() - 1].span.hi
1893         };
1894         mk_sp(l.lifetime.span.lo, hi)
1895     });
1896     let ty_spans = tys.iter().map(span_for_ty_param);
1897
1898     let items = itemize_list(context.codemap,
1899                              lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1900                              ">",
1901                              |&(sp, _)| sp.lo,
1902                              |&(sp, _)| sp.hi,
1903                              // FIXME: don't clone
1904                              |&(_, ref str)| str.clone(),
1905                              context.codemap.span_after(span, "<"),
1906                              span.hi);
1907     let list_str =
1908         try_opt!(format_item_list(items, Shape::legacy(h_budget, offset), context.config));
1909
1910     Some(if context.config.spaces_within_angle_brackets {
1911              format!("< {} >", list_str)
1912          } else {
1913              format!("<{}>", list_str)
1914          })
1915 }
1916
1917 fn rewrite_trait_bounds(context: &RewriteContext,
1918                         type_param_bounds: &ast::TyParamBounds,
1919                         shape: Shape)
1920                         -> Option<String> {
1921     let bounds: &[_] = type_param_bounds;
1922
1923     if bounds.is_empty() {
1924         return Some(String::new());
1925     }
1926
1927     let bound_str = try_opt!(bounds.iter()
1928                                  .map(|ty_bound| ty_bound.rewrite(&context, shape))
1929                                  .intersperse(Some(" + ".to_string()))
1930                                  .collect::<Option<String>>());
1931
1932     let mut result = String::new();
1933     result.push_str(": ");
1934     result.push_str(&bound_str);
1935     Some(result)
1936 }
1937
1938 //   fn reflow_list_node_with_rule(
1939 //        &self,
1940 //        node: &CompoundNode,
1941 //        rule: &Rule,
1942 //        args: &[Arg],
1943 //        shape: &Shape
1944 //    ) -> Result<String, ()>
1945 //    where
1946 //        T: Foo,
1947 //    {
1948
1949
1950 fn rewrite_where_clause_rfc_style(context: &RewriteContext,
1951                                   where_clause: &ast::WhereClause,
1952                                   shape: Shape,
1953                                   terminator: &str,
1954                                   suppress_comma: bool,
1955                                   // where clause can be kept on the current line.
1956                                   snuggle: bool,
1957                                   span_end: Option<BytePos>)
1958                                   -> Option<String> {
1959     let block_shape = shape.block();
1960
1961     let starting_newline = if snuggle {
1962         " ".to_owned()
1963     } else {
1964         "\n".to_owned() + &block_shape.indent.to_string(context.config)
1965     };
1966
1967     let clause_shape = block_shape.block_indent(context.config.tab_spaces);
1968     // each clause on one line, trailing comma (except if suppress_comma)
1969     let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1970     // If we don't have the start of the next span, then use the end of the
1971     // predicates, but that means we miss comments.
1972     let len = where_clause.predicates.len();
1973     let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1974     let span_end = span_end.unwrap_or(end_of_preds);
1975     let items = itemize_list(context.codemap,
1976                              where_clause.predicates.iter(),
1977                              terminator,
1978                              |pred| span_for_where_pred(pred).lo,
1979                              |pred| span_for_where_pred(pred).hi,
1980                              |pred| pred.rewrite(context, clause_shape),
1981                              span_start,
1982                              span_end);
1983     let comma_tactic = if suppress_comma {
1984         SeparatorTactic::Never
1985     } else {
1986         SeparatorTactic::Always
1987     };
1988
1989     let fmt = ListFormatting {
1990         tactic: DefinitiveListTactic::Vertical,
1991         separator: ",",
1992         trailing_separator: comma_tactic,
1993         shape: clause_shape,
1994         ends_with_newline: true,
1995         config: context.config,
1996     };
1997     let preds_str = try_opt!(write_list(items, &fmt));
1998
1999     Some(format!("{}where\n{}{}",
2000                  starting_newline,
2001                  clause_shape.indent.to_string(context.config),
2002                  preds_str))
2003 }
2004
2005 fn rewrite_where_clause(context: &RewriteContext,
2006                         where_clause: &ast::WhereClause,
2007                         brace_style: BraceStyle,
2008                         shape: Shape,
2009                         density: Density,
2010                         terminator: &str,
2011                         suppress_comma: bool,
2012                         snuggle: bool,
2013                         span_end: Option<BytePos>)
2014                         -> Option<String> {
2015     if where_clause.predicates.is_empty() {
2016         return Some(String::new());
2017     }
2018
2019     if context.config.where_style == Style::Rfc {
2020         return rewrite_where_clause_rfc_style(context,
2021                                               where_clause,
2022                                               shape,
2023                                               terminator,
2024                                               suppress_comma,
2025                                               snuggle,
2026                                               span_end);
2027     }
2028
2029     let extra_indent = match context.config.where_indent {
2030         BlockIndentStyle::Inherit => Indent::empty(),
2031         BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => {
2032             Indent::new(context.config.tab_spaces, 0)
2033         }
2034     };
2035
2036     let offset = match context.config.where_pred_indent {
2037         BlockIndentStyle::Inherit => shape.indent + extra_indent,
2038         BlockIndentStyle::Tabbed => shape.indent + extra_indent.block_indent(context.config),
2039         // 6 = "where ".len()
2040         BlockIndentStyle::Visual => shape.indent + extra_indent + 6,
2041     };
2042     // FIXME: if where_pred_indent != Visual, then the budgets below might
2043     // be out by a char or two.
2044
2045     let budget = context.config.max_width - offset.width();
2046     let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
2047     // If we don't have the start of the next span, then use the end of the
2048     // predicates, but that means we miss comments.
2049     let len = where_clause.predicates.len();
2050     let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
2051     let span_end = span_end.unwrap_or(end_of_preds);
2052     let items = itemize_list(context.codemap,
2053                              where_clause.predicates.iter(),
2054                              terminator,
2055                              |pred| span_for_where_pred(pred).lo,
2056                              |pred| span_for_where_pred(pred).hi,
2057                              |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2058                              span_start,
2059                              span_end);
2060     let item_vec = items.collect::<Vec<_>>();
2061     // FIXME: we don't need to collect here if the where_layout isn't
2062     // HorizontalVertical.
2063     let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
2064
2065     let mut comma_tactic = context.config.trailing_comma;
2066     // Kind of a hack because we don't usually have trailing commas in where clauses.
2067     if comma_tactic == SeparatorTactic::Vertical || suppress_comma {
2068         comma_tactic = SeparatorTactic::Never;
2069     }
2070
2071     let fmt = ListFormatting {
2072         tactic: tactic,
2073         separator: ",",
2074         trailing_separator: comma_tactic,
2075         shape: Shape::legacy(budget, offset),
2076         ends_with_newline: true,
2077         config: context.config,
2078     };
2079     let preds_str = try_opt!(write_list(&item_vec, &fmt));
2080
2081     let end_length = if terminator == "{" {
2082         // If the brace is on the next line we don't need to count it otherwise it needs two
2083         // characters " {"
2084         match brace_style {
2085             BraceStyle::AlwaysNextLine |
2086             BraceStyle::SameLineWhere => 0,
2087             BraceStyle::PreferSameLine => 2,
2088         }
2089     } else if terminator == "=" {
2090         2
2091     } else {
2092         terminator.len()
2093     };
2094     if density == Density::Tall || preds_str.contains('\n') ||
2095        shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width {
2096         Some(format!("\n{}where {}",
2097                      (shape.indent + extra_indent).to_string(context.config),
2098                      preds_str))
2099     } else {
2100         Some(format!(" where {}", preds_str))
2101     }
2102 }
2103
2104 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2105     format!("{}{}{}", format_visibility(vis), item_name, ident)
2106 }
2107
2108 fn format_generics(context: &RewriteContext,
2109                    generics: &ast::Generics,
2110                    opener: &str,
2111                    terminator: &str,
2112                    brace_style: BraceStyle,
2113                    force_same_line_brace: bool,
2114                    offset: Indent,
2115                    generics_offset: Indent,
2116                    span: Span)
2117                    -> Option<String> {
2118     let mut result = try_opt!(rewrite_generics(context,
2119                                                generics,
2120                                                Shape::legacy(context.config.max_width, offset),
2121                                                generics_offset,
2122                                                span));
2123
2124     if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2125         let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
2126         let where_clause_str = try_opt!(rewrite_where_clause(context,
2127                                                              &generics.where_clause,
2128                                                              brace_style,
2129                                                              Shape::legacy(budget,
2130                                                                            offset.block_only()),
2131                                                              Density::Tall,
2132                                                              terminator,
2133                                                              false,
2134                                                              false,
2135                                                              Some(span.hi)));
2136         result.push_str(&where_clause_str);
2137         if !force_same_line_brace &&
2138            (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
2139             result.push('\n');
2140             result.push_str(&offset.block_only().to_string(context.config));
2141         } else {
2142             result.push(' ');
2143         }
2144         result.push_str(opener);
2145     } else {
2146         if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
2147             result.push('\n');
2148             result.push_str(&offset.block_only().to_string(context.config));
2149         } else {
2150             result.push(' ');
2151         }
2152         result.push_str(opener);
2153     }
2154
2155     Some(result)
2156 }