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