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