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