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