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