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