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