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