]> git.lizzy.rs Git - rust.git/blob - src/items.rs
Merge pull request #1119 from HighCommander4/issue1109b
[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, type_annotation_separator};
20 use comment::{FindUncommented, contains_comment};
21 use visitor::FmtVisitor;
22 use rewrite::{Rewrite, RewriteContext};
23 use config::{Config, BlockIndentStyle, Density, ReturnIndent, BraceStyle, FnArgLayoutStyle};
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                 let separator = type_annotation_separator(context.config);
49                 let indent = offset + last_line_width(&result) + separator.len();
50                 // 1 = ;
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(separator);
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 fn type_annotation_spacing(config: &Config) -> &str {
1002     if config.space_before_type_annotation {
1003         " "
1004     } else {
1005         ""
1006     }
1007 }
1008
1009 impl Rewrite for ast::StructField {
1010     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1011         if contains_skip(&self.attrs) {
1012             let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
1013             return wrap_str(span, context.config.max_width, width, offset);
1014         }
1015
1016         let name = self.ident;
1017         let vis = format_visibility(&self.vis);
1018         let mut attr_str = try_opt!(self.attrs
1019             .rewrite(context, context.config.max_width - offset.width(), offset));
1020         if !attr_str.is_empty() {
1021             attr_str.push('\n');
1022             attr_str.push_str(&offset.to_string(context.config));
1023         }
1024
1025         let type_annotation_spacing = type_annotation_spacing(context.config);
1026         let result = match name {
1027             Some(name) => format!("{}{}{}{}: ", attr_str, vis, name, type_annotation_spacing),
1028             None => format!("{}{}", attr_str, vis),
1029         };
1030
1031         let last_line_width = last_line_width(&result);
1032         let budget = try_opt!(width.checked_sub(last_line_width));
1033         let rewrite = try_opt!(self.ty.rewrite(context, budget, offset + last_line_width));
1034         Some(result + &rewrite)
1035     }
1036 }
1037
1038 pub fn rewrite_static(prefix: &str,
1039                       vis: &ast::Visibility,
1040                       ident: ast::Ident,
1041                       ty: &ast::Ty,
1042                       mutability: ast::Mutability,
1043                       expr_opt: Option<&ptr::P<ast::Expr>>,
1044                       context: &RewriteContext)
1045                       -> Option<String> {
1046     let type_annotation_spacing = type_annotation_spacing(context.config);
1047     let prefix = format!("{}{} {}{}{}: ",
1048                          format_visibility(vis),
1049                          prefix,
1050                          format_mutability(mutability),
1051                          ident,
1052                          type_annotation_spacing);
1053     // 2 = " =".len()
1054     let ty_str = try_opt!(ty.rewrite(context,
1055                                      context.config.max_width - context.block_indent.width() -
1056                                      prefix.len() - 2,
1057                                      context.block_indent));
1058
1059     if let Some(ref expr) = expr_opt {
1060         let lhs = format!("{}{} =", prefix, ty_str);
1061         // 1 = ;
1062         let remaining_width = context.config.max_width - context.block_indent.width() - 1;
1063         rewrite_assign_rhs(context, lhs, expr, remaining_width, context.block_indent)
1064             .map(|s| s + ";")
1065     } else {
1066         let lhs = format!("{}{};", prefix, ty_str);
1067         Some(lhs)
1068     }
1069 }
1070
1071 pub fn rewrite_associated_type(ident: ast::Ident,
1072                                ty_opt: Option<&ptr::P<ast::Ty>>,
1073                                ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1074                                context: &RewriteContext,
1075                                indent: Indent)
1076                                -> Option<String> {
1077     let prefix = format!("type {}", ident);
1078
1079     let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1080         let bounds: &[_] = &ty_param_bounds;
1081         let bound_str = try_opt!(bounds.iter()
1082             .map(|ty_bound| ty_bound.rewrite(context, context.config.max_width, indent))
1083             .intersperse(Some(" + ".to_string()))
1084             .collect::<Option<String>>());
1085         if bounds.len() > 0 {
1086             format!(": {}", bound_str)
1087         } else {
1088             String::new()
1089         }
1090     } else {
1091         String::new()
1092     };
1093
1094     if let Some(ty) = ty_opt {
1095         let ty_str = try_opt!(ty.rewrite(context,
1096                                          context.config.max_width - context.block_indent.width() -
1097                                          prefix.len() -
1098                                          2,
1099                                          context.block_indent));
1100         Some(format!("{} = {};", prefix, ty_str))
1101     } else {
1102         Some(format!("{}{};", prefix, type_bounds_str))
1103     }
1104 }
1105
1106 impl Rewrite for ast::FunctionRetTy {
1107     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1108         match *self {
1109             ast::FunctionRetTy::Default(_) => Some(String::new()),
1110             ast::FunctionRetTy::None(_) => {
1111                 if width >= 4 {
1112                     Some("-> !".to_owned())
1113                 } else {
1114                     None
1115                 }
1116             }
1117             ast::FunctionRetTy::Ty(ref ty) => {
1118                 let inner_width = try_opt!(width.checked_sub(3));
1119                 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1120             }
1121         }
1122     }
1123 }
1124
1125 impl Rewrite for ast::Arg {
1126     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1127         if is_named_arg(self) {
1128             let mut result = try_opt!(self.pat.rewrite(context, width, offset));
1129
1130             if self.ty.node != ast::TyKind::Infer {
1131                 if context.config.space_before_type_annotation {
1132                     result.push_str(" ");
1133                 }
1134                 result.push_str(": ");
1135                 let max_width = try_opt!(width.checked_sub(result.len()));
1136                 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1137                 result.push_str(&ty_str);
1138             }
1139
1140             Some(result)
1141         } else {
1142             self.ty.rewrite(context, width, offset)
1143         }
1144     }
1145 }
1146
1147 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1148                          args: &[ast::Arg],
1149                          context: &RewriteContext)
1150                          -> Option<String> {
1151     match explicit_self.node {
1152         ast::SelfKind::Region(lt, m) => {
1153             let mut_str = format_mutability(m);
1154             match lt {
1155                 Some(ref l) => {
1156                     let lifetime_str =
1157                         try_opt!(l.rewrite(context, usize::max_value(), Indent::empty()));
1158                     Some(format!("&{} {}self", lifetime_str, mut_str))
1159                 }
1160                 None => Some(format!("&{}self", mut_str)),
1161             }
1162         }
1163         ast::SelfKind::Explicit(ref ty, _) => {
1164             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1165
1166             let mutability = explicit_self_mutability(&args[0]);
1167             let type_str = try_opt!(ty.rewrite(context, usize::max_value(), Indent::empty()));
1168
1169             Some(format!("{}self: {}", format_mutability(mutability), type_str))
1170         }
1171         ast::SelfKind::Value(_) => {
1172             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1173
1174             let mutability = explicit_self_mutability(&args[0]);
1175
1176             Some(format!("{}self", format_mutability(mutability)))
1177         }
1178     }
1179 }
1180
1181 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1182 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1183 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1184     if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1185         mutability
1186     } else {
1187         unreachable!()
1188     }
1189 }
1190
1191 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1192     if is_named_arg(arg) {
1193         arg.pat.span.lo
1194     } else {
1195         arg.ty.span.lo
1196     }
1197 }
1198
1199 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1200     match arg.ty.node {
1201         ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1202         _ => arg.ty.span.hi,
1203     }
1204 }
1205
1206 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1207     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1208         ident.node != token::keywords::Invalid.ident()
1209     } else {
1210         true
1211     }
1212 }
1213
1214 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1215     match *ret {
1216         ast::FunctionRetTy::None(ref span) |
1217         ast::FunctionRetTy::Default(ref span) => span.clone(),
1218         ast::FunctionRetTy::Ty(ref ty) => ty.span,
1219     }
1220 }
1221
1222 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1223     // Note that ty.span is the span for ty.ident, not the whole item.
1224     let lo = ty.span.lo;
1225     if let Some(ref def) = ty.default {
1226         return mk_sp(lo, def.span.hi);
1227     }
1228     if ty.bounds.is_empty() {
1229         return ty.span;
1230     }
1231     let hi = match ty.bounds[ty.bounds.len() - 1] {
1232         ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1233         ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1234     };
1235     mk_sp(lo, hi)
1236 }
1237
1238 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1239     match *pred {
1240         ast::WherePredicate::BoundPredicate(ref p) => p.span,
1241         ast::WherePredicate::RegionPredicate(ref p) => p.span,
1242         ast::WherePredicate::EqPredicate(ref p) => p.span,
1243     }
1244 }
1245
1246 // Return type is (result, force_new_line_for_brace)
1247 fn rewrite_fn_base(context: &RewriteContext,
1248                    indent: Indent,
1249                    ident: ast::Ident,
1250                    fd: &ast::FnDecl,
1251                    generics: &ast::Generics,
1252                    unsafety: ast::Unsafety,
1253                    constness: ast::Constness,
1254                    defaultness: ast::Defaultness,
1255                    abi: abi::Abi,
1256                    vis: &ast::Visibility,
1257                    span: Span,
1258                    newline_brace: bool,
1259                    has_body: bool)
1260                    -> Option<(String, bool)> {
1261     let mut force_new_line_for_brace = false;
1262     // FIXME we'll lose any comments in between parts of the function decl, but
1263     // anyone who comments there probably deserves what they get.
1264
1265     let where_clause = &generics.where_clause;
1266
1267     let mut result = String::with_capacity(1024);
1268     // Vis unsafety abi.
1269     result.push_str(&*format_visibility(vis));
1270
1271     if let ast::Defaultness::Default = defaultness {
1272         result.push_str("default ");
1273     }
1274
1275     if let ast::Constness::Const = constness {
1276         result.push_str("const ");
1277     }
1278
1279     result.push_str(::utils::format_unsafety(unsafety));
1280
1281     if abi != abi::Abi::Rust {
1282         result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi));
1283     }
1284
1285     // fn foo
1286     result.push_str("fn ");
1287     result.push_str(&ident.to_string());
1288
1289     // Generics.
1290     let generics_indent = indent + result.len();
1291     let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1292     let generics_str = try_opt!(rewrite_generics(context,
1293                                                  generics,
1294                                                  indent,
1295                                                  context.config.max_width,
1296                                                  generics_indent,
1297                                                  generics_span));
1298     result.push_str(&generics_str);
1299
1300     // Note that if the width and indent really matter, we'll re-layout the
1301     // return type later anyway.
1302     let ret_str = try_opt!(fd.output
1303         .rewrite(&context, context.config.max_width - indent.width(), indent));
1304
1305     let multi_line_ret_str = ret_str.contains('\n');
1306     let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1307
1308     // Args.
1309     let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1310         try_opt!(compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace));
1311
1312     if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1313        context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1314         arg_indent = indent.block_indent(context.config);
1315         multi_line_budget = context.config.max_width - arg_indent.width();
1316     }
1317
1318     debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1319            one_line_budget,
1320            multi_line_budget,
1321            arg_indent);
1322
1323     // Check if vertical layout was forced by compute_budget_for_args.
1324     if one_line_budget == 0 {
1325         if context.config.fn_args_paren_newline {
1326             result.push('\n');
1327             result.push_str(&arg_indent.to_string(context.config));
1328             arg_indent = arg_indent + 1; // extra space for `(`
1329             result.push('(');
1330         } else {
1331             result.push_str("(\n");
1332             result.push_str(&arg_indent.to_string(context.config));
1333         }
1334     } else {
1335         result.push('(');
1336     }
1337
1338     if multi_line_ret_str {
1339         one_line_budget = 0;
1340     }
1341
1342     // A conservative estimation, to goal is to be over all parens in generics
1343     let args_start = generics.ty_params
1344         .last()
1345         .map_or(span.lo, |tp| end_typaram(tp));
1346     let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1347                           span_for_return(&fd.output).lo);
1348     let arg_str = try_opt!(rewrite_args(context,
1349                                         &fd.inputs,
1350                                         fd.get_self().as_ref(),
1351                                         one_line_budget,
1352                                         multi_line_budget,
1353                                         indent,
1354                                         arg_indent,
1355                                         args_span,
1356                                         fd.variadic));
1357
1358     let multi_line_arg_str = arg_str.contains('\n');
1359
1360     let put_args_in_block = match context.config.fn_args_layout {
1361         FnArgLayoutStyle::Block => multi_line_arg_str,
1362         FnArgLayoutStyle::BlockAlways => true,
1363         _ => false,
1364     } && fd.inputs.len() > 0;
1365
1366     if put_args_in_block {
1367         arg_indent = indent.block_indent(context.config);
1368         result.push('\n');
1369         result.push_str(&arg_indent.to_string(context.config));
1370         result.push_str(&arg_str);
1371         result.push('\n');
1372         result.push_str(&indent.to_string(context.config));
1373         result.push(')');
1374     } else {
1375         result.push_str(&arg_str);
1376         result.push(')');
1377     }
1378
1379     // Return type.
1380     if !ret_str.is_empty() {
1381         let ret_should_indent = match context.config.fn_args_layout {
1382             // If our args are block layout then we surely must have space.
1383             FnArgLayoutStyle::Block if put_args_in_block => false,
1384             FnArgLayoutStyle::BlockAlways => false,
1385             _ => {
1386                 // If we've already gone multi-line, or the return type would push over the max
1387                 // width, then put the return type on a new line. With the +1 for the signature
1388                 // length an additional space between the closing parenthesis of the argument and
1389                 // the arrow '->' is considered.
1390                 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1391
1392                 // If there is no where clause, take into account the space after the return type
1393                 // and the brace.
1394                 if where_clause.predicates.is_empty() {
1395                     sig_length += 2;
1396                 }
1397
1398                 let overlong_sig = sig_length > context.config.max_width;
1399
1400                 result.contains("\n") || multi_line_ret_str || overlong_sig
1401             }
1402         };
1403         let ret_indent = if ret_should_indent {
1404             let indent = match context.config.fn_return_indent {
1405                 ReturnIndent::WithWhereClause => indent + 4,
1406                 // Aligning with non-existent args looks silly.
1407                 _ if arg_str.is_empty() => {
1408                     force_new_line_for_brace = true;
1409                     indent + 4
1410                 }
1411                 // FIXME: we might want to check that using the arg indent
1412                 // doesn't blow our budget, and if it does, then fallback to
1413                 // the where clause indent.
1414                 _ => arg_indent,
1415             };
1416
1417             result.push('\n');
1418             result.push_str(&indent.to_string(context.config));
1419             indent
1420         } else {
1421             result.push(' ');
1422             Indent::new(indent.width(), result.len())
1423         };
1424
1425         if multi_line_ret_str {
1426             // Now that we know the proper indent and width, we need to
1427             // re-layout the return type.
1428             let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1429             let ret_str = try_opt!(fd.output.rewrite(context, budget, ret_indent));
1430             result.push_str(&ret_str);
1431         } else {
1432             result.push_str(&ret_str);
1433         }
1434
1435         // Comment between return type and the end of the decl.
1436         let snippet_lo = fd.output.span().hi;
1437         if where_clause.predicates.is_empty() {
1438             let snippet_hi = span.hi;
1439             let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1440             let snippet = snippet.trim();
1441             if !snippet.is_empty() {
1442                 result.push(' ');
1443                 result.push_str(snippet);
1444             }
1445         } else {
1446             // FIXME it would be nice to catch comments between the return type
1447             // and the where clause, but we don't have a span for the where
1448             // clause.
1449         }
1450     }
1451
1452     let should_compress_where = match context.config.where_density {
1453         Density::Compressed => !result.contains('\n') || put_args_in_block,
1454         Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1455         _ => false,
1456     } || (put_args_in_block && ret_str.is_empty());
1457
1458     let where_density = if should_compress_where {
1459         Density::Compressed
1460     } else {
1461         Density::Tall
1462     };
1463
1464     // Where clause.
1465     let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1466     let where_clause_str = try_opt!(rewrite_where_clause(context,
1467                                                          where_clause,
1468                                                          context.config,
1469                                                          context.config.fn_brace_style,
1470                                                          indent,
1471                                                          where_budget,
1472                                                          where_density,
1473                                                          "{",
1474                                                          has_body,
1475                                                          Some(span.hi)));
1476
1477     if last_line_width(&result) + where_clause_str.len() > context.config.max_width &&
1478        !where_clause_str.contains('\n') {
1479         result.push('\n');
1480     }
1481
1482     result.push_str(&where_clause_str);
1483
1484     Some((result, force_new_line_for_brace))
1485 }
1486
1487 fn rewrite_args(context: &RewriteContext,
1488                 args: &[ast::Arg],
1489                 explicit_self: Option<&ast::ExplicitSelf>,
1490                 one_line_budget: usize,
1491                 multi_line_budget: usize,
1492                 indent: Indent,
1493                 arg_indent: Indent,
1494                 span: Span,
1495                 variadic: bool)
1496                 -> Option<String> {
1497     let mut arg_item_strs = try_opt!(args.iter()
1498         .map(|arg| arg.rewrite(&context, multi_line_budget, arg_indent))
1499         .collect::<Option<Vec<_>>>());
1500
1501     // Account for sugary self.
1502     // FIXME: the comment for the self argument is dropped. This is blocked
1503     // on rust issue #27522.
1504     let min_args =
1505         explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1506             .map_or(1, |self_str| {
1507                 arg_item_strs[0] = self_str;
1508                 2
1509             });
1510
1511     // Comments between args.
1512     let mut arg_items = Vec::new();
1513     if min_args == 2 {
1514         arg_items.push(ListItem::from_str(""));
1515     }
1516
1517     // FIXME(#21): if there are no args, there might still be a comment, but
1518     // without spans for the comment or parens, there is no chance of
1519     // getting it right. You also don't get to put a comment on self, unless
1520     // it is explicit.
1521     if args.len() >= min_args || variadic {
1522         let comment_span_start = if min_args == 2 {
1523             let second_arg_start = if arg_has_pattern(&args[1]) {
1524                 args[1].pat.span.lo
1525             } else {
1526                 args[1].ty.span.lo
1527             };
1528             let reduced_span = mk_sp(span.lo, second_arg_start);
1529
1530             context.codemap.span_after_last(reduced_span, ",")
1531         } else {
1532             span.lo
1533         };
1534
1535         enum ArgumentKind<'a> {
1536             Regular(&'a ast::Arg),
1537             Variadic(BytePos),
1538         }
1539
1540         let variadic_arg = if variadic {
1541             let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1542             let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1543             Some(ArgumentKind::Variadic(variadic_start))
1544         } else {
1545             None
1546         };
1547
1548         let more_items = itemize_list(context.codemap,
1549                                       args[min_args - 1..]
1550                                           .iter()
1551                                           .map(ArgumentKind::Regular)
1552                                           .chain(variadic_arg),
1553                                       ")",
1554                                       |arg| {
1555                                           match *arg {
1556                                               ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1557                                               ArgumentKind::Variadic(start) => start,
1558                                           }
1559                                       },
1560                                       |arg| {
1561                                           match *arg {
1562                                               ArgumentKind::Regular(arg) => arg.ty.span.hi,
1563                                               ArgumentKind::Variadic(start) => start + BytePos(3),
1564                                           }
1565                                       },
1566                                       |arg| {
1567                                           match *arg {
1568                                               ArgumentKind::Regular(..) => None,
1569                                               ArgumentKind::Variadic(..) => Some("...".to_owned()),
1570                                           }
1571                                       },
1572                                       comment_span_start,
1573                                       span.hi);
1574
1575         arg_items.extend(more_items);
1576     }
1577
1578     for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1579         item.item = Some(arg);
1580     }
1581
1582     let indent = match context.config.fn_arg_indent {
1583         BlockIndentStyle::Inherit => indent,
1584         BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1585         BlockIndentStyle::Visual => arg_indent,
1586     };
1587
1588     let tactic = definitive_tactic(&arg_items,
1589                                    context.config.fn_args_density.to_list_tactic(),
1590                                    one_line_budget);
1591     let budget = match tactic {
1592         DefinitiveListTactic::Horizontal => one_line_budget,
1593         _ => multi_line_budget,
1594     };
1595
1596     debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1597
1598     let end_with_newline = match context.config.fn_args_layout {
1599         FnArgLayoutStyle::Block |
1600         FnArgLayoutStyle::BlockAlways => true,
1601         _ => false,
1602     };
1603
1604     let fmt = ListFormatting {
1605         tactic: tactic,
1606         separator: ",",
1607         trailing_separator: SeparatorTactic::Never,
1608         indent: indent,
1609         width: budget,
1610         ends_with_newline: end_with_newline,
1611         config: context.config,
1612     };
1613
1614     write_list(&arg_items, &fmt)
1615 }
1616
1617 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1618     if let ast::PatKind::Ident(_,
1619                                codemap::Spanned {
1620                                    node: ast::Ident { name: ast::Name(0u32), .. },
1621                                    ..
1622                                },
1623                                _) = arg.pat.node {
1624         false
1625     } else {
1626         true
1627     }
1628 }
1629
1630 fn compute_budgets_for_args(context: &RewriteContext,
1631                             result: &str,
1632                             indent: Indent,
1633                             ret_str_len: usize,
1634                             newline_brace: bool)
1635                             -> Option<((usize, usize, Indent))> {
1636     // Try keeping everything on the same line.
1637     if !result.contains("\n") {
1638         // 3 = `() `, space is before ret_string.
1639         let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1640         if !newline_brace {
1641             used_space += 2;
1642         }
1643         let one_line_budget = context.config.max_width.checked_sub(used_space).unwrap_or(0);
1644
1645         if one_line_budget > 0 {
1646             // 4 = "() {".len()
1647             let multi_line_budget =
1648                 try_opt!(context.config.max_width.checked_sub(indent.width() + result.len() + 4));
1649
1650             return Some((one_line_budget, multi_line_budget, indent + result.len() + 1));
1651         }
1652     }
1653
1654     // Didn't work. we must force vertical layout and put args on a newline.
1655     let new_indent = indent.block_indent(context.config);
1656     let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`.
1657     let max_space = context.config.max_width;
1658     if used_space <= max_space {
1659         Some((0, max_space - used_space, new_indent))
1660     } else {
1661         // Whoops! bankrupt.
1662         None
1663     }
1664 }
1665
1666 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1667     match config.fn_brace_style {
1668         BraceStyle::AlwaysNextLine => true,
1669         BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1670         _ => false,
1671     }
1672 }
1673
1674 fn rewrite_generics(context: &RewriteContext,
1675                     generics: &ast::Generics,
1676                     offset: Indent,
1677                     width: usize,
1678                     generics_offset: Indent,
1679                     span: Span)
1680                     -> Option<String> {
1681     // FIXME: convert bounds to where clauses where they get too big or if
1682     // there is a where clause at all.
1683     let lifetimes: &[_] = &generics.lifetimes;
1684     let tys: &[_] = &generics.ty_params;
1685     if lifetimes.is_empty() && tys.is_empty() {
1686         return Some(String::new());
1687     }
1688
1689     let offset = match context.config.generics_indent {
1690         BlockIndentStyle::Inherit => offset,
1691         BlockIndentStyle::Tabbed => offset.block_indent(context.config),
1692         // 1 = <
1693         BlockIndentStyle::Visual => generics_offset + 1,
1694     };
1695
1696     let h_budget = try_opt!(width.checked_sub(generics_offset.width() + 2));
1697     // FIXME: might need to insert a newline if the generics are really long.
1698
1699     // Strings for the generics.
1700     let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset));
1701     let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(&context, h_budget, offset));
1702
1703     // Extract comments between generics.
1704     let lt_spans = lifetimes.iter().map(|l| {
1705         let hi = if l.bounds.is_empty() {
1706             l.lifetime.span.hi
1707         } else {
1708             l.bounds[l.bounds.len() - 1].span.hi
1709         };
1710         mk_sp(l.lifetime.span.lo, hi)
1711     });
1712     let ty_spans = tys.iter().map(span_for_ty_param);
1713
1714     let items = itemize_list(context.codemap,
1715                              lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1716                              ">",
1717                              |&(sp, _)| sp.lo,
1718                              |&(sp, _)| sp.hi,
1719                              // FIXME: don't clone
1720                              |&(_, ref str)| str.clone(),
1721                              context.codemap.span_after(span, "<"),
1722                              span.hi);
1723     let list_str = try_opt!(format_item_list(items, h_budget, offset, context.config));
1724
1725     Some(format!("<{}>", list_str))
1726 }
1727
1728 fn rewrite_trait_bounds(context: &RewriteContext,
1729                         type_param_bounds: &ast::TyParamBounds,
1730                         indent: Indent,
1731                         width: usize)
1732                         -> Option<String> {
1733     let bounds: &[_] = &type_param_bounds;
1734
1735     if bounds.is_empty() {
1736         return Some(String::new());
1737     }
1738
1739     let bound_str = try_opt!(bounds.iter()
1740         .map(|ty_bound| ty_bound.rewrite(&context, width, indent))
1741         .intersperse(Some(" + ".to_string()))
1742         .collect::<Option<String>>());
1743
1744     let mut result = String::new();
1745     result.push_str(": ");
1746     result.push_str(&bound_str);
1747     Some(result)
1748 }
1749
1750 fn rewrite_where_clause(context: &RewriteContext,
1751                         where_clause: &ast::WhereClause,
1752                         config: &Config,
1753                         brace_style: BraceStyle,
1754                         indent: Indent,
1755                         width: usize,
1756                         density: Density,
1757                         terminator: &str,
1758                         allow_trailing_comma: bool,
1759                         span_end: Option<BytePos>)
1760                         -> Option<String> {
1761     if where_clause.predicates.is_empty() {
1762         return Some(String::new());
1763     }
1764
1765     let extra_indent = match context.config.where_indent {
1766         BlockIndentStyle::Inherit => Indent::empty(),
1767         BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces, 0),
1768     };
1769
1770     let offset = match context.config.where_pred_indent {
1771         BlockIndentStyle::Inherit => indent + extra_indent,
1772         BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
1773         // 6 = "where ".len()
1774         BlockIndentStyle::Visual => indent + extra_indent + 6,
1775     };
1776     // FIXME: if where_pred_indent != Visual, then the budgets below might
1777     // be out by a char or two.
1778
1779     let budget = context.config.max_width - offset.width();
1780     let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1781     // If we don't have the start of the next span, then use the end of the
1782     // predicates, but that means we miss comments.
1783     let len = where_clause.predicates.len();
1784     let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1785     let span_end = span_end.unwrap_or(end_of_preds);
1786     let items = itemize_list(context.codemap,
1787                              where_clause.predicates.iter(),
1788                              terminator,
1789                              |pred| span_for_where_pred(pred).lo,
1790                              |pred| span_for_where_pred(pred).hi,
1791                              |pred| pred.rewrite(&context, budget, offset),
1792                              span_start,
1793                              span_end);
1794     let item_vec = items.collect::<Vec<_>>();
1795     // FIXME: we don't need to collect here if the where_layout isn't
1796     // HorizontalVertical.
1797     let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
1798     let use_trailing_comma = allow_trailing_comma && context.config.where_trailing_comma;
1799
1800     let fmt = ListFormatting {
1801         tactic: tactic,
1802         separator: ",",
1803         trailing_separator: SeparatorTactic::from_bool(use_trailing_comma),
1804         indent: offset,
1805         width: budget,
1806         ends_with_newline: true,
1807         config: context.config,
1808     };
1809     let preds_str = try_opt!(write_list(&item_vec, &fmt));
1810
1811     let end_length = if terminator == "{" {
1812         // If the brace is on the next line we don't need to count it otherwise it needs two
1813         // characters " {"
1814         match brace_style {
1815             BraceStyle::AlwaysNextLine => 0,
1816             BraceStyle::PreferSameLine => 2,
1817             BraceStyle::SameLineWhere => 0,
1818         }
1819     } else if terminator == "=" {
1820         2
1821     } else {
1822         terminator.len()
1823     };
1824     if density == Density::Tall || preds_str.contains('\n') ||
1825        indent.width() + " where ".len() + preds_str.len() + end_length > width {
1826         Some(format!("\n{}where {}",
1827                      (indent + extra_indent).to_string(context.config),
1828                      preds_str))
1829     } else {
1830         Some(format!(" where {}", preds_str))
1831     }
1832 }
1833
1834 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1835     format!("{}{}{}", format_visibility(vis), item_name, ident)
1836 }
1837
1838 fn format_generics(context: &RewriteContext,
1839                    generics: &ast::Generics,
1840                    opener: &str,
1841                    terminator: &str,
1842                    brace_style: BraceStyle,
1843                    force_same_line_brace: bool,
1844                    offset: Indent,
1845                    generics_offset: Indent,
1846                    span: Span)
1847                    -> Option<String> {
1848     let mut result = try_opt!(rewrite_generics(context,
1849                                                generics,
1850                                                offset,
1851                                                context.config.max_width,
1852                                                generics_offset,
1853                                                span));
1854
1855     if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
1856         let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1857         let where_clause_str = try_opt!(rewrite_where_clause(context,
1858                                                              &generics.where_clause,
1859                                                              context.config,
1860                                                              brace_style,
1861                                                              context.block_indent,
1862                                                              budget,
1863                                                              Density::Tall,
1864                                                              terminator,
1865                                                              true,
1866                                                              Some(span.hi)));
1867         result.push_str(&where_clause_str);
1868         if !force_same_line_brace &&
1869            (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
1870             result.push('\n');
1871             result.push_str(&context.block_indent.to_string(context.config));
1872         } else {
1873             result.push(' ');
1874         }
1875         result.push_str(opener);
1876     } else {
1877         if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
1878             result.push('\n');
1879             result.push_str(&context.block_indent.to_string(context.config));
1880         } else {
1881             result.push(' ');
1882         }
1883         result.push_str(opener);
1884     }
1885
1886     Some(result)
1887 }