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