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