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