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