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