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