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