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