]> git.lizzy.rs Git - rust.git/blob - src/items.rs
Update to the latest syntex module
[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, codemap, ptr, symbol};
27 use syntax::codemap::{Span, BytePos, mk_sp};
28 use syntax::ast::ImplItem;
29
30 // Statements of the form
31 // let pat: ty = init;
32 impl Rewrite for ast::Local {
33     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
34         let mut result = "let ".to_owned();
35         let pattern_offset = offset + result.len();
36         // 1 = ;
37         let pattern_width = try_opt!(width.checked_sub(pattern_offset.width() + 1));
38
39         let pat_str = try_opt!(self.pat.rewrite(&context, pattern_width, pattern_offset));
40         result.push_str(&pat_str);
41
42         // String that is placed within the assignment pattern and expression.
43         let infix = {
44             let mut infix = String::new();
45
46             if let Some(ref ty) = self.ty {
47                 let separator = type_annotation_separator(context.config);
48                 let indent = offset + last_line_width(&result) + separator.len();
49                 // 1 = ;
50                 let budget = try_opt!(width.checked_sub(indent.width() + 1));
51                 let rewrite = try_opt!(ty.rewrite(context, budget, indent));
52
53                 infix.push_str(separator);
54                 infix.push_str(&rewrite);
55             }
56
57             if self.init.is_some() {
58                 infix.push_str(" =");
59             }
60
61             infix
62         };
63
64         result.push_str(&infix);
65
66         if let Some(ref ex) = self.init {
67             let budget = try_opt!(width.checked_sub(context.block_indent.width() + 1));
68
69             // 1 = trailing semicolon;
70             result =
71                 try_opt!(rewrite_assign_rhs(&context, result, ex, budget, context.block_indent));
72         }
73
74         result.push(';');
75         Some(result)
76     }
77 }
78
79 impl<'a> FmtVisitor<'a> {
80     pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
81         let abi_str = ::utils::format_abi(fm.abi, self.config.force_explicit_abi);
82         self.buffer.push_str(&abi_str);
83
84         let snippet = self.snippet(span);
85         let brace_pos = snippet.find_uncommented("{").unwrap();
86
87         self.buffer.push_str("{");
88         if !fm.items.is_empty() || contains_comment(&snippet[brace_pos..]) {
89             // FIXME: this skips comments between the extern keyword and the opening
90             // brace.
91             self.last_pos = span.lo + BytePos(brace_pos as u32 + 1);
92             self.block_indent = self.block_indent.block_indent(self.config);
93
94             if fm.items.is_empty() {
95                 self.format_missing_no_indent(span.hi - BytePos(1));
96                 self.block_indent = self.block_indent.block_unindent(self.config);
97
98                 self.buffer.push_str(&self.block_indent.to_string(self.config));
99             } else {
100                 for item in &fm.items {
101                     self.format_foreign_item(&*item);
102                 }
103
104                 self.block_indent = self.block_indent.block_unindent(self.config);
105                 self.format_missing_with_indent(span.hi - BytePos(1));
106             }
107         }
108
109         self.buffer.push_str("}");
110         self.last_pos = span.hi;
111     }
112
113     fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
114         self.format_missing_with_indent(item.span.lo);
115         // Drop semicolon or it will be interpreted as comment.
116         // FIXME: this may be a faulty span from libsyntax.
117         let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
118
119         match item.node {
120             ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
121                 let indent = self.block_indent;
122                 let rewrite = rewrite_fn_base(&self.get_context(),
123                                               indent,
124                                               item.ident,
125                                               fn_decl,
126                                               generics,
127                                               ast::Unsafety::Normal,
128                                               ast::Constness::NotConst,
129                                               ast::Defaultness::Final,
130                                               // These are not actually rust functions,
131                                               // but we format them as such.
132                                               abi::Abi::Rust,
133                                               &item.vis,
134                                               span,
135                                               false,
136                                               false);
137
138                 match rewrite {
139                     Some((new_fn, _)) => {
140                         self.buffer.push_str(&new_fn);
141                         self.buffer.push_str(";");
142                     }
143                     None => self.format_missing(item.span.hi),
144                 }
145             }
146             ast::ForeignItemKind::Static(ref ty, is_mutable) => {
147                 // FIXME(#21): we're dropping potential comments in between the
148                 // function keywords here.
149                 let vis = format_visibility(&item.vis);
150                 let mut_str = if is_mutable { "mut " } else { "" };
151                 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
152                 let offset = self.block_indent + prefix.len();
153                 // 1 = ;
154                 let width = self.config.max_width - offset.width() - 1;
155                 let rewrite = ty.rewrite(&self.get_context(), width, offset);
156
157                 match rewrite {
158                     Some(result) => {
159                         self.buffer.push_str(&prefix);
160                         self.buffer.push_str(&result);
161                         self.buffer.push_str(";");
162                     }
163                     None => self.format_missing(item.span.hi),
164                 }
165             }
166         }
167
168         self.last_pos = item.span.hi;
169     }
170
171     pub fn rewrite_fn(&mut self,
172                       indent: Indent,
173                       ident: ast::Ident,
174                       fd: &ast::FnDecl,
175                       generics: &ast::Generics,
176                       unsafety: ast::Unsafety,
177                       constness: ast::Constness,
178                       defaultness: ast::Defaultness,
179                       abi: abi::Abi,
180                       vis: &ast::Visibility,
181                       span: Span,
182                       block: &ast::Block)
183                       -> Option<String> {
184         let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
185         let context = self.get_context();
186
187         let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
188         let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
189                        !context.config.fn_empty_single_line;
190
191         let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
192                                                                          indent,
193                                                                          ident,
194                                                                          fd,
195                                                                          generics,
196                                                                          unsafety,
197                                                                          constness,
198                                                                          defaultness,
199                                                                          abi,
200                                                                          vis,
201                                                                          span,
202                                                                          newline_brace,
203                                                                          has_body));
204
205         if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
206             newline_brace = false;
207         } else if force_newline_brace {
208             newline_brace = true;
209         }
210
211         // Prepare for the function body by possibly adding a newline and
212         // indent.
213         // FIXME we'll miss anything between the end of the signature and the
214         // start of the body, but we need more spans from the compiler to solve
215         // this.
216         if newline_brace {
217             result.push('\n');
218             result.push_str(&indent.to_string(self.config));
219         } else {
220             result.push(' ');
221         }
222
223         self.single_line_fn(&result, block).or_else(|| Some(result))
224     }
225
226     pub fn rewrite_required_fn(&mut self,
227                                indent: Indent,
228                                ident: ast::Ident,
229                                sig: &ast::MethodSig,
230                                span: Span)
231                                -> Option<String> {
232         // Drop semicolon or it will be interpreted as comment.
233         let span = mk_sp(span.lo, span.hi - BytePos(1));
234         let context = self.get_context();
235
236         let (mut result, _) = try_opt!(rewrite_fn_base(&context,
237                                                        indent,
238                                                        ident,
239                                                        &sig.decl,
240                                                        &sig.generics,
241                                                        sig.unsafety,
242                                                        sig.constness.node,
243                                                        ast::Defaultness::Final,
244                                                        sig.abi,
245                                                        &ast::Visibility::Inherited,
246                                                        span,
247                                                        false,
248                                                        false));
249
250         // Re-attach semicolon
251         result.push(';');
252
253         Some(result)
254     }
255
256     fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
257         if fn_str.contains('\n') {
258             return None;
259         }
260
261         let codemap = self.get_context().codemap;
262
263         if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
264            self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
265             return Some(format!("{}{{}}", fn_str));
266         }
267
268         if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
269             let rewrite = {
270                 if let Some(ref stmt) = block.stmts.first() {
271                     match stmt_expr(stmt) {
272                         Some(e) => {
273                             let suffix = if semicolon_for_expr(e) { ";" } else { "" };
274
275                             e.rewrite(&self.get_context(),
276                                          self.config.max_width - self.block_indent.width(),
277                                          self.block_indent)
278                                 .map(|s| s + suffix)
279                                 .or_else(|| Some(self.snippet(e.span)))
280                         }
281                         None => {
282                             stmt.rewrite(&self.get_context(),
283                                          self.config.max_width - self.block_indent.width(),
284                                          self.block_indent)
285                         }
286                     }
287                 } else {
288                     None
289                 }
290             };
291
292             if let Some(res) = rewrite {
293                 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
294                 if !res.contains('\n') && width <= self.config.max_width {
295                     return Some(format!("{}{{ {} }}", fn_str, res));
296                 }
297             }
298         }
299
300         None
301     }
302
303     pub fn visit_enum(&mut self,
304                       ident: ast::Ident,
305                       vis: &ast::Visibility,
306                       enum_def: &ast::EnumDef,
307                       generics: &ast::Generics,
308                       span: Span) {
309         self.buffer.push_str(&format_header("enum ", ident, vis));
310
311         let enum_snippet = self.snippet(span);
312         let brace_pos = enum_snippet.find_uncommented("{").unwrap();
313         let body_start = span.lo + BytePos(brace_pos as u32 + 1);
314         let generics_str = format_generics(&self.get_context(),
315                                            generics,
316                                            "{",
317                                            "{",
318                                            self.config.item_brace_style,
319                                            enum_def.variants.is_empty(),
320                                            self.block_indent,
321                                            self.block_indent.block_indent(self.config),
322                                            mk_sp(span.lo, body_start))
323             .unwrap();
324         self.buffer.push_str(&generics_str);
325
326         self.last_pos = body_start;
327
328         self.block_indent = self.block_indent.block_indent(self.config);
329         let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
330         match variant_list {
331             Some(ref body_str) => self.buffer.push_str(body_str),
332             None => {
333                 if contains_comment(&enum_snippet[brace_pos..]) {
334                     self.format_missing_no_indent(span.hi - BytePos(1))
335                 } else {
336                     self.format_missing(span.hi - BytePos(1))
337                 }
338             }
339         }
340         self.block_indent = self.block_indent.block_unindent(self.config);
341
342         if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
343             self.buffer.push_str(&self.block_indent.to_string(self.config));
344         }
345         self.buffer.push_str("}");
346         self.last_pos = span.hi;
347     }
348
349     // Format the body of an enum definition
350     fn format_variant_list(&self,
351                            enum_def: &ast::EnumDef,
352                            body_lo: BytePos,
353                            body_hi: BytePos)
354                            -> Option<String> {
355         if enum_def.variants.is_empty() {
356             return None;
357         }
358         let mut result = String::with_capacity(1024);
359         result.push('\n');
360         let indentation = self.block_indent.to_string(self.config);
361         result.push_str(&indentation);
362
363         let items = itemize_list(self.codemap,
364                                  enum_def.variants.iter(),
365                                  "}",
366                                  |f| if !f.node.attrs.is_empty() {
367                                      f.node.attrs[0].span.lo
368                                  } else {
369                                      f.span.lo
370                                  },
371                                  |f| f.span.hi,
372                                  |f| self.format_variant(f),
373                                  body_lo,
374                                  body_hi);
375
376         let budget = self.config.max_width - self.block_indent.width() - 2;
377         let fmt = ListFormatting {
378             tactic: DefinitiveListTactic::Vertical,
379             separator: ",",
380             trailing_separator: SeparatorTactic::from_bool(self.config.enum_trailing_comma),
381             indent: self.block_indent,
382             width: budget,
383             ends_with_newline: true,
384             config: self.config,
385         };
386
387         let list = try_opt!(write_list(items, &fmt));
388         result.push_str(&list);
389         result.push('\n');
390         Some(result)
391     }
392
393     // Variant of an enum.
394     fn format_variant(&self, field: &ast::Variant) -> Option<String> {
395         if contains_skip(&field.node.attrs) {
396             let lo = field.node.attrs[0].span.lo;
397             let span = mk_sp(lo, field.span.hi);
398             return Some(self.snippet(span));
399         }
400
401         let indent = self.block_indent;
402         let mut result = try_opt!(field.node
403             .attrs
404             .rewrite(&self.get_context(),
405                      self.config.max_width - indent.width(),
406                      indent));
407         if !result.is_empty() {
408             result.push('\n');
409             result.push_str(&indent.to_string(self.config));
410         }
411
412         let context = self.get_context();
413         let variant_body = match field.node.data {
414             ast::VariantData::Tuple(..) |
415             ast::VariantData::Struct(..) => {
416                 // FIXME: Should limit the width, as we have a trailing comma
417                 format_struct(&context,
418                               "",
419                               field.node.name,
420                               &ast::Visibility::Inherited,
421                               &field.node.data,
422                               None,
423                               field.span,
424                               indent,
425                               Some(self.config.struct_variant_width))
426             }
427             ast::VariantData::Unit(..) => {
428                 let tag = if let Some(ref expr) = field.node.disr_expr {
429                     format!("{} = {}", field.node.name, self.snippet(expr.span))
430                 } else {
431                     field.node.name.to_string()
432                 };
433
434                 wrap_str(tag,
435                          self.config.max_width,
436                          self.config.max_width - indent.width(),
437                          indent)
438             }
439         };
440
441         if let Some(variant_str) = variant_body {
442             result.push_str(&variant_str);
443             Some(result)
444         } else {
445             None
446         }
447     }
448 }
449
450 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
451     if let ast::ItemKind::Impl(_, _, ref generics, ref trait_ref, _, ref items) = item.node {
452         let mut result = String::new();
453
454         // First try to format the ref and type without a split at the 'for'.
455         let mut ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset, false));
456
457         // If there is a line break present in the first result format it again
458         // with a split at the 'for'. Skip this if there is no trait ref and
459         // therefore no 'for'.
460         if let Some(_) = *trait_ref {
461             if ref_and_type.contains('\n') {
462                 ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset, true));
463             }
464         }
465         result.push_str(&ref_and_type);
466
467         let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
468         let where_clause_str = try_opt!(rewrite_where_clause(context,
469                                                              &generics.where_clause,
470                                                              context.config,
471                                                              context.config.item_brace_style,
472                                                              context.block_indent,
473                                                              where_budget,
474                                                              context.config.where_density,
475                                                              "{",
476                                                              true,
477                                                              None));
478
479         if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
480             result.push_str(&where_clause_str);
481             if where_clause_str.contains('\n') {
482                 let white_space = offset.to_string(context.config);
483                 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
484             } else {
485                 result.push_str(" {}");
486             }
487             return Some(result);
488         }
489
490         if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
491             result.push('\n');
492             let width = context.block_indent.width() + context.config.tab_spaces - 1;
493             let where_indent = Indent::new(0, width);
494             result.push_str(&where_indent.to_string(context.config));
495         }
496         result.push_str(&where_clause_str);
497
498         match context.config.item_brace_style {
499             BraceStyle::AlwaysNextLine => {
500                 result.push('\n');
501                 result.push_str(&offset.to_string(context.config));
502             }
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
965     if context.config.spaces_within_parens && body.len() > 0 {
966         result.push(' ');
967     }
968
969     result.push_str(&body);
970
971     if context.config.spaces_within_parens && body.len() > 0 {
972         result.push(' ');
973     }
974
975     result.push(')');
976
977     if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
978        (result.contains('\n') ||
979         context.block_indent.width() + result.len() + where_clause_str.len() + 1 >
980         context.config.max_width) {
981         // We need to put the where clause on a new line, but we didn'to_string
982         // know that earlier, so the where clause will not be indented properly.
983         result.push('\n');
984         result.push_str(&(context.block_indent + (context.config.tab_spaces - 1))
985             .to_string(context.config));
986     }
987     result.push_str(&where_clause_str);
988
989     Some(result)
990 }
991
992 pub fn rewrite_type_alias(context: &RewriteContext,
993                           indent: Indent,
994                           ident: ast::Ident,
995                           ty: &ast::Ty,
996                           generics: &ast::Generics,
997                           vis: &ast::Visibility,
998                           span: Span)
999                           -> Option<String> {
1000     let mut result = String::new();
1001
1002     result.push_str(&format_visibility(vis));
1003     result.push_str("type ");
1004     result.push_str(&ident.to_string());
1005
1006     let generics_indent = indent + result.len();
1007     let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1008     let generics_width = context.config.max_width - " =".len();
1009     let generics_str = try_opt!(rewrite_generics(context,
1010                                                  generics,
1011                                                  indent,
1012                                                  generics_width,
1013                                                  generics_indent,
1014                                                  generics_span));
1015
1016     result.push_str(&generics_str);
1017
1018     let where_budget = try_opt!(context.config
1019         .max_width
1020         .checked_sub(last_line_width(&result)));
1021     let where_clause_str = try_opt!(rewrite_where_clause(context,
1022                                                          &generics.where_clause,
1023                                                          context.config,
1024                                                          context.config.item_brace_style,
1025                                                          indent,
1026                                                          where_budget,
1027                                                          context.config.where_density,
1028                                                          "=",
1029                                                          false,
1030                                                          Some(span.hi)));
1031     result.push_str(&where_clause_str);
1032     result.push_str(" = ");
1033
1034     let line_width = last_line_width(&result);
1035     // This checked_sub may fail as the extra space after '=' is not taken into account
1036     // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1037     let budget = context.config
1038         .max_width
1039         .checked_sub(indent.width() + line_width + ";".len())
1040         .unwrap_or(0);
1041     let type_indent = indent + line_width;
1042     // Try to fit the type on the same line
1043     let ty_str = try_opt!(ty.rewrite(context, budget, type_indent)
1044         .or_else(|| {
1045             // The line was too short, try to put the type on the next line
1046
1047             // Remove the space after '='
1048             result.pop();
1049             let type_indent = indent.block_indent(context.config);
1050             result.push('\n');
1051             result.push_str(&type_indent.to_string(context.config));
1052             let budget = try_opt!(context.config
1053                 .max_width
1054                 .checked_sub(type_indent.width() + ";".len()));
1055             ty.rewrite(context, budget, type_indent)
1056         }));
1057     result.push_str(&ty_str);
1058     result.push_str(";");
1059     Some(result)
1060 }
1061
1062 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1063     (if config.space_before_type_annotation {
1064          " "
1065      } else {
1066          ""
1067      },
1068      if config.space_after_type_annotation_colon {
1069          " "
1070      } else {
1071          ""
1072      })
1073 }
1074
1075 impl Rewrite for ast::StructField {
1076     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1077         if contains_skip(&self.attrs) {
1078             let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
1079             return wrap_str(span, context.config.max_width, width, offset);
1080         }
1081
1082         let name = self.ident;
1083         let vis = format_visibility(&self.vis);
1084         let mut attr_str = try_opt!(self.attrs
1085             .rewrite(context, context.config.max_width - offset.width(), offset));
1086         if !attr_str.is_empty() {
1087             attr_str.push('\n');
1088             attr_str.push_str(&offset.to_string(context.config));
1089         }
1090
1091         let type_annotation_spacing = type_annotation_spacing(context.config);
1092         let result = match name {
1093             Some(name) => {
1094                 format!("{}{}{}{}:{}",
1095                         attr_str,
1096                         vis,
1097                         name,
1098                         type_annotation_spacing.0,
1099                         type_annotation_spacing.1)
1100             }
1101             None => format!("{}{}", attr_str, vis),
1102         };
1103
1104         let last_line_width = last_line_width(&result);
1105         let budget = try_opt!(width.checked_sub(last_line_width));
1106         let rewrite = try_opt!(self.ty.rewrite(context, budget, offset + last_line_width));
1107         Some(result + &rewrite)
1108     }
1109 }
1110
1111 pub fn rewrite_static(prefix: &str,
1112                       vis: &ast::Visibility,
1113                       ident: ast::Ident,
1114                       ty: &ast::Ty,
1115                       mutability: ast::Mutability,
1116                       expr_opt: Option<&ptr::P<ast::Expr>>,
1117                       context: &RewriteContext)
1118                       -> Option<String> {
1119     let type_annotation_spacing = type_annotation_spacing(context.config);
1120     let prefix = format!("{}{} {}{}{}:{}",
1121                          format_visibility(vis),
1122                          prefix,
1123                          format_mutability(mutability),
1124                          ident,
1125                          type_annotation_spacing.0,
1126                          type_annotation_spacing.1);
1127     // 2 = " =".len()
1128     let ty_str = try_opt!(ty.rewrite(context,
1129                                      context.config.max_width - context.block_indent.width() -
1130                                      prefix.len() - 2,
1131                                      context.block_indent));
1132
1133     if let Some(expr) = expr_opt {
1134         let lhs = format!("{}{} =", prefix, ty_str);
1135         // 1 = ;
1136         let remaining_width = context.config.max_width - context.block_indent.width() - 1;
1137         rewrite_assign_rhs(context, lhs, expr, remaining_width, context.block_indent)
1138             .map(|s| s + ";")
1139     } else {
1140         let lhs = format!("{}{};", prefix, ty_str);
1141         Some(lhs)
1142     }
1143 }
1144
1145 pub fn rewrite_associated_type(ident: ast::Ident,
1146                                ty_opt: Option<&ptr::P<ast::Ty>>,
1147                                ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1148                                context: &RewriteContext,
1149                                indent: Indent)
1150                                -> Option<String> {
1151     let prefix = format!("type {}", ident);
1152
1153     let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1154         let bounds: &[_] = ty_param_bounds;
1155         let bound_str = try_opt!(bounds.iter()
1156             .map(|ty_bound| ty_bound.rewrite(context, context.config.max_width, indent))
1157             .intersperse(Some(" + ".to_string()))
1158             .collect::<Option<String>>());
1159         if bounds.len() > 0 {
1160             format!(": {}", bound_str)
1161         } else {
1162             String::new()
1163         }
1164     } else {
1165         String::new()
1166     };
1167
1168     if let Some(ty) = ty_opt {
1169         let ty_str = try_opt!(ty.rewrite(context,
1170                                          context.config.max_width - context.block_indent.width() -
1171                                          prefix.len() -
1172                                          2,
1173                                          context.block_indent));
1174         Some(format!("{} = {};", prefix, ty_str))
1175     } else {
1176         Some(format!("{}{};", prefix, type_bounds_str))
1177     }
1178 }
1179
1180 impl Rewrite for ast::FunctionRetTy {
1181     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1182         match *self {
1183             ast::FunctionRetTy::Default(_) => Some(String::new()),
1184             ast::FunctionRetTy::Ty(ref ty) => {
1185                 let inner_width = try_opt!(width.checked_sub(3));
1186                 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1187             }
1188         }
1189     }
1190 }
1191
1192 impl Rewrite for ast::Arg {
1193     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1194         if is_named_arg(self) {
1195             let mut result = try_opt!(self.pat.rewrite(context, width, offset));
1196
1197             if self.ty.node != ast::TyKind::Infer {
1198                 if context.config.space_before_type_annotation {
1199                     result.push_str(" ");
1200                 }
1201                 result.push_str(":");
1202                 if context.config.space_after_type_annotation_colon {
1203                     result.push_str(" ");
1204                 }
1205                 let max_width = try_opt!(width.checked_sub(result.len()));
1206                 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1207                 result.push_str(&ty_str);
1208             }
1209
1210             Some(result)
1211         } else {
1212             self.ty.rewrite(context, width, offset)
1213         }
1214     }
1215 }
1216
1217 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1218                          args: &[ast::Arg],
1219                          context: &RewriteContext)
1220                          -> Option<String> {
1221     match explicit_self.node {
1222         ast::SelfKind::Region(lt, m) => {
1223             let mut_str = format_mutability(m);
1224             match lt {
1225                 Some(ref l) => {
1226                     let lifetime_str =
1227                         try_opt!(l.rewrite(context, usize::max_value(), Indent::empty()));
1228                     Some(format!("&{} {}self", lifetime_str, mut_str))
1229                 }
1230                 None => Some(format!("&{}self", mut_str)),
1231             }
1232         }
1233         ast::SelfKind::Explicit(ref ty, _) => {
1234             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1235
1236             let mutability = explicit_self_mutability(&args[0]);
1237             let type_str = try_opt!(ty.rewrite(context, usize::max_value(), Indent::empty()));
1238
1239             Some(format!("{}self: {}", format_mutability(mutability), type_str))
1240         }
1241         ast::SelfKind::Value(_) => {
1242             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1243
1244             let mutability = explicit_self_mutability(&args[0]);
1245
1246             Some(format!("{}self", format_mutability(mutability)))
1247         }
1248     }
1249 }
1250
1251 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1252 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1253 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1254     if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1255         mutability
1256     } else {
1257         unreachable!()
1258     }
1259 }
1260
1261 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1262     if is_named_arg(arg) {
1263         arg.pat.span.lo
1264     } else {
1265         arg.ty.span.lo
1266     }
1267 }
1268
1269 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1270     match arg.ty.node {
1271         ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1272         _ => arg.ty.span.hi,
1273     }
1274 }
1275
1276 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1277     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1278         ident.node != symbol::keywords::Invalid.ident()
1279     } else {
1280         true
1281     }
1282 }
1283
1284 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1285     match *ret {
1286         ast::FunctionRetTy::Default(ref span) => span.clone(),
1287         ast::FunctionRetTy::Ty(ref ty) => ty.span,
1288     }
1289 }
1290
1291 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1292     // Note that ty.span is the span for ty.ident, not the whole item.
1293     let lo = ty.span.lo;
1294     if let Some(ref def) = ty.default {
1295         return mk_sp(lo, def.span.hi);
1296     }
1297     if ty.bounds.is_empty() {
1298         return ty.span;
1299     }
1300     let hi = match ty.bounds[ty.bounds.len() - 1] {
1301         ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1302         ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1303     };
1304     mk_sp(lo, hi)
1305 }
1306
1307 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1308     match *pred {
1309         ast::WherePredicate::BoundPredicate(ref p) => p.span,
1310         ast::WherePredicate::RegionPredicate(ref p) => p.span,
1311         ast::WherePredicate::EqPredicate(ref p) => p.span,
1312     }
1313 }
1314
1315 // Return type is (result, force_new_line_for_brace)
1316 fn rewrite_fn_base(context: &RewriteContext,
1317                    indent: Indent,
1318                    ident: ast::Ident,
1319                    fd: &ast::FnDecl,
1320                    generics: &ast::Generics,
1321                    unsafety: ast::Unsafety,
1322                    constness: ast::Constness,
1323                    defaultness: ast::Defaultness,
1324                    abi: abi::Abi,
1325                    vis: &ast::Visibility,
1326                    span: Span,
1327                    newline_brace: bool,
1328                    has_body: bool)
1329                    -> Option<(String, bool)> {
1330     let mut force_new_line_for_brace = false;
1331     // FIXME we'll lose any comments in between parts of the function decl, but
1332     // anyone who comments there probably deserves what they get.
1333
1334     let where_clause = &generics.where_clause;
1335
1336     let mut result = String::with_capacity(1024);
1337     // Vis unsafety abi.
1338     result.push_str(&*format_visibility(vis));
1339
1340     if let ast::Defaultness::Default = defaultness {
1341         result.push_str("default ");
1342     }
1343
1344     if let ast::Constness::Const = constness {
1345         result.push_str("const ");
1346     }
1347
1348     result.push_str(::utils::format_unsafety(unsafety));
1349
1350     if abi != abi::Abi::Rust {
1351         result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi));
1352     }
1353
1354     // fn foo
1355     result.push_str("fn ");
1356     result.push_str(&ident.to_string());
1357
1358     // Generics.
1359     let generics_indent = indent + result.len();
1360     let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1361     let generics_str = try_opt!(rewrite_generics(context,
1362                                                  generics,
1363                                                  indent,
1364                                                  context.config.max_width,
1365                                                  generics_indent,
1366                                                  generics_span));
1367     result.push_str(&generics_str);
1368
1369     // Note that if the width and indent really matter, we'll re-layout the
1370     // return type later anyway.
1371     let ret_str = try_opt!(fd.output
1372         .rewrite(&context, context.config.max_width - indent.width(), indent));
1373
1374     let multi_line_ret_str = ret_str.contains('\n');
1375     let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1376
1377     // Args.
1378     let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1379         try_opt!(compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace));
1380
1381     if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1382        context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1383         arg_indent = indent.block_indent(context.config);
1384         multi_line_budget = context.config.max_width - arg_indent.width();
1385     }
1386
1387     debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1388            one_line_budget,
1389            multi_line_budget,
1390            arg_indent);
1391
1392     // Check if vertical layout was forced by compute_budget_for_args.
1393     if one_line_budget == 0 {
1394         if context.config.fn_args_paren_newline {
1395             result.push('\n');
1396             result.push_str(&arg_indent.to_string(context.config));
1397             arg_indent = arg_indent + 1; // extra space for `(`
1398             result.push('(');
1399             if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1400                 result.push(' ')
1401             }
1402         } else {
1403             result.push_str("(\n");
1404             result.push_str(&arg_indent.to_string(context.config));
1405         }
1406     } else {
1407         result.push('(');
1408         if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1409             result.push(' ')
1410         }
1411     }
1412
1413     if multi_line_ret_str {
1414         one_line_budget = 0;
1415     }
1416
1417     // A conservative estimation, to goal is to be over all parens in generics
1418     let args_start = generics.ty_params
1419         .last()
1420         .map_or(span.lo, |tp| end_typaram(tp));
1421     let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1422                           span_for_return(&fd.output).lo);
1423     let arg_str = try_opt!(rewrite_args(context,
1424                                         &fd.inputs,
1425                                         fd.get_self().as_ref(),
1426                                         one_line_budget,
1427                                         multi_line_budget,
1428                                         indent,
1429                                         arg_indent,
1430                                         args_span,
1431                                         fd.variadic));
1432
1433     let multi_line_arg_str = arg_str.contains('\n');
1434
1435     let put_args_in_block = match context.config.fn_args_layout {
1436         FnArgLayoutStyle::Block => multi_line_arg_str,
1437         FnArgLayoutStyle::BlockAlways => true,
1438         _ => false,
1439     } && !fd.inputs.is_empty();
1440
1441     if put_args_in_block {
1442         arg_indent = indent.block_indent(context.config);
1443         result.push('\n');
1444         result.push_str(&arg_indent.to_string(context.config));
1445         result.push_str(&arg_str);
1446         result.push('\n');
1447         result.push_str(&indent.to_string(context.config));
1448         result.push(')');
1449     } else {
1450         result.push_str(&arg_str);
1451         if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1452             result.push(' ')
1453         }
1454         result.push(')');
1455     }
1456
1457     // Return type.
1458     if !ret_str.is_empty() {
1459         let ret_should_indent = match context.config.fn_args_layout {
1460             // If our args are block layout then we surely must have space.
1461             FnArgLayoutStyle::Block if put_args_in_block => false,
1462             FnArgLayoutStyle::BlockAlways => false,
1463             _ => {
1464                 // If we've already gone multi-line, or the return type would push over the max
1465                 // width, then put the return type on a new line. With the +1 for the signature
1466                 // length an additional space between the closing parenthesis of the argument and
1467                 // the arrow '->' is considered.
1468                 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1469
1470                 // If there is no where clause, take into account the space after the return type
1471                 // and the brace.
1472                 if where_clause.predicates.is_empty() {
1473                     sig_length += 2;
1474                 }
1475
1476                 let overlong_sig = sig_length > context.config.max_width;
1477
1478                 result.contains('\n') || multi_line_ret_str || overlong_sig
1479             }
1480         };
1481         let ret_indent = if ret_should_indent {
1482             let indent = match context.config.fn_return_indent {
1483                 ReturnIndent::WithWhereClause => indent + 4,
1484                 // Aligning with non-existent args looks silly.
1485                 _ if arg_str.is_empty() => {
1486                     force_new_line_for_brace = true;
1487                     indent + 4
1488                 }
1489                 // FIXME: we might want to check that using the arg indent
1490                 // doesn't blow our budget, and if it does, then fallback to
1491                 // the where clause indent.
1492                 _ => arg_indent,
1493             };
1494
1495             result.push('\n');
1496             result.push_str(&indent.to_string(context.config));
1497             indent
1498         } else {
1499             result.push(' ');
1500             Indent::new(indent.width(), result.len())
1501         };
1502
1503         if multi_line_ret_str {
1504             // Now that we know the proper indent and width, we need to
1505             // re-layout the return type.
1506             let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1507             let ret_str = try_opt!(fd.output.rewrite(context, budget, ret_indent));
1508             result.push_str(&ret_str);
1509         } else {
1510             result.push_str(&ret_str);
1511         }
1512
1513         // Comment between return type and the end of the decl.
1514         let snippet_lo = fd.output.span().hi;
1515         if where_clause.predicates.is_empty() {
1516             let snippet_hi = span.hi;
1517             let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1518             let snippet = snippet.trim();
1519             if !snippet.is_empty() {
1520                 result.push(' ');
1521                 result.push_str(snippet);
1522             }
1523         } else {
1524             // FIXME it would be nice to catch comments between the return type
1525             // and the where clause, but we don't have a span for the where
1526             // clause.
1527         }
1528     }
1529
1530     let should_compress_where = match context.config.where_density {
1531         Density::Compressed => !result.contains('\n') || put_args_in_block,
1532         Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1533         _ => false,
1534     } || (put_args_in_block && ret_str.is_empty());
1535
1536     let where_density = if should_compress_where {
1537         Density::Compressed
1538     } else {
1539         Density::Tall
1540     };
1541
1542     // Where clause.
1543     let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1544     let where_clause_str = try_opt!(rewrite_where_clause(context,
1545                                                          where_clause,
1546                                                          context.config,
1547                                                          context.config.fn_brace_style,
1548                                                          indent,
1549                                                          where_budget,
1550                                                          where_density,
1551                                                          "{",
1552                                                          has_body,
1553                                                          Some(span.hi)));
1554
1555     if last_line_width(&result) + where_clause_str.len() > context.config.max_width &&
1556        !where_clause_str.contains('\n') {
1557         result.push('\n');
1558     }
1559
1560     result.push_str(&where_clause_str);
1561
1562     Some((result, force_new_line_for_brace))
1563 }
1564
1565 fn rewrite_args(context: &RewriteContext,
1566                 args: &[ast::Arg],
1567                 explicit_self: Option<&ast::ExplicitSelf>,
1568                 one_line_budget: usize,
1569                 multi_line_budget: usize,
1570                 indent: Indent,
1571                 arg_indent: Indent,
1572                 span: Span,
1573                 variadic: bool)
1574                 -> Option<String> {
1575     let mut arg_item_strs = try_opt!(args.iter()
1576         .map(|arg| arg.rewrite(&context, multi_line_budget, arg_indent))
1577         .collect::<Option<Vec<_>>>());
1578
1579     // Account for sugary self.
1580     // FIXME: the comment for the self argument is dropped. This is blocked
1581     // on rust issue #27522.
1582     let min_args =
1583         explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1584             .map_or(1, |self_str| {
1585                 arg_item_strs[0] = self_str;
1586                 2
1587             });
1588
1589     // Comments between args.
1590     let mut arg_items = Vec::new();
1591     if min_args == 2 {
1592         arg_items.push(ListItem::from_str(""));
1593     }
1594
1595     // FIXME(#21): if there are no args, there might still be a comment, but
1596     // without spans for the comment or parens, there is no chance of
1597     // getting it right. You also don't get to put a comment on self, unless
1598     // it is explicit.
1599     if args.len() >= min_args || variadic {
1600         let comment_span_start = if min_args == 2 {
1601             let second_arg_start = if arg_has_pattern(&args[1]) {
1602                 args[1].pat.span.lo
1603             } else {
1604                 args[1].ty.span.lo
1605             };
1606             let reduced_span = mk_sp(span.lo, second_arg_start);
1607
1608             context.codemap.span_after_last(reduced_span, ",")
1609         } else {
1610             span.lo
1611         };
1612
1613         enum ArgumentKind<'a> {
1614             Regular(&'a ast::Arg),
1615             Variadic(BytePos),
1616         }
1617
1618         let variadic_arg = if variadic {
1619             let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1620             let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1621             Some(ArgumentKind::Variadic(variadic_start))
1622         } else {
1623             None
1624         };
1625
1626         let more_items = itemize_list(context.codemap,
1627                                       args[min_args - 1..]
1628                                           .iter()
1629                                           .map(ArgumentKind::Regular)
1630                                           .chain(variadic_arg),
1631                                       ")",
1632                                       |arg| match *arg {
1633                                           ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1634                                           ArgumentKind::Variadic(start) => start,
1635                                       },
1636                                       |arg| match *arg {
1637                                           ArgumentKind::Regular(arg) => arg.ty.span.hi,
1638                                           ArgumentKind::Variadic(start) => start + BytePos(3),
1639                                       },
1640                                       |arg| match *arg {
1641                                           ArgumentKind::Regular(..) => None,
1642                                           ArgumentKind::Variadic(..) => Some("...".to_owned()),
1643                                       },
1644                                       comment_span_start,
1645                                       span.hi);
1646
1647         arg_items.extend(more_items);
1648     }
1649
1650     for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1651         item.item = Some(arg);
1652     }
1653
1654     let indent = match context.config.fn_arg_indent {
1655         BlockIndentStyle::Inherit => indent,
1656         BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1657         BlockIndentStyle::Visual => arg_indent,
1658     };
1659
1660     let tactic = definitive_tactic(&arg_items,
1661                                    context.config.fn_args_density.to_list_tactic(),
1662                                    one_line_budget);
1663     let budget = match tactic {
1664         DefinitiveListTactic::Horizontal => one_line_budget,
1665         _ => multi_line_budget,
1666     };
1667
1668     debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1669
1670     let end_with_newline = match context.config.fn_args_layout {
1671         FnArgLayoutStyle::Block |
1672         FnArgLayoutStyle::BlockAlways => true,
1673         _ => false,
1674     };
1675
1676     let fmt = ListFormatting {
1677         tactic: tactic,
1678         separator: ",",
1679         trailing_separator: SeparatorTactic::Never,
1680         indent: indent,
1681         width: budget,
1682         ends_with_newline: end_with_newline,
1683         config: context.config,
1684     };
1685
1686     write_list(&arg_items, &fmt)
1687 }
1688
1689 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1690     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1691         ident.node != symbol::keywords::Invalid.ident()
1692     } else {
1693         true
1694     }
1695 }
1696
1697 fn compute_budgets_for_args(context: &RewriteContext,
1698                             result: &str,
1699                             indent: Indent,
1700                             ret_str_len: usize,
1701                             newline_brace: bool)
1702                             -> Option<((usize, usize, Indent))> {
1703     // Try keeping everything on the same line.
1704     if !result.contains('\n') {
1705         // 3 = `() `, space is before ret_string.
1706         let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1707         if !newline_brace {
1708             used_space += 2;
1709         }
1710         let one_line_budget = context.config.max_width.checked_sub(used_space).unwrap_or(0);
1711
1712         if one_line_budget > 0 {
1713             // 4 = "() {".len()
1714             let multi_line_budget =
1715                 try_opt!(context.config.max_width.checked_sub(indent.width() + result.len() + 4));
1716
1717             return Some((one_line_budget, multi_line_budget, indent + result.len() + 1));
1718         }
1719     }
1720
1721     // Didn't work. we must force vertical layout and put args on a newline.
1722     let new_indent = indent.block_indent(context.config);
1723     let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`.
1724     let max_space = context.config.max_width;
1725     if used_space <= max_space {
1726         Some((0, max_space - used_space, new_indent))
1727     } else {
1728         // Whoops! bankrupt.
1729         None
1730     }
1731 }
1732
1733 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1734     match config.fn_brace_style {
1735         BraceStyle::AlwaysNextLine => true,
1736         BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1737         _ => false,
1738     }
1739 }
1740
1741 fn rewrite_generics(context: &RewriteContext,
1742                     generics: &ast::Generics,
1743                     offset: Indent,
1744                     width: usize,
1745                     generics_offset: Indent,
1746                     span: Span)
1747                     -> Option<String> {
1748     // FIXME: convert bounds to where clauses where they get too big or if
1749     // there is a where clause at all.
1750     let lifetimes: &[_] = &generics.lifetimes;
1751     let tys: &[_] = &generics.ty_params;
1752     if lifetimes.is_empty() && tys.is_empty() {
1753         return Some(String::new());
1754     }
1755
1756     let offset = match context.config.generics_indent {
1757         BlockIndentStyle::Inherit => offset,
1758         BlockIndentStyle::Tabbed => offset.block_indent(context.config),
1759         // 1 = <
1760         BlockIndentStyle::Visual => generics_offset + 1,
1761     };
1762
1763     let h_budget = try_opt!(width.checked_sub(generics_offset.width() + 2));
1764     // FIXME: might need to insert a newline if the generics are really long.
1765
1766     // Strings for the generics.
1767     let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, h_budget, offset));
1768     let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(context, h_budget, offset));
1769
1770     // Extract comments between generics.
1771     let lt_spans = lifetimes.iter().map(|l| {
1772         let hi = if l.bounds.is_empty() {
1773             l.lifetime.span.hi
1774         } else {
1775             l.bounds[l.bounds.len() - 1].span.hi
1776         };
1777         mk_sp(l.lifetime.span.lo, hi)
1778     });
1779     let ty_spans = tys.iter().map(span_for_ty_param);
1780
1781     let items = itemize_list(context.codemap,
1782                              lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1783                              ">",
1784                              |&(sp, _)| sp.lo,
1785                              |&(sp, _)| sp.hi,
1786                              // FIXME: don't clone
1787                              |&(_, ref str)| str.clone(),
1788                              context.codemap.span_after(span, "<"),
1789                              span.hi);
1790     let list_str = try_opt!(format_item_list(items, h_budget, offset, context.config));
1791
1792     Some(if context.config.spaces_within_angle_brackets {
1793         format!("< {} >", list_str)
1794     } else {
1795         format!("<{}>", list_str)
1796     })
1797 }
1798
1799 fn rewrite_trait_bounds(context: &RewriteContext,
1800                         type_param_bounds: &ast::TyParamBounds,
1801                         indent: Indent,
1802                         width: usize)
1803                         -> Option<String> {
1804     let bounds: &[_] = type_param_bounds;
1805
1806     if bounds.is_empty() {
1807         return Some(String::new());
1808     }
1809
1810     let bound_str = try_opt!(bounds.iter()
1811         .map(|ty_bound| ty_bound.rewrite(&context, width, indent))
1812         .intersperse(Some(" + ".to_string()))
1813         .collect::<Option<String>>());
1814
1815     let mut result = String::new();
1816     result.push_str(": ");
1817     result.push_str(&bound_str);
1818     Some(result)
1819 }
1820
1821 fn rewrite_where_clause(context: &RewriteContext,
1822                         where_clause: &ast::WhereClause,
1823                         config: &Config,
1824                         brace_style: BraceStyle,
1825                         indent: Indent,
1826                         width: usize,
1827                         density: Density,
1828                         terminator: &str,
1829                         allow_trailing_comma: bool,
1830                         span_end: Option<BytePos>)
1831                         -> Option<String> {
1832     if where_clause.predicates.is_empty() {
1833         return Some(String::new());
1834     }
1835
1836     let extra_indent = match context.config.where_indent {
1837         BlockIndentStyle::Inherit => Indent::empty(),
1838         BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces, 0),
1839     };
1840
1841     let offset = match context.config.where_pred_indent {
1842         BlockIndentStyle::Inherit => indent + extra_indent,
1843         BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
1844         // 6 = "where ".len()
1845         BlockIndentStyle::Visual => indent + extra_indent + 6,
1846     };
1847     // FIXME: if where_pred_indent != Visual, then the budgets below might
1848     // be out by a char or two.
1849
1850     let budget = context.config.max_width - offset.width();
1851     let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1852     // If we don't have the start of the next span, then use the end of the
1853     // predicates, but that means we miss comments.
1854     let len = where_clause.predicates.len();
1855     let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1856     let span_end = span_end.unwrap_or(end_of_preds);
1857     let items = itemize_list(context.codemap,
1858                              where_clause.predicates.iter(),
1859                              terminator,
1860                              |pred| span_for_where_pred(pred).lo,
1861                              |pred| span_for_where_pred(pred).hi,
1862                              |pred| pred.rewrite(context, budget, offset),
1863                              span_start,
1864                              span_end);
1865     let item_vec = items.collect::<Vec<_>>();
1866     // FIXME: we don't need to collect here if the where_layout isn't
1867     // HorizontalVertical.
1868     let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
1869     let use_trailing_comma = allow_trailing_comma && context.config.where_trailing_comma;
1870
1871     let fmt = ListFormatting {
1872         tactic: tactic,
1873         separator: ",",
1874         trailing_separator: SeparatorTactic::from_bool(use_trailing_comma),
1875         indent: offset,
1876         width: budget,
1877         ends_with_newline: true,
1878         config: context.config,
1879     };
1880     let preds_str = try_opt!(write_list(&item_vec, &fmt));
1881
1882     let end_length = if terminator == "{" {
1883         // If the brace is on the next line we don't need to count it otherwise it needs two
1884         // characters " {"
1885         match brace_style {
1886             BraceStyle::AlwaysNextLine |
1887             BraceStyle::SameLineWhere => 0,
1888             BraceStyle::PreferSameLine => 2,
1889         }
1890     } else if terminator == "=" {
1891         2
1892     } else {
1893         terminator.len()
1894     };
1895     if density == Density::Tall || preds_str.contains('\n') ||
1896        indent.width() + " where ".len() + preds_str.len() + end_length > width {
1897         Some(format!("\n{}where {}",
1898                      (indent + extra_indent).to_string(context.config),
1899                      preds_str))
1900     } else {
1901         Some(format!(" where {}", preds_str))
1902     }
1903 }
1904
1905 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1906     format!("{}{}{}", format_visibility(vis), item_name, ident)
1907 }
1908
1909 fn format_generics(context: &RewriteContext,
1910                    generics: &ast::Generics,
1911                    opener: &str,
1912                    terminator: &str,
1913                    brace_style: BraceStyle,
1914                    force_same_line_brace: bool,
1915                    offset: Indent,
1916                    generics_offset: Indent,
1917                    span: Span)
1918                    -> Option<String> {
1919     let mut result = try_opt!(rewrite_generics(context,
1920                                                generics,
1921                                                offset,
1922                                                context.config.max_width,
1923                                                generics_offset,
1924                                                span));
1925
1926     if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
1927         let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1928         let where_clause_str = try_opt!(rewrite_where_clause(context,
1929                                                              &generics.where_clause,
1930                                                              context.config,
1931                                                              brace_style,
1932                                                              context.block_indent,
1933                                                              budget,
1934                                                              Density::Tall,
1935                                                              terminator,
1936                                                              true,
1937                                                              Some(span.hi)));
1938         result.push_str(&where_clause_str);
1939         if !force_same_line_brace &&
1940            (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
1941             result.push('\n');
1942             result.push_str(&context.block_indent.to_string(context.config));
1943         } else {
1944             result.push(' ');
1945         }
1946         result.push_str(opener);
1947     } else {
1948         if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
1949             result.push('\n');
1950             result.push_str(&context.block_indent.to_string(context.config));
1951         } else {
1952             result.push(' ');
1953         }
1954         result.push_str(opener);
1955     }
1956
1957     Some(result)
1958 }